开发者

image file from MemoryStream (IronPython web service)

开发者 https://www.devze.com 2023-01-30 13:24 出处:网络
I used to use CPython + PIL + bottle to serve image files on my web site. I used the code below to serve the image data from the PIL memory directly.

I used to use CPython + PIL + bottle to serve image files on my web site. I used the code below to serve the image data from the PIL memory directly.

# works well in CPython
@route('/test')
def index():
    response.set_content_type开发者_如何学编程('image/png')
    img = DrawSomePILImage()
    output = StringIO.StringIO()
    img.save(output,'PNG')
    contents = output.getvalue()
    output.close()
    return contents

Now, I need to use IronPython instead of CPython to serve image files. And I'm trying to serve the image of the Microsoft Chart Control (System.Windows.Forms.DataVisualization.Charting).

# image is broken in IronPython
@route('/test')
def index():
    response.set_content_type('image/png')
    cht = GetChartControl()
    stream = MemoryStream()
    cht.SaveImage(stream, ChartImageFormat.Png)
    contents = System.Text.ASCIIEncoding.ASCII.GetString(stream.ToArray())
    stream.Close()
    return contents

But this does not work. The served image file on the web browser is broken. Can you guys help me how to make this ironpython code work?


It's this line:

contents = System.Text.ASCIIEncoding.ASCII.GetString(stream.ToArray()) 

In doing this, you are sending a string which is the encoded form of the bytes in the image when in reality, you just want to send the bytes.

I imagine if you change it to this:

contents = stream.ToArray()

It might work (I'm not a python guy). The idea here is to pass the bytes, not a string back to the client making the request.


I found an answer (or just a workaround). The str of ironpython is unicode, while str of of cpython(below 3) is not. So i removed the casting part of unicode data to WSGI compatible in Bottle framework.(line 543 of bottle.py), and return the stream data as below.

contents = ''.join([chr(v) for v in stream.ToArray()])
0

精彩评论

暂无评论...
验证码 换一张
取 消