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};
};