首页 > 编程语言 >Python 一键生成所有尺寸的应用Ico图标

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

时间:2024-09-29 16:13:40浏览次数:8  
标签:scale Ico icon Python 1x image filename 图标 size

项目介绍

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

编译环境

Python版本:python3.8

制作应用尺寸配置文件

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

{
    "images": [
        {
            "size": "20x20",
            "idiom": "iphone",
            "filename": "[email protected]",
            "scale": "2x"
        },
        {
            "size": "20x20",
            "idiom": "iphone",
            "filename": "[email protected]",
            "scale": "3x"
        },
        {
            "size": "29x29",
            "idiom": "iphone",
            "filename": "icon-29.png",
            "scale": "1x"
        },
        {
            "size": "29x29",
            "idiom": "iphone",
            "filename": "[email protected]",
            "scale": "2x"
        },
        {
            "size": "29x29",
            "idiom": "iphone",
            "filename": "[email protected]",
            "scale": "3x"
        },
        {
            "size": "40x40",
            "idiom": "iphone",
            "filename": "[email protected]",
            "scale": "2x"
        },
        {
            "size": "40x40",
            "idiom": "iphone",
            "filename": "[email protected]",
            "scale": "3x"
        },
        {
            "size": "60x60",
            "idiom": "iphone",
            "filename": "[email protected]",
            "scale": "2x"
        },
        {
            "size": "60x60",
            "idiom": "iphone",
            "filename": "[email protected]",
            "scale": "3x"
        },
        {
            "size": "20x20",
            "idiom": "ipad",
            "filename": "icon-20-ipad.png",
            "scale": "1x"
        },
        {
            "size": "20x20",
            "idiom": "ipad",
            "filename": "[email protected]",
            "scale": "2x"
        },
        {
            "size": "29x29",
            "idiom": "ipad",
            "filename": "icon-29-ipad.png",
            "scale": "1x"
        },
        {
            "size": "29x29",
            "idiom": "ipad",
            "filename": "[email protected]",
            "scale": "2x"
        },
        {
            "size": "40x40",
            "idiom": "ipad",
            "filename": "icon-40.png",
            "scale": "1x"
        },
        {
            "size": "40x40",
            "idiom": "ipad",
            "filename": "[email protected]",
            "scale": "2x"
        },
        {
            "size": "76x76",
            "idiom": "ipad",
            "filename": "icon-76.png",
            "scale": "1x"
        },
        {
            "size": "76x76",
            "idiom": "ipad",
            "filename": "[email protected]",
            "scale": "2x"
        },
        {
            "size": "83.5x83.5",
            "idiom": "ipad",
            "filename": "[email protected]",
            "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": "[email protected]",
            "scale": "2x"
        },
        {
            "size": "72x72",
            "idiom": "ipad",
            "filename": "icon-72.png",
            "scale": "1x"
        },
        {
            "size": "72x72",
            "idiom": "ipad",
            "filename": "[email protected]",
            "scale": "2x"
        },
        {
            "size": "57x57",
            "idiom": "iphone",
            "filename": "icon-57.png",
            "scale": "1x"
        },
        {
            "size": "57x57",
            "idiom": "iphone",
            "filename": "[email protected]",
            "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

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

标签:scale,Ico,icon,Python,1x,image,filename,图标,size
From: https://www.cnblogs.com/mq0036/p/18440252

相关文章

  • Python 的 PIL库——Image.new() 的使用说明,制作icon图标
    Image包中的new()方法:新建一个图片对象,设置参数有:图片的模式,图片的尺寸,图片的颜色(不填写颜色的时候,其默认值为0,即黑色)返回:一个图片对象,即<class'PIL.Image.Image'>【语法格式:】Image.new(mode,size,color) 【参数说明:】mode:图片的模式。"1","CMYK","F",......
  • 计算机专业毕设选题推荐-基于大数据的豆瓣图书数据分析【python-爬虫-大数据定制】
    ......
  • Python基于自定义方法的排序
    Python基于自定义方法的排序在Python中,排序是一个常见的任务,它可以帮助我们根据特定的规则对数据结构(如列表)中的元素进行排序。Python的内置排序方法,如列表的sort()函数和内置函数sorted(),提供了非常灵活的排序机制,特别是通过key参数,我们可以指定一个自定义的函数来决定排序的顺......
  • 基于python+flask框架的社区防疫物资统计分析系统(开题+程序+论文) 计算机毕设
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容研究背景随着全球公共卫生事件的频发,社区作为疫情防控的第一线,其防疫物资的有效管理与分配显得尤为重要。传统的物资管理模式往往存在信息不对称、......
  • 基于python+flask框架的山西省残疾人就业服务平台的设计与实现(开题+程序+论文) 计算机
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容研究背景随着社会文明的进步与残疾人权益保障政策的不断完善,山西省作为华夏文明的重要发祥地,其残疾人事业的发展日益受到社会各界的关注。然而,当前......
  • 基于python+flask框架的商厦会员管理系统(开题+程序+论文) 计算机毕设
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容研究背景随着商业竞争的日益激烈,商厦作为集购物、休闲、娱乐为一体的综合性商业体,其管理效率与顾客服务体验成为决定其竞争力的关键因素。传统的人......
  • 基于python+flask框架的少儿编程网站的设计与实现(开题+程序+论文) 计算机毕设
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容研究背景随着信息技术的飞速发展,编程教育在全球范围内日益受到重视,尤其是在基础教育阶段。少儿编程作为培养学生逻辑思维、问题解决能力和创新能力......
  • 听我的!开展Python副业接单,你一定要去尝试的方向!
    前言上班打工不给力,打工人需要PlanB,敢问当代年轻人谁没动过搞副业的念头呢?ChatGPT的横空出世,更是让担心饭碗不保的年轻人把搞副业提上了日程。在哪个城市搞副业最卷?副业在网上炒的火热,实际上能不能挣到钱?哪个副业才是能月入过万的“财富密码”?每两个年轻人中,就有一人做过......
  • 【python】进制转换
    defbinary_to_octal(binary_str):decimal=int(binary_str,2)returnoct(decimal)[2:]#去掉'0o'前缀defbinary_to_decimal(binary_str):returnint(binary_str,2)defbinary_to_hexadecimal(binary_str):decimal=int(binary_str,2......
  • Python更换下载源:提升包安装速度的实用指南
    Python更换下载源:提升包安装速度的实用指南Python作为一门广泛使用的编程语言,其强大的生态系统和丰富的第三方库是吸引众多开发者的关键因素之一。然而,在使用pip安装这些第三方库时,由于网络延迟、官方源服务器负载等原因,下载速度可能会变得非常缓慢,尤其是在某些地理位置偏远的地......