import os
from PIL import Image
for infile in os.listdir('./'):
if infile.endswith('.png'):
f, e = os.path.splitext(infile)
outfile = '/tmp/'+ f + ".png"
Image.open('./'+infile).save(outfile)
def safe_image_open(image_path):
"""
安全打开可能损坏的图像文件
"""
try:
img = Image.open(image_path)
# 验证图像是否完整
img.verify()
# 需要重新打开因为verify()会关闭文件
img = Image.open(image_path)
return img
except (IOError, SyntaxError) as e:
print(f"文件损坏或不是有效图像: {image_path} - {e}")
return None
def robust_convert(input_path, output_path, output_format):
"""
健壮的格式转换,处理可能损坏的文件
"""
img = safe_image_open(input_path)
if img is not None:
try:
img.save(output_path, format=output_format)
return True
except Exception as e:
print(f"转换失败: {e}")
return False
def convert_heic_to_jpg(input_path, output_path):
"""
转换HEIC格式为JPG(需要pyheif库)
"""
try:
import pyheif
heif_file = pyheif.read(input_path)
img = Image.frombytes(
heif_file.mode,
heif_file.size,
heif_file.data,
"raw",
heif_file.mode,
heif_file.stride,
)
img.save(output_path, format="JPEG", quality=95)
return True
except ImportError:
print("请先安装pyheif: pip install pyheif")
except Exception as e:
print(f"HEIC转换失败: {e}")
return False