【发布时间】:2018-08-17 10:11:57
【问题描述】:
我正在尝试将附加图像转换为base64。我尝试过这样,但出现错误。
https://jsbin.com/lubosabore/edit?html,js,console,output
function getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to
// guess the original format, but be aware the using "image/jpg"
// will re-encode the image.
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
$(function(){
// alert()
$('#fileId').on('change', function (e) {
console.log('ddd');
var file = e.target.files[0];
console.log(getBase64Image(file))
})
})
我附上了一个png值
它没有打印 base64 值
【问题讨论】:
-
@AndreiGheorghiu 太复杂了——不需要服务器往返。
-
@user944513 感谢您提供 jsbin 链接,这很有帮助,并且在将来它还有助于在您的问题中包含确切的错误消息。
标签: javascript jquery