Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert image from base64 to image and save in database in django

I'm trying export a string base64 that represents an image taken from canvas html5, this is the code in javascript:

var canvas1 = $("#canvas1")[0];
var ctx1 = canvas1.getContext('2d');
dataURL1 = canvas1.toDataURL();

Whit ajax I sent the image to server:

$.ajax({
    type: "POST",
    url: "/regiter_respuesta_agilidad/",
    data:{
        'imagen1': dataURL1,
    }
});

In views.py of django I use base64.b64decode to export the string to image:

imagen1 = request.POST['imagen1']
image_data = base64.b64decode(imagen1)
imagene = ContentFile(image_data, 'imagen1.png')
answer = Answer(imagen=imagene)

In models.py I have:

class Answer(models.Model):
    imagen = models.ImageField(upload_to=url)

The Problem is when the image is saved, the file imagen1.png is corrupted and I can't open it, Can someone help me with this problem?, or is there another way to do this? thank you very much.

like image 917
hypuerta Avatar asked Nov 17 '13 23:11

hypuerta


1 Answers

I'm guessing you need to strip the data: off the Data URI returned by canvas.toDataURL();.

A quick google search found some code designed for parsing data uris in python https://gist.github.com/zacharyvoase/5538178 and another: dataurl.py

like image 134
Kevin Stone Avatar answered Oct 04 '22 20:10

Kevin Stone