我需要使用<input type="file">
上传图片,我也希望当我点击上传按钮时,它会创建缩略图并保存“图片”和“缩略图”,我需要帮助。
有我的代码。 在这里,我已经减小了图像的大小,但我无法自动下载该文件。
var resizeImage = function(src,width,height) {
var orig_src = new Image(),
resize_canvas = document.createElement('canvas');
orig_src.src = src;
resize_canvas.width = width;
resize_canvas.height = height;
resize_canvas.getContext('2d').drawImage(orig_src, 0, 0, width, height);
$(".resize-image").attr('src', resize_canvas.toDataURL("image/png"));
}
$(function(){
resizeImage('thumb-1920-358764.jpg',100,100); // Image path, width, height
});
<img class="resize-image" src="thumb-1920-358764.jpg" />`
<img class="resize-image" src="thumb-1920-358764.jpg" />`
答案 0 :(得分:0)
您可以将<img>
元素'crossOrigin
属性设置为"anonymous"
,创建FormData()
对象以将图像存储为File
个对象,使用{{1 } canvas.toBlob()
,.toDataURL()
事件在原始图片上动态创建load
调用<img>
,首先在第二个.toBlob()
元素,<canvas>
结果.append()
到Blob
个实例,然后在原始FormData
元素上调用.toBlob()
并重复调用<canvas>
,将.append()
设置为Blob
},可以使用FormData
或XMLHttpRequest()
fetch()
var resizeImage = function(src, width, height, fd, input) {
var orig_src = new Image(),
resize_canvas = document.createElement('canvas');
orig_src.crossOrigin = "anonymous";
orig_src.src = src;
orig_src.onload = function() {
resize_canvas.width = width;
resize_canvas.height = height;
resize_canvas.getContext('2d').drawImage(orig_src, 0, 0, width, height);
var imageCanvas = document.createElement("canvas");
imageCanvas.getContext("2d").drawImage($(".resize-image")[0], 0, 0);
imageCanvas.toBlob(function(blob) {
imageBlob = blob;
fd.append("originalImage", blob);
});
resize_canvas.toBlob(function(blob) {
canvasBlob = blob;
fd.append("resizedImage", blob);
$(".resize-image")
.attr('src', URL.createObjectURL(blob));
input.removeAttr("disabled");
});
}
}
$(function() {
var canvasBlob, imageBlob, fd = new FormData(),
input = $("input[type=button]");
resizeImage("https://upload.wikimedia.org/wikipedia/commons/d/d4/Wikipedesketch1.png", 100, 100, fd, input); // Image path, width, height
input.on("click", function() {
for (let [key, prop] of fd) {
console.log(key, prop)
}
})
});