[英]Base64 convert from image not getting base64 string
I am convertin image to base64 string using following code 我正在使用以下代码将图像转换为base64字符串
function getBase64Image() {
p = document.getElementById("fileUpload").value;
img1.setAttribute('src', p);
canvas.width = img1.width;
canvas.height = img1.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img1, 0, 0);
var dataURL = canvas.toDataURL("image/jpg");
$("#b64").val(dataURL);
}
But what I am getting in dataURL is Data;
但是我在dataURL中得到的是
Data;
and there is not base64 string contained. 并且不包含base64字符串。
How can I fetch base64 string from image? 如何从图像中获取base64字符串?
Here's a simple example: 这是一个简单的例子:
// assuming that you have jQuery lib
$('#fileUpload').on('change', function(e) {
if (this.files.length === 0) return;
var imageFile = this.files[0];
var reader = new FileReader();
// when reading of image file completes
reader.onloadend = function() {
var tempImg = new Image();
tempImg.src = reader.result;
// when image is loaded
tempImg.onload = function() {
canvas.getContext("2d").drawImage(tempImg, 0, 0);
}
}
// start reading
reader.readAsDataURL(imageFile);
});
Hope this helps!! 希望这可以帮助!!
i think this could work if you use load callback because the loading is async. 我认为这可以工作,如果您使用加载回调,因为加载是异步的。 not sure what your fileUpload is tho, but if's a text field pasting a url
不确定您的fileUpload是什么,但是如果是粘贴url的文本字段
function getBase64Image() {
p = document.getElementById("fileUpload").value;
img1.setAttribute('src', p);
img1.setAttribute('load', fileLoaded);
function fileLoaded(e) {
canvas.width = img1.width;
canvas.height = img1.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img1, 0, 0);
var dataURL = canvas.toDataURL("image/jpeg");
$("#b64").val(dataURL);
}
}
the image type is also image/jpeg. 图像类型也是image / jpeg。 jpg won't work or, it will return png instead since it isn't valid.
jpg无法使用,否则会返回png,因为它无效。 and cross-origin can be a problem iirc.
跨域可能是一个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.