如何在 JavaScript 中缩放图像(数据 URI 格式)(实际缩放,不使用样式)

我们正在 Chrome 浏览器中捕获可见选项卡(通过使用扩展 API chrome.tabs.captureVisibleTab)并接收数据 URI 方案(Base64 编码字符串)中的快照.

We are capturing a visible tab in a Chrome browser (by using the extensions API chrome.tabs.captureVisibleTab) and receiving a snapshot in the data URI scheme (Base64 encoded string).

是否有 JavaScript 库可用于将图像缩小到特定大小?

Is there a JavaScript library that can be used to scale down an image to a certain size?

目前我们正在通过 CSS 对其进行样式设置,但必须支付性能损失,因为图片通常比所需的大 100 倍.另一个问题是我们用来保存快照的 localStorage 的负载.

Currently we are styling it via CSS, but have to pay performance penalties as pictures are mostly 100 times bigger than required. Additional concern is also the load on the localStorage we use to save our snapshots.

有谁知道一种方法来处理这种数据 URI 方案格式的图片并通过缩小它们来减小它们的大小?

Does anyone know of a way to process this data URI scheme formatted pictures and reduce their size by scaling them down?

参考资料:

  • http://en.wikipedia.org/wiki/Data_URI_scheme上的数据 URI 方案
  • http://code.google.com/chrome/extensions/上的 Chrome 扩展 APItabs.html
  • http://code.google.com 上的最近关闭的标签"Chrome 扩展程序/p/recently-closed-tabs
  • Data URI scheme on http://en.wikipedia.org/wiki/Data_URI_scheme
  • Chrome Extensions API on http://code.google.com/chrome/extensions/tabs.html
  • The "Recently Closed Tabs" Chrome Extension on http://code.google.com/p/recently-closed-tabs

推荐答案

这里有一个函数可以满足你的需要.你给它一个图像的 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 实现不支持 image/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;
}

相关文章