首页 > 解决方案 > 在上传期间调整图像大小(Canvas 和 SimpleImage 库)

问题描述

我的目标是让用户上传本地图像。我在画布元素中绘制此图像。在此画布元素之上,我创建了另一个画布,用于在其上绘制框,以便框覆盖上传的图像。

我希望以特定尺寸上传图像,例如最大 100 宽度和最大 100 高度。仅以最大高度和最大宽度显示图像对我来说是不够的:100,它在上传过程中物理上需要调整大小。因为如果我把一张超大图片放在一个 100x100 的画布上,那么它上面的框就会变得非常小,我需要它们的大小相同,无论画布中的图像是什么大小。

以下是代码: HTML:

  <div style="position: relative;">
    <canvas id="can" 
      style="position: absolute; left: 0; top: 0; z-index: 0;max-width:80%;"></canvas>
    <canvas id="box" 
      style="position: absolute; left: 0; top: 0; z-index: 1;max-width:80%;"></canvas>
   </div>

<input type="file" multiple="false" accept="image/*" id="finput" onchange="upload()">

和 JS:

function upload() {
  //Get input from file input
  var fileinput = document.getElementById("finput");
  //Make new SimpleImage from file input
  image = new SimpleImage(fileinput);
  
  //Get canvas
  var canvas = document.getElementById("can");
  //Draw image on canvas
  image.drawTo(canvas);
}

我使用 simpleImage 库,因为它可以让我提取图像的 RGB 值。

标签: javascripthtmlcsscanvasfile-upload

解决方案


let originalWidth;
let originalHeight;
let imageWidth;
let imageHeight;

const load = result => {
    return new Promise((fulfill, _reject) => {
      let imageObj = new Image();

      imageObj.onload = () => fulfill(imageObj);
      imageObj.src = result;
    });
}

const upload = () => {
    const fileinput = document.getElementById("finput");
    const canvas = document.getElementById("can");

    let context = canvas.getContext("2d");

    const reader = new FileReader();

    reader.onload = event => {
        Promise.all([
            load(event.target.result)
          ])
          .then(images => {
              originalWidth = images[0].width;
              originalHeight = images[0].height;

              imageWidth = originalWidth;
              imageHeight = originalHeight;

              imageWidth = 200; // Fixed value
              // Value proportional to width. Keeping to scale without distorting the image ( recommended )
              imageHeight = originalHeight * (imageWidth / originalWidth);

              context.drawImage(images[0], positionX, positionY, imageWidth, imageHeight);
           })
    }

    reader.readAsDataURL(fileinput);
}

推荐阅读