我正在尝试创建一个函数,它接收具有宽度和高度的base64图像数据,并在javascript中返回具有给定宽度和高度的重新调整大小的base64图像数据。从本质上讲它是
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;
} 我试着跟随this post,但它对我来说并不起作用。我目前正在做研究,以找到在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();
}我该如何解决这个问题?
发布于 2014-08-16 07:22:41
这个实现对我来说很好。
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();
}发布于 2014-11-12 21:57:23
当您将图像绘制到画布上时是否加载了图像?
您必须在加载图像后调用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“的事件,并在加载对象时调用事件处理程序(您先前定义的函数)。
附注:请看我对这个问题的回答:https://stackoverflow.com/a/26884245/4034886
如果您对该代码还有其他问题,请不要犹豫,尽管问我;)
很抱歉,我的英文很烂。
https://stackoverflow.com/questions/25332804
复制相似问题