Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

javascript - Load an html5 canvas into a PIL Image with Django

I'm trying to get the contents of an html5 canvas and pass it to my django server, where it will then be manipulated with PIL and saved as a PNG. Here's what I have so far:

From the HTML form, the user clicks the "update" button, the canvas's contents - with canvas.toDataURL() - gets dumped into a text box that is submitted via a POST form. Eventually this will be automatic, but not for now.

<input type="text" id="canvasData" name="canvasData"/>
<input type='button' value="update" onclick='jscript:updateData();'>
<canvas id="sketch"></canvas>
<script type="text/javascript">
    function jscript:updateData() {
        $('#canvasData')[0].value = $('canvas')[0].toDataURL();
    }
</script>

The canvasData is in the form of 'data:image/png;base64,iVBORw0KGgoAAAA...etc...=' when it gets sent over. Then I deal with it in django:

from PIL import Image
...
canvasData = request.POST.get('canvasData', '')
im = Image.somehowLoad(canvasData)
...
im.save('canvas.png')

And this is where i'm stuck. I can't figure out how to get the base64-encoded data url to load up the image into a usable form with PIL.

Thanks!

edit: here's the code for the bottom comment:

>>> d
'data:image/png;base64,iVBORw0K'
>>> d.strip('data:image/png;base64,')
'VBORw0K'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
import re

datauri = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='

imgstr = re.search(r'base64,(.*)', datauri).group(1)

output = open('output.png', 'wb')

output.write(imgstr.decode('base64'))

output.close()

or if you need to load it into PIL :

import cStringIO

tempimg = cStringIO.StringIO(imgstr.decode('base64'))

im = Image.open(tempimg)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...