[英]Image Compression using LZMA Python
有什么方法可以使用 Python 通过 LZMA 压缩图像。 预先存在的 package 可以压缩文本文件,但我找不到任何使用图像的方法。 任何帮助都很棒!
谢谢!
import lzma
data = b"Insert Data Here"
with lzma.open("file.xz", "w") as f:
f.write(data)
注意 data 是字节(b-prefix),因此您可以以二进制模式读取任何文件并将其内容用作data
,例如,如果您说文件名为image.png
,您可能会这样做
import lzma
with open("image.png", "rb") as f:
data = f.read()
with lzma.open("image.png.xz", "w") as f:
f.write(data)
预先存在的 package 与bytes
类型一起工作,它可以表示任何二进制数据,而不仅仅是文本。 你只需要让你的图像采用这种格式。 如果您的图像已经存储在文件系统中,这应该可以:
import lzma
with open('myimage.jpg', 'rb') as f: # read bytes mode
image_bytes = f.read()
compressor = lzma.LZMACompressor()
compressed_bytes = compressor.compress(image_bytes)
compressed_bytes += compressor.flush()
with open('myimage.jpg.lzma', 'wb') as f:
f.write(compressed_bytes)
Of course there is, first read the pictures with img = cv2.imread() using opencv, then the img value becomes a numpy list anyway, then convert this numpy list to a python list and you can save the lists in db or anywhere as文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.