开发手记(二)——图片转换成base64编码

1 Windows系统powershell命令

1.1 完整清晰的多步命令

# 将图片转换为 Base64 字符串
$imagePath = "C:\path\to\your\image.jpg"
$imageBytes = [System.IO.File]::ReadAllBytes($imagePath)
$base64String = [System.Convert]::ToBase64String($imageBytes)

# 输出结果
$base64String

# (可选)保存到文本文件
$base64String | Out-File -FilePath "output_base64.txt" -Encoding UTF8

 

1.2 一行简单命令

[Convert]::ToBase64String([IO.File]::ReadAllBytes("C:\path\to\image.jpg")) | Out-File "output.txt"

 

2 Linux系统自带命令

2.1 base64命令

base64 input_image.jpg > output_base64.txt

读取input_image.jpg路径指向的图片文件,base64编码后输出到output_base64.txt路径指向的文本文件。

若无需保存文件,则仅执行

base64 input_image.jpg

 

2.2 openssl命令

openssl enc -base64 -in input_image.jpg -out output_base64.txt

路径含义和2.1相同,-in参数代表指定输入文件,-out参数代表指定输出文件。

 

3 编程方法

import base64

def image_to_base64(image_path):
    with open(image_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
    # 可选:添加 Data URL 前缀(适用于HTML中直接显示)
    return f"data:image/jpeg;base64,{encoded_string}"

# 使用示例
image_path = "example.jpg"  # 替换为你的图片路径
base64_str = image_to_base64(image_path)
print(base64_str)

以python为例,可以导入库对图片进行编码。编码最后的效果可以根据实际需要修改。

posted @ 2025-09-08 19:05  学术大垃圾  阅读(34)  评论(0)    收藏  举报