auto_build_launcher/scripts/project_res_md5.py

81 lines
2.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from scripts.task import Task
import os
import hashlib
from PIL import Image
import random
def get_md5(file_path):
"""计算文件的MD5值"""
hash_md5 = hashlib.md5()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def modify_one_pixel(input_path, output_path):
"""随机修改图片中一个不显眼的像素,每次执行结果不同"""
try:
with Image.open(input_path) as img:
width, height = img.size
# 随机选择一个像素位置(避开边缘以防某些特殊图片格式问题)
x = random.randint(1, width - 2)
y = random.randint(1, height - 2)
# 获取该位置的像素值
pixel = img.getpixel((x, y))
# 随机决定是增加还是减少像素值
change = random.choice([-1, 1])
# 根据图像模式处理像素值
if img.mode in ['RGB', 'RGBA']:
new_pixel = list(pixel)
# 随机选择一个颜色通道进行修改
channel = random.randint(0, len(new_pixel) - 1)
new_pixel[channel] = (new_pixel[channel] + change) % 256
new_pixel = tuple(new_pixel)
elif img.mode == 'L': # 灰度图
new_pixel = (pixel + change) % 256
else:
# 其他模式处理
if isinstance(pixel, int):
new_pixel = (pixel + change) % 256
else:
# 对多通道非RGB模式随机选择一个通道修改
new_pixel = list(pixel)
channel = random.randint(0, len(new_pixel) - 1)
new_pixel[channel] = (new_pixel[channel] + change) % 256
new_pixel = tuple(new_pixel)
# 设置新的像素值
img.putpixel((x, y), new_pixel)
# 保存修改后的图片
img.save(output_path)
return True
except Exception as e:
print(f"处理图片时出错: {e}")
return False
class ProjectResMd5(Task):
def execute(self):
path = f"launcher-game/res/"
root_path = os.path.join(self.context.temp_project_path, path)
for i in os.listdir(root_path):
if i.startswith("drawable"):
path = os.path.join(root_path, i)
for file in os.listdir(path):
if file.endswith(".png") or file.endswith(".jpg"):
file_path = os.path.join(path, file)
md51 = get_md5(file_path)
modify_one_pixel(file_path, file_path)
md52 = get_md5(file_path)
print(file_path, md51, md52)
pass