from PIL import Image
import numpy as np
input_image_path = './cc-logo.png'
output_image_path = './logo.png'
output_size = (246, 184)
tolerance = 150
try:
image = Image.open(input_image_path).convert("RGBA")
except FileNotFoundError:
print(f"错误: 文件 {input_image_path} 未找到,请检查路径是否正确。")
exit(1)
except Exception as e:
print(f"错误: 无法打开图片文件 {input_image_path}。详细信息: {e}")
exit(1)
def make_white_transparent(img, tolerance):
datas = img.getdata()
new_data = []
for item in datas:
if all([item[i] > 255 - tolerance for i in range(3)]):
new_data.append((255, 255, 255, 0))
else:
new_data.append(item)
img.putdata(new_data)
return img
image = make_white_transparent(image, tolerance)
smooth_factor = 18
image = image.resize((image.size[0]*smooth_factor, image.size[1]*smooth_factor), Image.Resampling.LANCZOS)
original_width, original_height = image.size
target_width, target_height = output_size
ratio = min(target_width / original_width, target_height / original_height)
new_width = int(original_width * ratio)
new_height = int(original_height * ratio)
resized_image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
new_image = Image.new("RGBA", output_size, (0, 0, 0, 0))
paste_x = (output_size[0] - new_width) // 2
paste_y = (output_size[1] - new_height) // 2
new_image.paste(resized_image, (paste_x, paste_y), resized_image)
try:
new_image.save(output_image_path, format="PNG")
print(f"成功: 图片已保存到 {output_image_path}")
except Exception as e:
print(f"错误: 无法保存图片到 {output_image_path}。详细信息: {e}")