如何在 JavaScript 中缩放图像(数据 URI 格式)(真实缩放,不使用样式)
我们正在 Chrome 浏览器中捕获可见选项卡(通过使用扩展 API chrome.tabs.captureVisibleTab)并接收数据 URI 方案(Base64 编码字符串)中的快照。
是否有一个 JavaScript 库可用于将图像缩小到特定尺寸?
目前我们通过 CSS 对其进行样式设计,但由于图片大多比所需的大 100 倍,因此必须付出性能损失。另外一个问题是我们用来保存快照的 localStorage 上的负载。
有谁知道一种方法来处理这种数据 URI 方案格式的图片并通过缩小它们来减小它们的大小?
参考资料:
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).
Is there a JavaScript library that can be used to scale down an image to a certain size?
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.
Does anyone know of a way to process this data URI scheme formatted pictures and reduce their size by scaling them down?
References:
- 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个应该可以满足您需要的函数。您为其提供图像的 URL(例如,
chrome.tabs.captureVisibleTab
的结果,但它可以是任何 URL)、所需的大小和回调。它以异步方式执行,因为不能保证在设置src
属性时立即加载图像。使用数据 URL 可能会,因为它不需要下载任何东西,但我还没有尝试过。回调将把生成的图像作为数据 URL 传递。请注意,生成的图像将是 PNG,因为 Chrome 的
toDataURL
实现不支持 image/jpeg。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 thesrc
property. With a data URL it probably will since it doesn't need to download anything, but I haven't tried it.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.至于性能问题,也许画布标签可以帮助? https://developer.mozilla.org/en/Canvas_tutorial/Using_images#drawImage_example_2
如果你加载图像,用drawImage显示它,然后尝试丢弃它,你可能会成功。但我不确定如何将画布序列化为图像以保存调整大小的文件......
As for the performance issues, maybe the canvas tag could help? https://developer.mozilla.org/en/Canvas_tutorial/Using_images#drawImage_example_2
If you load the image, display it with drawImage and then try to discard it, you may succeed. But I am not sure how to serialize a canvas as an image to save the resized file...