在上传期间调整图像大小(Canvas 和 SimpleImage 库)

Resize image during upload (Canvas and SimpleImage library)

我的目标是让用户上传本地图片。我在 canvas 元素中绘制此图像。在这个 canvas 元素之上,我创建了另一个 canvas,我用它来绘制框,以便框覆盖上传的图像。

我希望以特定尺寸上传图片,例如最大宽度 100 和最大高度 100。仅让图像以 max-height 和 max-width: 100 显示是不够的,它在上传过程中需要实际调整大小。因为如果我把一张超大的图片放在 100x100 canvas 中,那么它上面的框就会变得非常小,无论 canvas 中的图像大小如何,我都需要它们的大小相同.

代码如下: 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 值。

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