views:

664

answers:

3

I need to upload the canvas image data to the server (database) on the fly, i.e., I need to create a form and with an input=file, and post the image data without any user interaction.

A: 

You can get the image data in the form of a data: url, this only works in Firefox and Opera so far though.

http://cow.neondragon.net/index.php/681-Canvas-Todataurl

Jeffrey Aylesworth
...and safari (and every other webkit based browser)
olliej
+2  A: 

You don't need a file input, just get the data with ctx.getImageData() and post it to the server with Ajax.

https://developer.mozilla.org/En/HTML/Canvas/Pixel%5Fmanipulation%5Fwith%5Fcanvas

But I have to tell you that you won't be able to get the image data in IE, even with ExCanvas.

Fabien Ménager
Did anyone got this to actually work? I got that data returned from getImageData() can be POSTed to the server, but I can't figure out how. I tried using different options in jQuery.ajax and jQuery.post, but I couldn't figure how to specify image data in ajax request. My server can't interpret the data I send. I couldn't find any code examples either. Do you have any pointers? (I made sure server is working correct by doing the same request with Curl as client.)Thanks.
Jayesh
ok, got it working. pasted code in the answer.
Jayesh
+1  A: 

FWIW, this is how I got it working.

My server is in google app engine. I send canvas.toDataURL()'s output as part of post request using jQuery.post. The data URL is base64 encoded image data. So on server I decode it and convert it to image

import re 
import base64
class TnUploadHandler(webapp.RequestHandler):
    dataUrlPattern = re.compile('data:image/(png|jpeg);base64,(.*)$')
    def post(self):
        uid = self.request.get('uid')
        img = self.request.get('img')

        imgb64 = self.dataUrlPattern.match(img).group(2)
        if imgb64 is not None and len(imgb64) > 0:
            thumbnail = Thumbnail(
                    uid = uid, img = db.Blob(base64.b64decode(imgb64)))
            thumbnail.put()

From client I send the data like this:

$.post('/upload',
        {
            uid : uid,
            img : canvas.toDataURL('image/jpeg')
        },
        function(data) {});

This may not be the best way to do it, but it works.

Jayesh