如何在现代浏览器中生成缩略图客户端? [英] How do I generate a thumbnail client-side in a modern browser?

查看:148
本文介绍了如何在现代浏览器中生成缩略图客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种优雅的方式来生成缩略图,供 FileAPI 使用。目前,我获得了代表图像的 DataURL 。问题是,如果图像非常大,那么移动它并重新渲染就会变成CPU密集型。我可以看到2个选项来解决这个问题。

I'm looking for an elegant way to generate a thumbnail for use with the FileAPI. Currently I get a DataURL representing an image. Problem is, if the image is very large, than moving it around and rerendering it becomes CPU intensive. I can see 2 options to get around this.


  • 在客户端生成缩略图

  • 生成服务器上的缩略图,将缩略图发送回客户端(AJAX)。使用 HTML5

code>我们有一个 canvas 元素?有谁知道如何使用它从图片生成缩略图?他们不必是完美的 - 抽样质量是可以接受的。是否有一个 jQuery 插件可以为我做到这一点?有没有其他方法可以加速客户端使用大图像?

With HTML5 we have a canvas element? Does anyone know how to use it to generate thumbnails from pictures? They don't have to be perfect -- sampling quality is acceptable. Is there a jQuery plugin that will do this for me? Are there any other way to speed up the clientside use of large images?

我使用 HTML5 ,并且 Firefox 3.6 + :除了 Firefox 3.6 + 以外不需要任何支持,请不要提供 IE 6.0

I'm using HTML5, and Firefox 3.6+: there is no need to support anything other than Firefox 3.6+, please don't provide suggestions for IE 6.0

推荐答案

以下是您可以执行的操作:

Here’s what you can do:

function getThumbnail(original, scale) {
  var canvas = document.createElement("canvas");

  canvas.width = original.width * scale;
  canvas.height = original.height * scale;

  canvas.getContext("2d").drawImage(original, 0, 0, canvas.width, canvas.height);

  return canvas
}

现在,要创建缩略图,你可以简单地做到这一点:

Now, to create thumbnails, you simply do the equivalent of this:

var image = document.getElementsByTagName("img")[0];
var thumbnail = getThubmnail(image, 1/5);

document.body.appendChild(thumbnail);

注意:请记住确保图像已加载(使用 onload ),然后尝试制作缩略图。

Note: Remember to make sure that the image is loaded (using onload) before trying to make a thumbnail of it.

这篇关于如何在现代浏览器中生成缩略图客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆