JPG转PDF还要收费?20行Python轻松实现!
昨天,由于工作需要将JPG图片转为PDF才能上传网站,打开某国产热门软件,转换时竟然要冲会员才能转,好吧,打开Python,几分钟弄了一段代码,几秒钟完成转化,完美!
附完整代码,需要的朋友可以复制直接运行。
"""
图片转PDF工具
"""
from PIL import Image
import os
import tkinter as tk
from tkinter import filedialog, messagebox
def convert_to_pdf(image_path):
"""
将图片转换为PDF
Args:
image_path (str): 图片文件路径
"""
try:
# 打开图片
image = Image.open(image_path)
# 生成PDF保存路径
pdf_path = os.path.splitext(image_path)[0] + '.pdf'
# 转换为PDF并保存
image.save(pdf_path, "PDF", resolution=100.0)
messagebox.showinfo("成功", f"转换完成,已保存为:\n{pdf_path}")
return pdf_path
except Exception as e:
messagebox.showerror("错误", f"转换图片时出错: {str(e)}")
return None
def create_gui():
"""创建图形用户界面"""
root = tk.Tk()
root.title("图片转PDF工具")
root.geometry("400x200")
def select_file():
"""选择图片文件"""
file_path = filedialog.askopenfilename(
title="选择图片文件",
filetypes=[("图片文件", "*.jpg;*.jpeg;*.png;*.bmp;*.gif")]
)
if file_path:
entry_path.delete(0, tk.END)
entry_path.insert(0, file_path)
def process_file():
"""处理选中的图片"""
file_path = entry_path.get()
if not file_path:
messagebox.showwarning("警告", "请先选择图片文件")
return
convert_to_pdf(file_path)
# 文件路径输入框
tk.Label(root, text="图片文件路径:").pack(pady=5)
entry_path = tk.Entry(root, width=40)
entry_path.pack(pady=5)
# 选择文件按钮
btn_select = tk.Button(root, text="选择文件", command=select_file)
btn_select.pack(pady=5)
# 处理按钮
btn_process = tk.Button(root, text="转换为PDF", command=process_file)
btn_process.pack(pady=10)
root.mainloop()
if __name__ == "__main__":
create_gui()