Teach you how to quickly replace iOS project application icons with Python

I wrote a simple script to automatically replace the Icon image resources in the iOS project and record the complete process. Children’s shoes who want to try it can refer to it.

1. Preparation

It’s hard to make a meal without rice. As a programmer, without , how can we create ?

So first, we need to configure the Python environment

It is recommended to use pyenv to install and switch between different versions, as well as configure the virtual environment. Usage reference

Use the pip tool to complete the functions of searching, downloading, installing and uninstalling the Python package. Usage reference

You can freely choose development tools. I use vscode.

2. Goal analysis and step split

First, let’s make it clear that our goal is to set an incoming picture as an icons resource for an iOS project.

  • The first step is to get the path of an image and determine whether it is 1024*1024 size (project image requirements)

To set the icons resource of the iOS project, you need to store the picture with specified size pixels required by the project to the corresponding path, and configure the description file.

  • In the second step, we need to compress the original image into images of various sizes.

  • The third step is to store these images under the specified path. If they already exist, replace them directly.

  • The fourth step is to configure the description file

Next let’s take a look at the specific implementation

3. Implementation

1. Depend on header file import

import sys
import shutil
import json
import os

The tool library provided by the system can be introduced directly as above. The third-party library needs to be downloaded using pip first (note that if you use a virtual environment, you need to download it in the corresponding environment, otherwise there will be unrecognized problems. )

pip install Pillow

Then import the header file

from PIL import Image

2. Source image reading

Determine png format

def is_png_file(file_name):
    if file_name.endswith(".png"):
        return True
    else:
        return False

Get the image size and determine whether the size is 1024*1024

def check_image_size_1024(image_path):
    try:
        with Image.open(image_path) as img:
            width, height = img.size
            return width == 1024 and height == 1024
    exceptIOError:
        print(f"Unable to open or read image file: {image_path}")
        return False

3. Image compression

try:
    with Image.open(input_path) as img:
        # Get the original size of the image
        original_width, original_height = img.size

        # Calculate the scaling ratio of the target size
        ratio = min(target_size[0] / original_width, target_size[1] / original_height)

        # Calculate the adjusted size
        new_width = int(original_width * ratio)
        new_height = int(original_height * ratio)

        #Adjust image size
        resized_img = img.resize((new_width, new_height), Image.LANCZOS)
    exceptIOError:
        print(f"Unable to open or read image file: {input_path}")
    except Exception as e:
        print(f"An error occurred while processing the image: {e}")

4. Write the picture and replace it if it exists

targetImageSize = imageSizeInfo[0] * imageSizeInfo[1]
targetImageSuffix = ".png" if imageSizeInfo[1] == 1 else "@{0}x.png".format(imageSizeInfo[1])
targetIconName = '{0}-iphone{1}'.format(imageSizeInfo[0],targetImageSuffix)
targetIconPath = os.path.join(targetAppIconAssetsPath, targetIconName)
resized_img.save(targetIconPath)

Note that you need to process all the images required for the corresponding iPhone, iPad, and AppStore at once.

5. Modification of picture description file

Description file content reading

targetAppIconAssetsJsonPath = os.path.join(targetAppIconAssetsPath, "Contents.json")
with open(targetAppIconAssetsJsonPath, "r + ") as file:
    contents = file.read()
jsonData = json.loads(contents)

Image configuration information content, each image needs to be configured

newImagesJsonInfo = []
newImagesJsonInfo.append({
            "size" : '{0}x{1}'.format(imageSizeInfo[0],imageSizeInfo[0]),
            "idiom" : "ipad",
            "filename" : targetIconName,
            "scale" : "{}x".format(imageSizeInfo[1]),
            })
            ...
            ...

Modify the configuration file content and store it

jsonData['images'] = newImagesJsonInfo
modified_content = json.dumps(jsonData, indent=2)
with open(targetAppIconAssetsJsonPath, "w") as file:
    file.write(modified_content)

In this way, the icon resources have been configured.

4. Command line configuration

You can use the shuttle tool to complete the configuration and trigger it with one click.

Add a new method for triggering scripts in the .libsonnet file for calls by the .jsonnet file

//Replace project icons
replaceXcodeIconsCommand(
    script_path,
    iOS_project_path,
    inTerminal='new',
):: {
    local name = 'Change AppIcon',
    local title = 'Replace project Icons',
    cmd: "cd %s; python auto_replace_icon.py -p %s" % [script_path, iOS_project_path],
    inTerminal: inTerminal,
    name: name,
    title: title,
},

In the above method, pass in the shuttle code path and the project path that needs to be replaced.

Then add the trigger event in the .jsonnet file where you want it.


———————————END——————- ——–

Digression

In this era of big data, how can you keep up with scripting without mastering a programming language? Python, the hottest programming language at the moment, has a bright future! If you also want to keep up with the times and improve yourself, please take a look.

Interested friends will receive a complete set of Python learning materials, including interview questions, resume information, etc. See below for details.

CSDN gift package:The most complete “Python learning materials” on the Internet are given away for free! (Safe link, click with confidence)

1. Python learning routes in all directions

The technical points in all directions of Python have been compiled to form a summary of knowledge points in various fields. Its usefulness is that you can find corresponding learning resources according to the following knowledge points to ensure that you learn more comprehensively.

img
img

2. Essential development tools for Python

The tools have been organized for you, and you can get started directly after installation! img

3. Latest Python study notes

When I learn a certain basic and have my own understanding ability, I will read some books or handwritten notes compiled by my seniors. These notes record their understanding of some technical points in detail. These understandings are relatively unique and can be learned. to a different way of thinking.

img

4. Python video collection

Watch a comprehensive zero-based learning video. Watching videos is the fastest and most effective way to learn. It is easy to get started by following the teacher’s ideas in the video, from basic to in-depth.

img

5. Practical cases

What you learn on paper is ultimately shallow. You must learn to type along with the video and practice it in order to apply what you have learned into practice. At this time, you can learn from some practical cases. img

6. Interview Guide

Resume template