更新时间:2022-02-08 09:06:03
下面是应该做你所需要的功能。你给它一个图像的URL(例如,从 chrome.tabs.captureVisibleTab
的结果,但它可以是任何URL),所需的大小,和一个回调。它以异步方式执行,因为没有保证,当你设置的src
属性中的图像将被立即加载。随着数据的URL,它可能会,因为它不需要下载任何东西,但我还没有尝试过。
Here's a function that should do what you need. You give it the URL of an image (e.g. the result from chrome.tabs.captureVisibleTab
, but it could be any URL), the desired size, and a callback. It executes asynchronously because there is no guarantee that the image will be loaded immediately when you set the src
property. With a data URL it probably will since it doesn't need to download anything, but I haven't tried it.
回调将被传递所产生的图像作为数据URL。请注意,由此产生的图像将是一个PNG,因为Chrome的实施 toDataURL
不支持图像/ JPEG。
The callback will be passed the resulting image as a data URL. Note that the resulting image will be a PNG, since Chrome's implementation of toDataURL
doesn't support image/jpeg.
function resizeImage(url, width, height, callback) {
var sourceImage = new Image();
sourceImage.onload = function() {
// Create a canvas with the desired dimensions
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
// Scale and draw the source image to the canvas
canvas.getContext("2d").drawImage(sourceImage, 0, 0, width, height);
// Convert the canvas to a data URL in PNG format
callback(canvas.toDataURL());
}
sourceImage.src = url;
}