当前位置: 代码网 > it编程>前端脚本>Python > 使用Python实现图片和base64转换工具

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

2025年02月09日 Python 我要评论
简介使用python的base64模块来实现图片和base64编码之间的转换。可以将图片转换为base64编码,以及将base64编码转换回图片并保存。依赖库该工具仅依赖 python 标准库(tki

简介

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

依赖库

该工具仅依赖 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内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com