from PIL import Image, ImageDraw, ImageFont
from pathlib import Path
from platform import system
version = 0.8
def IsValidImage(img_path):
"""
判断文件是否为有效(完整)的图片
:param img_path:图片路径
:return:True:有效 False:无效
"""
Valid = True
try:
Image.open(img_path).verify()
except:
Valid = False
return Valid
def add_mark_png(file, words, size=60, color=(200, 200, 200)):
# 设置所使用的字体
if "Darwin" in system():
font_file = r"/System/Library/Fonts/PingFang.ttc"
elif "Windows" in system():
font_file = r"C:\windows\Fonts\msyh.ttc"
font = ImageFont.truetype(font_file, int(size))
# Opening Image & Creating New Text Layer
img = Image.open(file)
if (Path(file).suffix).lower() == ".png":
txt = Image.new('RGBA', img.size, (255, 255, 255, 0))
# 针对jpeg无透明通道,先创建水印图片的模式
else:
txt = Image.new('L', img.size)
# Creating Draw Object
d = ImageDraw.Draw(txt)
# Positioning Text
width, height = img.size
x = y = 0
# textwidth, textheight = d.textsize(words, font)
# x=width/2-textwidth/2
# y=height-textheight-300
while y < height or x < width:
mark = txt.rotate(16.8)
if (Path(file).suffix).lower() == ".png":
d.text((x, y), words, fill=(255, 255, 255, 155), font=font)
else:
d.text((x, y), words, fill=100, font=font)
x += 50
y += 120
# 另存图片
dir_name = Path(file).parent.joinpath("水印图")
if not dir_name.is_dir():
Path.mkdir(dir_name)
file_name = (Path(file).stem + "_new" + Path(file).suffix.lower()).replace(" ", "_")
file_name = dir_name.joinpath(file_name)
if (Path(file).suffix).lower() == ".png":
try:
watermarked = Image.alpha_composite(img, mark)
watermarked.save(file_name)
except:
rgb_im = img.convert('RGB')
rgb_im.paste(color, (0, 0), mark)
rgb_im.save(file_name)
else: # 针对jpeg格式的图片,用paste方法
img.paste(color, (0, 0), mark)
img.save(file_name)
from PIL import Image
def image_to_pdf(image_path, pdf_path):
# 打开图像文件
try:
image = Image.open(image_path)
except Exception as e:
print(f"Error opening image: {e}")
return
# 检查图像模式,如果不是 RGB,则转换为 RGB
if image.mode != "RGB":
image = image.convert("RGB")
# 保存图像为 PDF 文件
image.save(pdf_path, "PDF", resolution=100.0)