使用Python实现图片转ICO格式
作者:黑客白泽
这篇文章主要为大家详细介绍了如何使用Python编写一个基于PyQt5的用于将图像文件转换为ICO格式GUI应用程序,感兴趣的小伙伴可以跟随小编一起学习一下
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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
