图片based64编码解码python代码

图片based64编码解码python代码

import base64
from PIL import Image

def image_to_base64(image_path):
    # 打开图片文件
    image = Image.open(image_path)
    # 将图片转换为二进制数据
    image_bytes = None
    with open(image_path, 'rb') as image_file:
        image_bytes = image_file.read()
    # 将二进制数据编码为Base64字符串
    image_base64 = base64.b64encode(image_bytes).decode('utf-8')
    return image_base64

def base64_to_image(base64_string, output_path):
    # 将Base64字符串解码为二进制数据
    image_data = base64.b64decode(base64_string)
    # 将二进制数据写入文件
    with open(output_path, 'wb') as file:
        file.write(image_data)
    print(f"Image saved to {output_path}")

# 使用示例
image_path = '1.jpg'
base64_string = image_to_base64(image_path)
print(f"Image encoded to Base64: {base64_string}")

# 解码示例
output_path = 'output_image.jpg'
base64_to_image(base64_string, output_path)

相关推荐

  1. 图片based64编码解码python代码

    2024-06-15 05:18:03       30 阅读
  2. 图片Base64编码

    2024-06-15 05:18:03       35 阅读
  3. Base64编码解码

    2024-06-15 05:18:03       26 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-15 05:18:03       85 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-15 05:18:03       92 阅读
  3. 在Django里面运行非项目文件

    2024-06-15 05:18:03       72 阅读
  4. Python语言-面向对象

    2024-06-15 05:18:03       84 阅读

热门阅读

  1. ray框架训练阶段和 Serve 阶段对比

    2024-06-15 05:18:03       40 阅读
  2. 大数据开发语言Scala(一) - Scala入门

    2024-06-15 05:18:03       32 阅读
  3. C# 事件(Event)定义及其使用

    2024-06-15 05:18:03       32 阅读
  4. fastapi搭建的python项目,怎么才能出来API接口文档

    2024-06-15 05:18:03       33 阅读
  5. 一文搞懂OPC质量码

    2024-06-15 05:18:03       66 阅读