我目前有一个可用的JS代码来调整客户端图像的大小。现在我需要将这个已调整大小的图像发送到我的烧瓶应用程序。我的烧瓶应用程序然后将其上传到aws3。
这是我用来调整图像大小的JS代码,它还生成一个dataurl:
$( "input[type='file']" ).change(function() {
// from an input element
var filesToUpload = this.files;
console.log(filesToUpload);
var img = document.createElement("img");
img.src = window.URL.createObjectURL(this.files[0]);
$( img ).load(function() {
var MAX_WIDTH = 600;
var MAX_HEIGHT = 450;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/png");
//var file = canvas.mozGetAsFile("foo.png");
});
});
在我的烧瓶应用程序中,我使用form.company_logo_image_path.data.read()
来获取文件内容,但现在即使调整大小调整后的图像也会被忽略。那是因为我仍然从输入中获取旧图像。我需要获得画布图像。
如何使用dataurl在我的烧瓶应用中获取图像? 或者还有其他方式吗?
这是我在获得dataurl后立即使用的AJAX代码:
$.ajax({
type: "POST",
url: "/profil/unternehmen-bearbeiten",
data:{
imageBase64: dataurl
}
}).done(function() {
console.log('sent');
});
在我的python视图中,我尝试访问dataurl:
data_url = request.values['imageBase64']
#data_url = request.args.get('image') # here parse the data_url out http://xxxxx/?image={dataURL}
print data_url
content = data_url.split(';')[1]
image_encoded = content.split(',')[1]
body = base64.decodebytes(image_encoded.encode('utf-8'))
# Then do whatever you want
print body, type(body)
答案 0 :(得分:1)
每https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL,你得到的结果如下:
var canvas = document.getElementById('canvas');
var dataURL = canvas.toDataURL();
console.log(dataURL);
// "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby
// blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC"
然后只需使用base64解码文件。
import base64
from flask import request
def your_view():
data_url = request.args.get('image') # here parse the data_url out http://xxxxx/?image={dataURL}
content = data_url.split(';')[1]
image_encoded = content.split(',')[1]
body = base64.decodebytes(image_encoded.encode('utf-8'))
# Then do whatever you want
身体就是你所需要的。