Python:优化内存中的图片(使用jpegoptim的StringIO和POpen) [英] Python: Optimizing Images in Memory (StringIO & POpen with jpegoptim)

查看:234
本文介绍了Python:优化内存中的图片(使用jpegoptim的StringIO和POpen)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用各种库的STDIN版本(在此示例中为jpegoptim)压缩图像而不接触磁盘.

I'm trying to compress images without touching disk using the STDIN version of various libraries(jpegoptim in this example).

此代码不会返回经过优化(jpegoptim压缩)的图像.

This code does not return an optimized(jpegoptim compressed) image.

有人可以帮助或解释为什么将Popen()与StringIO.StringIO()对象一起使用不会返回图像的优化版本吗?如果我将文件保存到磁盘,则可以正常工作.

Can someone please help or explain why this usage of Popen() with a StringIO.StringIO() object does not return the optimized version of the image? If I save the file to disk, it works just fine.

import sys
import urllib2 as urllib
import StringIO

from subprocess import Popen, PIPE, STDOUT
fp = urllib.urlopen('http://www.path.to/unoptimized.jpg')
out_im2 = StringIO.StringIO(fp.read()) # StringIO Image
print "Image Size: %s" % format(sys.getsizeof(out_im2.getvalue()))
subp = Popen(["/usr/bin/jpegoptim", "-"], shell=True, stdout=PIPE, stdin=PIPE, stderr=STDOUT)
image_str = subp.communicate(input=out_im2.getvalue())[0]
out_im2.write(image_str)

##This should be a different size if it worked! It's not
print "Compressed JPG: %s" % format(sys.getsizeof(out_im2.getvalue()))

推荐答案

这是因为您正在写入相同的输入缓冲区.创建一个新的StringIO().

It is because you are writing to the same input buffer. Create a new StringIO().

StringIO缓冲区最初扩展为第一个未压缩jpeg的大小.然后,使用新的较短的字符串缓冲区覆盖从0位置开始的缓冲区,但是它不会自动截断缓冲区或其他内容. StringIO缓冲区的大小仍然相同,实际上,所有尾随数据都将保留原始图像中的垃圾.

StringIO buffer expands to the size of the first uncompressed jpeg initially. Then you write over that buffer starting at 0 position with the new shorter string buffer, but it doesn't auto-truncate your buffer or anything. The StringIO buffer is still the same size and in fact all the trailing data will be left over junk from the original image.

In [1]: import StringIO

In [2]: out = StringIO.StringIO("abcdefg")

In [3]: out.getvalue()
Out[3]: 'abcdefg'

In [4]: out.write("123")

In [5]: out.getvalue()
Out[5]: '123defg'

这篇关于Python:优化内存中的图片(使用jpegoptim的StringIO和POpen)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆