python图片读取优化,Python:优化内存中的图片(使用jpegoptim的StringIO和POpen)

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

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

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()))

解决方案

It is because you are writing to the same input buffer. Create a new 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'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值