从STDIN读取PNG的Python PIL [英] Python PIL reading PNG from STDIN

查看:117
本文介绍了从STDIN读取PNG的Python PIL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用PIL从STDIN读取png图像时遇到问题.当图片由PIL编写时,全部都是已加扰,但是如果我使用打开的简单文件来写入文件,写入并关闭文件完全保存.

I am having a problem reading png images from STDIN using PIL. When the image is written by PIL it is all scrambled, but if I write the file using simple file open, write and close the file is saved perfectly.

我有一个程序,可以不压缩将png文件按顺序转储到stdout,我使用python脚本读取该流,该脚本可以读取数据并在几乎所有png上执行一些例程.转储数据的程序会写一个特定的字符串来分隔PNG文件,该字符串为"{fim:FILE_NAME.png}"

I have a program that dumps png files to stdout in a sequence, with no compression, and I read that stream using a python script which is suposed to read the data and do some routines on almost every png. The program that dumps the data writes a certain string to delimiter the PNGs files, the string is "{fim:FILE_NAME.png}"

脚本类似于:

import sys
import re
from PIL import Image

png = None

for linha in sys.stdin: 
    if re.search('{fim:', linha):
        fname = linha.replace('{fim:','')[:-2]

        # writes data directly to file, works fine
        #f = open("/tmp/%s" % fname  , 'w')
        #f.write(png)
        #f.close()

        # create a PIL Image from data and writes to disk, fails fine
        im = Image.frombuffer("RGB",(640,480),png, "raw", "RGB", 0, 1)
        #im = Image.fromstring("RGB",(640,480),png)
        im.save("/tmp/%s" % fname)

        png = None

    else:
        if png is None:
            png = linha
        else:
            png+= linha

imagemagick从错误的图像中进行识别:

imagemagick identify from a wrong image:

/tmp/1349194042-24.png PNG 640x480 640x480 + 0 + 0 8位DirectClass 361KiB 0.010u 0:00.019

/tmp/1349194042-24.png PNG 640x480 640x480+0+0 8-bit DirectClass 361KiB 0.010u 0:00.019

imagemagick从工作图像中识别:

imagemagick identify from a working image:

/tmp/1349194586-01.png PNG 640x480 640x480 + 0 + 0 8位DirectClass 903KiB 0.010u 0:00.010

/tmp/1349194586-01.png PNG 640x480 640x480+0+0 8-bit DirectClass 903KiB 0.010u 0:00.010

有人知道发生了什么吗?关于小/大尾数吗?我尝试了Image.frombufferImage.fromstring,不同的模式,但是什么也没有.似乎PIL期望在缓冲区上有更多信息.

Does any one have an idea of what is happening? Is it something about little/big endians? I have tried Image.frombuffer, Image.fromstring, different modes, but nothing. It seems that there is more information on the buffer that the PIL expects.

谢谢

推荐答案

如果png变量包含PNG文件中的二进制数据,则无法使用frombuffer读取它:用于读取原始像素数据.而是使用StringIOImage.open,即:

If the png variable contains the binary data from a PNG file, you can't read it using frombuffer: that is used for reading raw pixel data. Instead, use StringIO and Image.open, i.e.:

img = Image.open(StringIO.StringIO(png))

这篇关于从STDIN读取PNG的Python PIL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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