使用Java来调整图像的大小,而无需在DOM上渲染画布 [英] Resizing a image with Javascript without rendering a canvas on the DOM

查看:154
本文介绍了使用Java来调整图像的大小,而无需在DOM上渲染画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了许多其他有趣的线程:

I've seen this interesting thread among many others: Resize a Base-64 image in JavaScript without using canvas

但是,当我使用创建屏幕外画布时

However when i create an off screen canvas using

const canvas = document.createElement('canvas');

结果图像是透明的,并且大小甚至与参数都不匹配. 如果我在DOM上的画布上绘画,一切都会很好

the result image is transparent and the size does not even match the parameters. If i draw on a canvas from the DOM everything works fine

const canvas = document.getElementById('canvas');

这是我的调整大小功能,可保持输入图像的比例:

Here is my resize function that keeps the input image ratio :

resizeImage(file) {
    const canvas = document.createElement('canvas');
    // const canvas = document.getElementById('canvas');
    const context = (<HTMLCanvasElement>canvas).getContext('2d');
    // set maximum width and height of output image
    const maxW = 400;
    const maxH = 400;
    const img = new Image;

    img.onload = function () {
        const iw = img.width;
        const ih = img.height;
        const scale = Math.min((maxW / iw), (maxH / ih));
        const iwScaled = iw * scale;
        const ihScaled = ih * scale;
        console.log(iwScaled + ' ' + ihScaled);
        (<HTMLCanvasElement>canvas).width = iwScaled;
        (<HTMLCanvasElement>canvas).height = ihScaled;
        context.drawImage(img, 0, 0, iwScaled, ihScaled);
    }
    img.src = URL.createObjectURL(file);
    // retrieve output img in base64 format
    console.log((<HTMLCanvasElement>canvas).toDataURL());
}

它将来自HTML输入的文件(文件)作为参数. 任何帮助将不胜感激,谢谢.

It takes a file (File) from a HTML input as parameter. Any help would be appreciated, thank you.

推荐答案

加载完成后,您将获得Base-64映像.

you get a Base-64 image when load is complete.

function resizeImage(file) {
      var canvas = document.createElement('canvas');
      var context = canvas.getContext('2d');
      var maxW = 400;
      var maxH = 400;
      var img = document.createElement('img');

      img.onload = function() {
        var iw = img.width;
        var ih = img.height;
        var scale = Math.min((maxW / iw), (maxH / ih));
        var iwScaled = iw * scale;
        var ihScaled = ih * scale;
        canvas.width = iwScaled;
        canvas.height = ihScaled;
        context.drawImage(img, 0, 0, iwScaled, ihScaled);
        console.log(canvas.toDataURL());
        document.body.innerHTML+=canvas.toDataURL();
      }
      img.src = URL.createObjectURL(file);
    }
    document.getElementById("file").addEventListener("change", function() {
      file = file.files[0];
      if (file) {
        resizeImage(file);
      }
    });

<input id="file" type="file">

这篇关于使用Java来调整图像的大小,而无需在DOM上渲染画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆