Python 一键生成所有尺寸的应用Ico图标

项目介绍

在开发软件或网站时,我们经常需要为应用程序或网站设计专属的icon图标。我们将通过Python脚本一键生成iOS所有尺寸的应用图标,省时省力。

编译环境

Python版本:python3.8

制作应用尺寸配置文件

1. 将所有尺寸的图片配置在iconContentsConfig.json文件中

{
    "images": [
        {
            "size": "20x20",
            "idiom": "iphone",
            "filename": "icon-20@2x.png",
            "scale": "2x"
        },
        {
            "size": "20x20",
            "idiom": "iphone",
            "filename": "icon-20@3x.png",
            "scale": "3x"
        },
        {
            "size": "29x29",
            "idiom": "iphone",
            "filename": "icon-29.png",
            "scale": "1x"
        },
        {
            "size": "29x29",
            "idiom": "iphone",
            "filename": "icon-29@2x.png",
            "scale": "2x"
        },
        {
            "size": "29x29",
            "idiom": "iphone",
            "filename": "icon-29@3x.png",
            "scale": "3x"
        },
        {
            "size": "40x40",
            "idiom": "iphone",
            "filename": "icon-40@2x.png",
            "scale": "2x"
        },
        {
            "size": "40x40",
            "idiom": "iphone",
            "filename": "icon-40@3x.png",
            "scale": "3x"
        },
        {
            "size": "60x60",
            "idiom": "iphone",
            "filename": "icon-60@2x.png",
            "scale": "2x"
        },
        {
            "size": "60x60",
            "idiom": "iphone",
            "filename": "icon-60@3x.png",
            "scale": "3x"
        },
        {
            "size": "20x20",
            "idiom": "ipad",
            "filename": "icon-20-ipad.png",
            "scale": "1x"
        },
        {
            "size": "20x20",
            "idiom": "ipad",
            "filename": "icon-20@2x-ipad.png",
            "scale": "2x"
        },
        {
            "size": "29x29",
            "idiom": "ipad",
            "filename": "icon-29-ipad.png",
            "scale": "1x"
        },
        {
            "size": "29x29",
            "idiom": "ipad",
            "filename": "icon-29@2x-ipad.png",
            "scale": "2x"
        },
        {
            "size": "40x40",
            "idiom": "ipad",
            "filename": "icon-40.png",
            "scale": "1x"
        },
        {
            "size": "40x40",
            "idiom": "ipad",
            "filename": "icon-40@2x.png",
            "scale": "2x"
        },
        {
            "size": "76x76",
            "idiom": "ipad",
            "filename": "icon-76.png",
            "scale": "1x"
        },
        {
            "size": "76x76",
            "idiom": "ipad",
            "filename": "icon-76@2x.png",
            "scale": "2x"
        },
        {
            "size": "83.5x83.5",
            "idiom": "ipad",
            "filename": "icon-83.5@2x.png",
            "scale": "2x"
        },
        {
            "size": "1024x1024",
            "idiom": "ios-marketing",
            "filename": "icon-1024.png",
            "scale": "1x"
        }
    ],
    # 旧icon尺寸
    "oldImages": [
        {
            "size": "50x50",
            "idiom": "ipad",
            "filename": "icon-50.png",
            "scale": "1x"
        },
        {
            "size": "50x50",
            "idiom": "ipad",
            "filename": "icon-50@2x.png",
            "scale": "2x"
        },
        {
            "size": "72x72",
            "idiom": "ipad",
            "filename": "icon-72.png",
            "scale": "1x"
        },
        {
            "size": "72x72",
            "idiom": "ipad",
            "filename": "icon-72@2x.png",
            "scale": "2x"
        },
        {
            "size": "57x57",
            "idiom": "iphone",
            "filename": "icon-57.png",
            "scale": "1x"
        },
        {
            "size": "57x57",
            "idiom": "iphone",
            "filename": "icon-57@2x.png",
            "scale": "2x"
        }
    ],
    "info": {
        "version": 1,
        "author": "xcode"
    }
}

2. 读取json文件并转成字典

在Python中,我们可以使用json模块来处理json数据。下面是一个简单的示例,演示了如何读取一个名为iconContentsConfig.json的json文件,并将其转换成字典格式。

import 
configFile = open('iconContentsConfig.json')
data = json.load(configFile)
configFile.close()
importIconSizeDataDic = data
importIconSizeArr = data['images']
importIconSizeOldArr = data['oldImages']

3. 遍历获取图片的尺寸和名称

# 图片存放路径
imagesNewSavePath = imagesSavePath + "ios/AppIcon.appiconset/"
if not os.path.exists(imagesNewSavePath):
    os.makedirs(imagesNewSavePath)
# 判断是否添加旧尺寸图片
if isOldImageSize:
    importIconSizeArr = importIconSizeArr + importIconSizeOldArr
else:
    importIconSizeArr = importIconSizeArr
for importIconSizeDict in importIconSizeArr:
    iconSize = float(importIconSizeDict["size"].split("x")[0])
    iconFileName = importIconSizeDict["filename"]
    iconScale = float(importIconSizeDict["scale"].split("x")[0])
    # 获取指定尺寸图片
    scaleImage(imagePath, imagesNewSavePath, (int(iconSize * iconScale), int(iconSize * iconScale)), iconFileName)

4.生成指定尺寸图片

def scaleImage(image_path, image_new_path, img_size_1x=(0, 0), img_target_name=""):
    # 自定义宽高
    custom_wid_1x = img_size_1x[0]
    custom_hei_1x = img_size_1x[1]
    # 原图
    image_ori = Image.open(image_path)
    # 图片名
    image_name = image_path.split('/')[-1].split('.')[-2]
    # 图片的类型
    image_type = image_path.split('/')[-1].split('.')[-1]
    if custom_wid_1x != 0 and custom_hei_1x != 0:
    	# 获取指定尺寸的图片
        image_new = image_ori.resize(img_size_1x, Image.BILINEAR)
        if img_target_name == "":
            image_new_path_x = '%s%s_%sx%s.%s' % (image_new_path, image_name, str(custom_wid_1x),
                                                  str(custom_hei_1x), image_type)
        else:
            image_new_path_x = '%s%s' % (image_new_path, img_target_name)
        image_new.save(image_new_path_x)
        # image_new.save(image_new_path_x, image_type.upper())
        print("[ImageDealProcess OK] " + image_new_path_x + "已完成")
        return True
    else:
        print(image_name + " -- 提供尺寸格式不正确。")
        return False

⭐️如果对你有用的话,希望可以点点赞,感谢了⭐️

完整代码

import json
import os
import shutil

from PIL import Image


def scaleImage(image_path, image_new_path, img_size_1x=(0, 0), img_target_name=""):
    # 自定义宽高
    custom_wid_1x = img_size_1x[0]
    custom_hei_1x = img_size_1x[1]
    # 原图
    image_ori = Image.open(image_path)
    # 图片名
    image_name = image_path.split('/')[-1].split('.')[-2]
    # 图片的类型
    image_type = image_path.split('/')[-1].split('.')[-1]
    if custom_wid_1x != 0 and custom_hei_1x != 0:
        image_new = image_ori.resize(img_size_1x, Image.BILINEAR)
        if img_target_name == "":
            image_new_path_x = '%s%s_%sx%s.%s' % (image_new_path, image_name, str(custom_wid_1x),
                                                  str(custom_hei_1x), image_type)
        else:
            image_new_path_x = '%s%s' % (image_new_path, img_target_name)
        image_new.save(image_new_path_x)
        # image_new.save(image_new_path_x, image_type.upper())
        print("[ImageDealProcess OK] " + image_new_path_x + "已完成")
        return True
    else:
        print(image_name + " -- 提供尺寸格式不正确。")
        return False


def createAppIcon():
    imagesNewSavePath = imagesSavePath + "ios/AppIcon.appiconset/"
    if not os.path.exists(imagesNewSavePath):
        os.makedirs(imagesNewSavePath)
    if isOldImageSize:
        newImportIconSizeArr = importIconSizeArr + importIconSizeOldArr
    else:
        newImportIconSizeArr = importIconSizeArr
    for importIconSizeDict in newImportIconSizeArr:
        iconSize = float(importIconSizeDict["size"].split("x")[0])
        iconFileName = importIconSizeDict["filename"]
        iconScale = float(importIconSizeDict["scale"].split("x")[0])
        scaleImage(imagePath, imagesNewSavePath,
                        (int(iconSize * iconScale), int(iconSize * iconScale)), iconFileName)
    contentsJsonFilePath = imagesNewSavePath + "Contents.json"
    shutil.copy('Res/iconContentsConfig.json', contentsJsonFilePath)
    if "oldImages" in importIconSizeDataDic:
        del importIconSizeDataDic["oldImages"]
    importIconSizeDataDic["images"] = newImportIconSizeArr
    with open(contentsJsonFilePath, "w", encoding='utf-8') as f:
        f.write(json.dumps(importIconSizeDataDic, indent=4))
    print("[ImageDealProcess End] 图片处理已完成")


if __name__ == "__main__":
    isOldImageSize = True
    imagesSavePath = "/Users/yfzx/Documents/output/"
    imagePath = "/Users/yfzx/Downloads/12.png"

    configFile = open('Res/iconContentsConfig.json')
    data = json.load(configFile)
    configFile.close()
    importIconSizeDataDic = data
    importIconSizeArr = data['images']
    importIconSizeOldArr = data['oldImages']
    # 一键生成所有尺寸图片
    createAppIcon()

⭐️如果对你有用的话,希望可以点点赞,感谢了⭐️

欢迎学习交流

 

2024-09-29 16:11:39【出处】:https://blog.csdn.net/qq_43673244/article/details/141641277

=======================================================================================

posted on 2024-09-29 16:13  jack_Meng  阅读(59)  评论(0编辑  收藏  举报

导航