如何保存JPG图片字节信息并跨设备通过该字节数据重建原图
保存图像字节数据以跨设备重建图像
你现有的代码已经能读取图像的原始字节并写入新文件,要让这些字节能在不同电脑上重建出相同图像,有几种简单可靠的方式:
方法1:直接保存原始二进制文件(最直接)
你的原代码本质就是做这件事——把图像的原始字节写入二进制文件。这种方式本身就跨平台,因为二进制数据不依赖操作系统的编码或格式,只要在另一台电脑上用同样的二进制写入方式读取,就能还原图像:
# 读取原始字节 with open("image.jpg", 'rb') as original_file: original_bytes = original_file.read() # 保存字节到二进制文件(可传输到其他电脑) with open("image_bytes.bin", 'wb') as byte_file: byte_file.write(original_bytes) # 在其他电脑上还原图像 with open("image_bytes.bin", 'rb') as byte_file: restored_bytes = byte_file.read() with open("restored_image.jpg", 'wb') as restored_file: restored_file.write(restored_bytes)
方法2:编码为Base64字符串保存(适合文本场景)
如果需要把字节数据嵌入到文本文件、JSON或代码里,可以把二进制字节编码成Base64字符串,这是一种纯文本格式,跨设备传输不会乱码:
import base64 # 读取并编码 with open("image.jpg", 'rb') as original_file: original_bytes = original_file.read() base64_str = base64.b64encode(original_bytes).decode('utf-8') # 保存Base64字符串到文本文件 with open("image_base64.txt", 'w', encoding='utf-8') as txt_file: txt_file.write(base64_str) # 在其他电脑上解码还原 with open("image_base64.txt", 'r', encoding='utf-8') as txt_file: base64_str = txt_file.read() restored_bytes = base64.b64decode(base64_str) with open("restored_image.jpg", 'wb') as restored_file: restored_file.write(restored_bytes)
方法3:用Pickle序列化保存(适合Python对象集合)
如果要和其他Python对象一起保存,可使用pickle序列化字节对象,注意只在Python环境中使用:
import pickle # 读取并序列化 with open("image.jpg", 'rb') as original_file: original_bytes = original_file.read() with open("image_pickle.pkl", 'wb') as pickle_file: pickle.dump(original_bytes, pickle_file) # 在其他电脑上反序列化还原 with open("image_pickle.pkl", 'rb') as pickle_file: restored_bytes = pickle.load(pickle_file) with open("restored_image.jpg", 'wb') as restored_file: restored_file.write(restored_bytes)
不管用哪种方式,只要能完整保存并还原原始的original_bytes字节数据,就能在任何电脑上重建出和原图像完全一致的文件。
内容的提问来源于stack exchange,提问作者Ashir Agrawal
相关产品推荐
相关产品推荐

