如何使用Python将PNG转换为ICO_并且指定尺寸

admin Python评论102字数 1073阅读模式

在Python中,将PNG转换为ICO并指定尺寸为128x128像素,你可以使用PIL(Python Imaging Library,也称为Pillow)库来完成这个任务。首先,确保你已经安装了Pillow库,如果没有安装,你可以通过以下命令来安装:

pip install Pillow

接下来,你可以使用以下代码将PNG图片转换为128x128像素的ICO文件:

from PIL import Image
import io

# PNG文件路径
png_file = 'example.png'
# 输出ICO文件路径
ico_file = 'example.ico'

# 打开PNG图片
with Image.open(png_file) as img:
    # 确保图片是正方形,如果不是,需要裁剪或填充
    width, height = img.size
    if width != height:
        # 选择较小的尺寸作为边长,居中裁剪
        size = min(width, height)
        left = (width - size) // 2
        top = (height - size) // 2
        right = (width + size) // 2
        bottom = (height + size) // 2
        img = img.crop((left, top, right, bottom))
    
    # 调整图片尺寸为128x128像素
    img = img.resize((128, 128))

    # 保存为ICO格式
    with io.BytesIO() as output:
        img.save(output, format='ICO', sizes=[(128, 128)])
        with open(ico_file, 'wb') as f:
            f.write(output.getvalue())

print(f'PNG file {png_file} has been converted to ICO file {ico_file} with 128x128 size.')

这段代码首先使用Pillow库打开PNG图片,然后检查图片的尺寸是否是正方形。如果不是,它会选择较小的尺寸作为边长,并居中裁剪图片以使其成为正方形。接着,它会调整图片尺寸为128x128像素,并将其保存为ICO格式。sizes=[(128, 128)]参数确保生成的ICO文件包含128x128像素的图标。

请注意,ICO格式通常用于Windows图标,它可以包含多个不同尺寸的图标。在这个例子中,我们只生成了一个128x128像素的图标。如果你需要包含其他尺寸的图标,你可以在sizes参数中添加更多的元组,例如sizes=[(16, 16), (32, 32), (48, 48), (128, 128)]。

如何使用Python将PNG转换为ICO_并且指定尺寸

版权声明:文章图片资源来源于网络,如有侵权,请留言删除!!!
admin
  • 本文由 发表于 2024年4月18日 21:59:51
  • 转载请务必保留本文链接:https://www.58pxe.com/11815.html
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: