繁体   English   中英

带有参数image,width,height的JS函数,并返回调整后的基础64位图像数据

[英]JS Function with parameters image, width, height and return a resized base 64 image data

我正在尝试创建一个函数,该函数接受具有宽度和高度的base 64图像数据,并在javascript中返回具有给定宽度和高度的已调整大小的base 64图像数据。 本质上是

function imageResize(img, width, height) {
    var newImg; 
    //PLAN:transform img with new width and height.
    // - change width
    // - change height
    // - convert back to base 64 data
    return newImg;
}  

这篇文章让我感到厌倦,但对我来说却没有用。 我目前正在做研究,以寻找在js中转换图片的方法,并会在我找到新线索时更新帖子。 是否有已经在执行我要执行的功能? 如果我的伪代码中没有一个或多个组件? 任何建议深表感谢。

这是我尝试实现的当前函数,但是它返回一个没有绘制实际img的空白画布。

function imageResize(img, width, height) {

            /// create an off-screen canvas
            var canvas = document.createElement('canvas');
            var ctx = canvas.getContext('2d');

            /// set its dimension to target size
            canvas.width = width;
            canvas.height = height;

            /// draw source image into the off-screen canvas:
            ctx.drawImage(img, 0, 0, width, height);

            /// encode image to data-uri with base64 version of compressed image
            return canvas.toDataURL();
        }

我该如何解决这个问题?

这个实现对我来说很棒。

function imageToDataURL(image, width, height) {
        var canvas = document.createElement("canvas");
        canvas.width = width;
        canvas.height = height;
        canvas.getContext("2d").drawImage(image, 0, 0, width, height);
        return canvas.toDataURL();
}

将图像绘制到画布上时是否加载了图像?

加载图像后,必须调用drawImage方法,以便进入图像的onload事件的处理函数,如下所示:

// You create your img
var img = document.createElement('img');

// When the img is loaded you can treat it ;)
img.src = 'your_data_url/your_url';

function imageResize(img, width, height) {

        /// create an off-screen canvas
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');

        /// set its dimension to target size
        canvas.width = width;
        canvas.height = height;
        img.onload = function() { 
            /// draw source image into the off-screen canvas:
            ctx.drawImage(this, 0, 0, width, height); 
            var dataUrl = ctx.toDataURL();
            // Here you can use and treat your DataURI
        };
    }

JavaScript是一种异步语言,这意味着当加载图像或视频等对象时,它不会中断代码的执行。

在适当的位置,它将在对象的加载完成时触发一个名为“ load”的事件,并在将对象加载时调用事件处理程序(您先前定义的函数)。

PS请参阅我对这个问题的回答: https : //stackoverflow.com/a/26884245/4034886

如果您对该代码还有其他问题,请随时询问我;)

对不起,我糟糕的英语顺便说一句。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM