I'm trying export a string base64 that represents an image taken from canvas html5, this is the code in javascript:
我正在尝试导出一个字符串base64,表示从canvas html5中获取的图像,这是javascript中的代码:
var canvas1 = $("#canvas1")[0];
var ctx1 = canvas1.getContext('2d');
dataURL1 = canvas1.toDataURL();
Whit ajax I sent the image to server:
Whit ajax我把图片发送到服务器:
$.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:
在django的views.py中,我使用base64.b64decode将字符串导出到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:
在models.py我有:
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.
问题是图像保存时,文件imagen1.png已损坏,我无法打开它,有人可以帮我解决这个问题吗?还是有另外一种方法可以做到这一点?非常感谢你。
2 个解决方案
#1
1
I'm guessing you need to strip the data:
off the Data URI returned by canvas.toDataURL();
.
我猜你需要剥离数据:关闭canvas.toDataURL();返回的数据URI。
A quick google search found some code designed for parsing data uris in python https://gist.github.com/zacharyvoase/5538178 and another: dataurl.py
一个快速谷歌搜索发现一些代码设计用于解析数据uris在python https://gist.github.com/zacharyvoase/5538178和另一个:dataurl.py
#2
0
instead of this line: image_data = base64.b64decode(imagen1)
而不是这一行:image_data = base64.b64decode(imagen1)
use this line : image_data = base64.b64decode(imagen1[22:] + b'=' * (-len(imagen1[22:]) % 4))
使用此行:image_data = base64.b64decode(imagen1 [22:] + b'='*(-len(imagen1 [22:])%4))
#1
1
I'm guessing you need to strip the data:
off the Data URI returned by canvas.toDataURL();
.
我猜你需要剥离数据:关闭canvas.toDataURL();返回的数据URI。
A quick google search found some code designed for parsing data uris in python https://gist.github.com/zacharyvoase/5538178 and another: dataurl.py
一个快速谷歌搜索发现一些代码设计用于解析数据uris在python https://gist.github.com/zacharyvoase/5538178和另一个:dataurl.py
#2
0
instead of this line: image_data = base64.b64decode(imagen1)
而不是这一行:image_data = base64.b64decode(imagen1)
use this line : image_data = base64.b64decode(imagen1[22:] + b'=' * (-len(imagen1[22:]) % 4))
使用此行:image_data = base64.b64decode(imagen1 [22:] + b'='*(-len(imagen1 [22:])%4))