当前位置: 首页 > 网络编程 > python

使用Python实现图片和base64转换工具<

时间:2025-03-18 14:19:12 python 我要投稿
这篇文章主要为大家详细介绍了如何使用Python中的base64模块编写一个工具,可以实现图片和Base64编码之间的转换,感兴趣的小伙伴可以了解下

简介

使用Python的base64模块来实现图片和Base64编码之间的转换。可以将图片转换为Base64编码,以及将Base64编码转换回图片并保存。

使用Python实现图片和base64转换工具<(图1)

依赖库

该工具仅依赖 Python 标准库(tkinter 和 base64),无需安装其他第三方库。

完整代码:

import tkinter as tk
from tkinter import filedialog, messagebox
import base64
 
class Base64ImageConverter:
    def __init__(self, root):
        self.root = root
        self.root.title("图片与Base64转换工具")
        self.root.geometry("500x400")
 
        # 上传图片按钮
        self.upload_button = tk.Button(root, text="上传图片", command=self.upload_image)
        self.upload_button.pack(pady=10)
 
        # 显示图片路径
        self.image_path_label = tk.Label(root, text="未选择图片", fg="gray")
        self.image_path_label.pack(pady=5)
 
        # Base64 输入框
        self.base64_input_label = tk.Label(root, text="输入Base64字符串:")
        self.base64_input_label.pack(pady=5)
        self.base64_input = tk.Text(root, height=5, width=50)
        self.base64_input.pack(pady=5)
 
        # 转换按钮
        self.convert_button = tk.Button(root, text="转换为Base64", command=self.convert_to_base64)
        self.convert_button.pack(pady=10)
 
        self.convert_button2 = tk.Button(root, text="转换为图片", command=self.convert_to_image)
        self.convert_button2.pack(pady=10)
 
        # 状态显示
        self.status_label = tk.Label(root, text="", fg="blue")
        self.status_label.pack(pady=10)
 
    def upload_image(self):
        """上传图片并显示路径"""
        file_path = filedialog.askopenfilename(filetypes=[("Image Files", "*.jpg;*.jpeg;*.png;*.bmp")])
        if file_path:
            self.image_path_label.config(text=file_path, fg="green")
            self.status_label.config(text="图片已上传", fg="blue")
 
    def convert_to_base64(self):
        """将图片转换为Base64"""
        image_path = self.image_path_label.cget("text")
        if image_path == "未选择图片":
            messagebox.showerror("错误", "请先上传图片!")
            return
 
        try:
            with open(image_path, "rb") as image_file:
                encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
                self.base64_input.delete(1.0, tk.END)  # 清空输入框
                self.base64_input.insert(tk.END, encoded_string)
                self.status_label.config(text="图片已转换为Base64", fg="green")
        except Exception as e:
            messagebox.showerror("错误", f"转换失败: {str(e)}")
 
    def convert_to_image(self):
        """将Base64转换为图片并保存"""
        base64_string = self.base64_input.get(1.0, tk.END).strip()
        if not base64_string:
            messagebox.showerror("错误", "Base64字符串不能为空!")
            return
 
        try:
            output_path = filedialog.asksaveasfilename(defaultextension=".jpg", filetypes=[("JPEG Files", "*.jpg"), ("PNG Files", "*.png")])
            if output_path:
                image_data = base64.b64decode(base64_string)
                with open(output_path, "wb") as image_file:
                    image_file.write(image_data)
                self.status_label.config(text=f"图片已保存为: {output_path}", fg="green")
        except Exception as e:
            messagebox.showerror("错误", f"转换失败: {str(e)}")
 
if __name__ == "__main__":
    root = tk.Tk()
    app = Base64ImageConverter(root)
    root.mainloop()

功能说明

1.上传图片:

点击“上传图片”按钮,选择本地图片文件(支持 .jpg, .jpeg, .png, .bmp 格式)。

图片路径会显示在界面上。

2.转换为Base64:

点击“转换为Base64”按钮,将上传的图片转换为 Base64 字符串,并显示在输入框中。

3.转换为图片:

在输入框中输入 Base64 字符串,点击“转换为图片”按钮,选择保存路径,将 Base64 字符串解码为图片并保存。

4.状态提示:

界面底部会显示当前操作的状态(如“图片已上传”、“图片已转换为Base64”等)。

到此这篇关于使用Python实现图片和base64转换工具的文章就介绍到这了,更多相关Python图片转base64内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!