使用Python實現(xiàn)圖片轉ICO格式
1. 簡介
這個工具實現(xiàn)了一個基于PyQt5的用于將圖像文件(如PNG、JPEG、BMP、GIF)轉換為ICO格式GUI應用程序。以下是該工具的功能介紹:
UI布局:
- 用于選擇要轉換的圖像的文件輸入。
- 用于指定將生成的ICO文件保存在何處的輸出路徑輸入。
- 用于選擇所需圖標大小(16x16、32x32、48x48、64x64、128x128、256x256)的組合框。 轉換前預覽圖像的區(qū)域。
- “轉換為ICO”按鈕以執(zhí)行轉換。
轉換過程:
- 使用Python Pillow庫(PIL)來處理圖像操作。
- 將所選圖像轉換為所需大?。ㄒ訧CO文件的形式)。
- 如果轉換成功,轉換將記錄到文件(conversion_history.log)中。
拖放支持:
您可以將圖像文件拖放到應用程序中,它將自動加載到輸入字段中并帶有預覽。
錯誤處理:
對于丟失的文件或轉換失敗,會顯示正確的錯誤消息。 如果有其他問題,可以評論區(qū)告訴我!
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"轉換過程中發(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實現(xiàn)圖片轉ICO格式的文章就介紹到這了,更多相關Python圖片轉ICO內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python編程開發(fā)時間序列calendar模塊示例詳解
這篇文章主要為大家介紹了python編程開發(fā)時間序列calendar模塊示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助祝大家多多進步早日升職加薪2021-11-11
TensorFlow用expand_dim()來增加維度的方法
今天小編就為大家分享一篇TensorFlow用expand_dim()來增加維度的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07
Python常見格式化字符串方法小結【百分號與format方法】
這篇文章主要介紹了Python常見格式化字符串方法,結合實例形式分析了百分號方法和format函數(shù)進行字符串格式化的具體使用技巧,需要的朋友可以參考下2016-09-09
關于Python中兩個不同shape的數(shù)組間運算規(guī)則
這篇文章主要介紹了關于Python中兩個不同shape的數(shù)組間運算規(guī)則,眾所周知,相同?shape?的兩個數(shù)組間運算是指兩個數(shù)組的對應元素相加,我們經常會碰到一些不同?shape?的數(shù)組間運算,需要的朋友可以參考下2023-08-08

