我想创建图像的缩略图,图像和缩略图都将存储在

时间:2017-10-07 08:27:35

标签: javascript php jquery

我需要使用<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" />`

1 个答案:

答案 0 :(得分:0)

您可以将<img>元素'crossOrigin属性设置为"anonymous",创建FormData()对象以将图像存储为File个对象,使用{{1 } canvas.toBlob().toDataURL()事件在原始图片上动态创建load调用<img>,首先在第二个.toBlob()元素,<canvas>结果.append()Blob个实例,然后在原始FormData元素上调用.toBlob()并重复调用<canvas>,将.append()设置为Blob },可以使用FormDataXMLHttpRequest()

发布到服务器

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