我正在尝试使用javascript创建上传图片大小调整功能。但是,使用 filereader 将上传文件转换为base64,在画布上不提供任何图像。相反,如果我使用外部图像,并将其转换为base64,该功能就像一个魅力。怎么会这样?有什么问题?
这是我的代码,它很长。
//When changes are made to our input field
$ ('#input-file').change (function (evt) {
//The selected file is recovered
var file = evt.target.files [0];
//And processFiles function that will resize and send the file to the server is started
processFiles (file);
});
processFiles = function (file) {
var reader = new FileReader ();
//When the file has been completely read, the function will be executed ResizeImage
reader.onloadend = function (evt) {
//Reader.result represents our base64 encoded file
ResizeImage (reader.result, file);
};
//Allows you to play the file
reader.readAsDataURL (file);
};
ResizeImage = function (data, file) {
var fileType = file.type,
maxWidth = 960
maxHeight = 960;
//The file is loaded in a <img>
var image = new Image ();
image.src = data;
//Once the image is loaded, the following operations are performed
image.onload = function () {
//The ImageSize function calculates the final file size keeping the proportions
var size = ImageSize (image.width, image.height, maxWidth, maxHeight)
ImageWidth = size.width,
imageHeight = size.height,
//We create a canvas element
//canvas = document.createElement ('canvas');
canvas=document.getElementById('hahaha')
canvas.width = ImageWidth;
canvas.height = imageHeight;
var ctx = canvas.getContext ("2d");
//DrawImage will allow resizing the image
//This is our image here
var img=document.getElementById('haha')
ctx.drawImage (img, 0, 0, ImageWidth, imageHeight);
//Allows you to export the contents of the canvas element (our resized image) base64
data = canvas.toDataURL(fileType);
alert(data)
//All the elements used for resizing is suppressed
delete image;
delete canvas;
//SubmitFile (data);
}
};
//Function to resize an image keeping the proportions
ImageSize = function (width, height, maxWidth, maxHeight) {
var newWidth = width,
newHeight = height;
if (width> height) {
if (width> maxWidth) {
newHeight = maxWidth / width;
newWidth = maxWidth;
}
else {}
if (height> maxHeight) {
newWidth = maxHeight / height;
newHeight = maxHeight;
}
}
return {width: newWidth, height: newHeight};
};
答案 0 :(得分:1)
你可以参考这个小提琴,http://jsfiddle.net/aliasm2k/tAum2/来表达一些想法。它可能会帮助你。这是我实现的一个小提琴,只是为了生成用户所选图像的缩略图。它使用FileReader API选择文件,然后在画布上加载缩略图。
我个人认为经典的JS比使用jQuery更多,而且使用了很多事件处理程序
oFileIn.addEventListener()
oFileReader.addEventListener()
oImage.addEventListener()