gpt4 book ai didi

javascript - html canvas可以绘制上传的图像吗?

转载 作者:行者123 更新时间:2023-11-28 01:58:00 26 4
gpt4 key购买 nike

我正在尝试使用 javascript 创建上传图像调整大小功能。但是,使用filereader将上传文件转换为base64,在 Canvas 上没有显示图像。相反,如果我使用外部图像,并将其转换为 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};
};

最佳答案

您可以引用这个 fiddle ,http://jsfiddle.net/aliasm2k/tAum2/一些想法。它可能对你有帮助。这是我实现的一个 fiddle ,只是为了有趣地生成用户选择的图像的缩略图。它使用 FileReader API 选择文件,然后将缩略图加载到 Canvas 上。

就我个人而言,我更喜欢经典 JS 而不是使用 jQuery,并且使用了很多事件处理程序

oFileIn.addEventListener()
oFileReader.addEventListener()
oImage.addEventListener()

关于javascript - html canvas可以绘制上传的图像吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18809671/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com