Skip to content

Commit

Permalink
3.3.2
Browse files Browse the repository at this point in the history
  • Loading branch information
riceshowerX committed Sep 29, 2024
1 parent 3c8ca4a commit da1e3ca
Show file tree
Hide file tree
Showing 6 changed files with 54 additions and 57 deletions.
Binary file modified SnapForge/__pycache__/logic.cpython-312.pyc
Binary file not shown.
Binary file modified SnapForge/__pycache__/ui.cpython-312.pyc
Binary file not shown.
78 changes: 34 additions & 44 deletions SnapForge/logic.py
Original file line number Diff line number Diff line change
@@ -1,64 +1,54 @@
# logic.py
import os
import re
import uuid
from PIL import Image
import logging

# 初始化日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

class ImageProcessor:
def batch_process(self, directory, prefix=None, start_number=1, extension=".jpg", convert_format=None, quality=None, progress_callback=None):
supported_formats = [".jpg", ".jpeg", ".png", ".bmp", ".gif", ".tiff"]
extension = extension.lower()
count = start_number
total_files = 0
processed_files = 0
if extension not in supported_formats:
logging.error(f"不支持的文件格式: {extension}")
return 0

files = os.listdir(directory) # 提前获取文件列表
for filename in files:
if filename.lower().endswith(extension):
total_files += 1 # 更新 total_files
files = [f for f in os.listdir(directory) if f.lower().endswith(extension)]
total_files = len(files)
processed_files = 0

src = os.path.join(directory, filename)
for i, filename in enumerate(files):
file_path = os.path.join(directory, filename)

# 设置新的文件扩展名
new_extension = convert_format.lower() if convert_format else extension
if not new_extension.startswith("."):
new_extension = f".{new_extension}"
# 文件处理
try:
image = Image.open(file_path)

# 重命名文件
if prefix:
valid_filename = re.sub(r'[\\/*?:"<>|]', '_', f"{prefix}_{count}")
unique_filename = valid_filename + "_" + str(uuid.uuid4())
dst = os.path.join(directory, f"{unique_filename}{new_extension}")

# 确保目标文件名唯一
while os.path.exists(dst):
count += 1
valid_filename = re.sub(r'[\\/*?:"<>|]', '_', f"{prefix}_{count}")
unique_filename = valid_filename + "_" + str(uuid.uuid4())
dst = os.path.join(directory, f"{unique_filename}{new_extension}")
new_filename = f"{prefix}_{start_number + i}{extension}"
new_file_path = os.path.join(directory, new_filename)
image.save(new_file_path)
else:
dst = src
new_file_path = file_path

try:
if convert_format:
with Image.open(src) as img:
if new_extension == ".jpg" and img.mode in ("RGBA", "LA"):
img = img.convert("RGB")
img.save(dst, format=convert_format.upper(), quality=quality or 95) # 提供默认质量值
os.remove(src)
else:
os.rename(src, dst)
except (PermissionError, FileNotFoundError) as e:
logging.error(f"处理文件 {filename} 时发生错误: {e}")
continue
# 格式转换
if convert_format:
new_file_path = new_file_path.replace(extension, f".{convert_format.lower()}")
image.save(new_file_path, format=convert_format)

# 压缩处理
if quality is not None:
image.save(new_file_path, quality=quality)

count += 1
processed_files += 1
# 在这里调用 progress_callback
if progress_callback:
if i % 10 == 0 and progress_callback:
progress = int((processed_files / total_files) * 100)
progress_callback(progress)

return count - start_number
except Exception as e:
logging.error(f"处理文件 {filename} 时发生错误: {str(e)}")
continue

if progress_callback:
progress_callback(100)

return processed_files
20 changes: 10 additions & 10 deletions SnapForge/main.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
# main.py
import sys
import traceback
import logging
from PyQt6.QtWidgets import QApplication, QMessageBox
from ui import BatchRenameApp


def main():
# 初始化日志记录
logging.basicConfig(filename='app.log', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(filename)s - %(lineno)d - %(message)s')
# 初始化日志记录,添加日志文件大小限制
from logging.handlers import RotatingFileHandler
logging.basicConfig(
handlers=[RotatingFileHandler('app.log', maxBytes=1 * 1024 * 1024, backupCount=5)], # 1MB, 最多5个备份
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(filename)s - %(lineno)d - %(message)s'
)

app = QApplication(sys.argv)

Expand All @@ -19,12 +21,10 @@ def main():
sys.exit(app.exec())

except Exception as e:
error_msg = f"发生未捕获的异常:\n{str(e)}"
logging.exception(error_msg) # 将错误信息记录到日志文件
logging.exception("发生未捕获的异常")
# 弹出错误对话框
QMessageBox.critical(None, "错误", error_msg)
QMessageBox.critical(None, "错误", f"发生未捕获的异常:\n{str(e)}")
sys.exit(1)


if __name__ == "__main__":
main()
main()
13 changes: 10 additions & 3 deletions SnapForge/ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,6 @@ def run(self):
self.finished.emit(processed_count)
except Exception as e:
self.error_occurred.emit(str(e))
finally:
self.finished.emit(0)

def update_progress(self, progress):
self.progress_updated.emit(progress)
Expand Down Expand Up @@ -86,7 +84,7 @@ def __init__(self):
layout.addWidget(self.start_number_input, 3, 1, 1, 4)

# 文件扩展名
self.extension_label = QLabel("文件扩展名:")
self.extension_label = QLabel("文件扩展名 (支持: .jpg, .jpeg, .png, .bmp, .gif, .tiff):")
layout.addWidget(self.extension_label, 4, 0)

self.extension_input = QLineEdit()
Expand Down Expand Up @@ -197,9 +195,18 @@ def update_progress(self, progress):

def process_finished(self, processed_count):
self.result_label.setText(f"处理完成,共处理 {processed_count} 个文件。")
self.restore_ui()

def show_error(self, message):
QMessageBox.critical(self, "错误", f"处理过程中出现错误: {message}")
self.restore_ui()

def restore_ui(self):
self.process_button.setEnabled(True)
self.directory_button.setEnabled(True)
self.rename_checkbox.setEnabled(True)
self.convert_format_checkbox.setEnabled(True)
self.compress_checkbox.setEnabled(True)

if __name__ == "__main__":
app = QApplication(sys.argv)
Expand Down
Empty file added app.log
Empty file.

0 comments on commit da1e3ca

Please sign in to comment.