当前位置: 代码网 > it编程>前端脚本>Python > 使用Python实现图片转ICO格式

使用Python实现图片转ICO格式

2025年01月16日 Python 我要评论
1. 简介这个工具实现了一个基于pyqt5的用于将图像文件(如png、jpeg、bmp、gif)转换为ico格式gui应用程序。以下是该工具的功能介绍:ui布局:用于选择要转换的图像的文件输入。用于指

1. 简介

这个工具实现了一个基于pyqt5的用于将图像文件(如png、jpeg、bmp、gif)转换为ico格式gui应用程序。以下是该工具的功能介绍:

ui布局:

  • 用于选择要转换的图像的文件输入。
  • 用于指定将生成的ico文件保存在何处的输出路径输入。
  • 用于选择所需图标大小(16x16、32x32、48x48、64x64、128x128、256x256)的组合框。 转换前预览图像的区域。
  • “转换为ico”按钮以执行转换。

转换过程:

  • 使用python pillow库(pil)来处理图像操作。
  • 将所选图像转换为所需大小(以ico文件的形式)。
  • 如果转换成功,转换将记录到文件(conversion_history.log)中。

拖放支持:

您可以将图像文件拖放到应用程序中,它将自动加载到输入字段中并带有预览。

错误处理:

对于丢失的文件或转换失败,会显示正确的错误消息。 如果有其他问题,可以评论区告诉我!

2. 运行效果

3. 相关源码

import sys
import os
from pyqt5.qtwidgets import (
    qapplication, qmainwindow, qlabel, qlineedit, qpushbutton, qfiledialog,
    qvboxlayout, qhboxlayout, qwidget, qmessagebox, qcombobox
)
from pyqt5.qtgui import qpixmap, qicon
from pyqt5.qtcore import qt
from pyqt5.qtcore import qmimedata
from pyqt5.qtgui import qdragenterevent, qdropevent
from pil import image

# 日志文件
log_file = "conversion_history.log"

class imagetoicoconverter(qmainwindow):
    def __init__(self):
        super().__init__()

        self.setwindowtitle("图片转ico工具")
        self.setgeometry(100, 100, 355, 360)
        self.setacceptdrops(true)  # 启用拖拽功能
        self.initui()

    def initui(self):
        # 主布局
        main_layout = qvboxlayout()

        # 图片选择
        file_layout = qhboxlayout()
        self.image_path_input = qlineedit(self)
        browse_button = qpushbutton("浏览", self)
        browse_button.clicked.connect(self.choose_image_file)
        file_layout.addwidget(qlabel("选择图片文件:"))
        file_layout.addwidget(self.image_path_input)
        file_layout.addwidget(browse_button)
        main_layout.addlayout(file_layout)

        # 输出路径选择
        output_layout = qhboxlayout()
        self.output_path_input = qlineedit(self)
        save_button = qpushbutton("保存", self)
        save_button.clicked.connect(self.choose_output_path)
        output_layout.addwidget(qlabel("选择输出路径:"))
        output_layout.addwidget(self.output_path_input)
        output_layout.addwidget(save_button)
        main_layout.addlayout(output_layout)

        # 图标尺寸选择(单选)
        size_layout = qhboxlayout()
        self.size_combo = qcombobox(self)
        self.size_combo.additems(["16", "32", "48", "64", "128", "256"])
        size_layout.addwidget(qlabel("选择图标尺寸:"))
        size_layout.addwidget(self.size_combo)
        main_layout.addlayout(size_layout)

        # 图片预览
        self.preview_label = qlabel("图片预览", self)
        self.preview_label.setalignment(qt.aligncenter)
        self.preview_label.setstylesheet("background-color: lightgray; border: 1px solid black;")
        self.preview_label.setfixedsize(200, 200)
        preview_layout = qvboxlayout()
        preview_layout.addwidget(self.preview_label, alignment=qt.aligncenter)
        main_layout.addlayout(preview_layout)

        # 转换按钮
        convert_button = qpushbutton("转换为ico", self)
        convert_button.clicked.connect(self.convert_to_ico)
        main_layout.addwidget(convert_button, alignment=qt.aligncenter)

        # 设置中央窗口
        central_widget = qwidget()
        central_widget.setlayout(main_layout)
        self.setcentralwidget(central_widget)

    def choose_image_file(self):
        file_path, _ = qfiledialog.getopenfilename(self, "选择图片文件", "", "图片文件 (*.png *.jpg *.jpeg *.bmp *.gif)")
        if file_path:
            self.image_path_input.settext(file_path)
            self.show_preview(file_path)

    def choose_output_path(self):
        output_path, _ = qfiledialog.getsavefilename(self, "选择输出路径", "", "ico文件 (*.ico)")
        if output_path:
            self.output_path_input.settext(output_path)

    def show_preview(self, image_path):
        try:
            pixmap = qpixmap(image_path)
            pixmap = pixmap.scaled(200, 200, qt.keepaspectratio, qt.smoothtransformation)
            self.preview_label.setpixmap(pixmap)
        except exception as e:
            qmessagebox.critical(self, "预览错误", f"无法加载图片预览: {str(e)}")

    def convert_to_ico(self):
        image_path = self.image_path_input.text()
        output_path = self.output_path_input.text()

        if not image_path:
            qmessagebox.critical(self, "错误", "请选择源图片文件")
            return

        if not output_path:
            output_path = os.path.splitext(image_path)[0] + ".ico"
            self.output_path_input.settext(output_path)

        try:
            img = image.open(image_path)

            # 获取用户选择的图标尺寸
            size = int(self.size_combo.currenttext())
            sizes = [(size, size)]

            img = img.convert("rgba")
            img.save(output_path, format="ico", sizes=sizes)

            with open(log_file, "a") as log_file:
                log_file.write(f"converted: {image_path} -> {output_path}\n")

            qmessagebox.information(self, "成功", f"图片已成功转换并保存为 {output_path}")
        except exception as e:
            qmessagebox.critical(self, "转换错误", f"转换过程中发生错误: {str(e)}")

    def dragenterevent(self, event: qdragenterevent):
        if event.mimedata().hasurls():
            event.accept()
        else:
            event.ignore()

    def dropevent(self, event: qdropevent):
        mime_data: qmimedata = event.mimedata()
        if mime_data.hasurls():
            file_path = mime_data.urls()[0].tolocalfile()
            self.image_path_input.settext(file_path)
            self.show_preview(file_path)

if __name__ == "__main__":
    app = qapplication(sys.argv)
    window = imagetoicoconverter()
    window.show()
    sys.exit(app.exec_())

到此这篇关于使用python实现图片转ico格式的文章就介绍到这了,更多相关python图片转ico内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com