uri uri 转换_使用JavaScript将图像转换为数据URI

àì夳堔傛蜴生んèń 2023-02-22 03:39 81阅读 0赞

uri uri 转换

Whenever I go on a “performance run” on a website, the first place I look is imagery. Why? Because you can save an image out of Photoshop, push it into ImageOptim or even TinyPNG, and save 70% on its file size. What do most developers not consider? Taking tiny image files and making them data URIs instead of traditional images (another HTTP request). Unfortunately that needs to happen on the CSS file before page load, but you need to get that data URI from somewhere, right?

每当我在网站上进行“性能测试”时,我首先看到的就是图像。 为什么? 由于可以将图像保存到Photoshop中,因此请将其推入ImageOptim甚至TinyPNG中,并节省70%的文件大小。 大多数开发人员不考虑什么? 获取微小的图像文件,并使其成为数据URI,而不是传统图像(另一个HTTP请求)。 不幸的是,这需要在页面加载之前在CSS文件上进行,但是您需要从某个地方获取该数据URI,对吗?

I’m a bit suspicious of random websites which allow you upload files or content and return a given result; you don’t know the author of said code. So I’ve gone to my own code, modifying it a bit along the way, to create a utility for converting an image to data URI!

我对随机网站有些怀疑,该网站允许您上传文件或内容并返回给定的结果; 您不认识所述代码的作者。 因此,我进入了自己的代码 ,并对其进行了一些修改,以创建用于将图像转换为数据URI的实用程序!

将图像转换为数据URI (Convert Image to Data URI)

Like my original post, we need to rely on canvas to do the heavy lifting:

就像我的原始帖子一样,我们需要依靠画布来完成繁重的工作:

  1. function getDataUri(url, callback) {
  2. var image = new Image();
  3. image.onload = function () {
  4. var canvas = document.createElement('canvas');
  5. canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
  6. canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size
  7. canvas.getContext('2d').drawImage(this, 0, 0);
  8. // Get raw image data
  9. callback(canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, ''));
  10. // ... or get as Data URI
  11. callback(canvas.toDataURL('image/png'));
  12. };
  13. image.src = url;
  14. }
  15. // Usage
  16. getDataUri('/logo.png', function(dataUri) {
  17. // Do whatever you'd like with the Data URI!
  18. });

You could also set this up to use Promises instead of a callback.

您还可以将其设置为使用Promises而不是回调。

Once the image has loaded, we thrust it into canvas and then export its data to a data URI. In practical terms, this isn’t a useful task since the image has already loaded but if you’re looking to create a local utility to perform this task, here you go!

加载图像后,我们将其放入画布,然后将其数据导出到数据URI。 实际上,这不是有用的任务,因为映像已经加载,但是如果您要创建本地实用程序来执行此任务,就可以了!

翻译自: https://davidwalsh.name/convert-image-data-uri-javascript

uri uri 转换

发表评论

表情:
评论列表 (有 0 条评论,81人围观)

还没有评论,来说两句吧...

相关阅读

    相关 URI,URL,URN

    URI,统一资源标识符 URL,统一资源定位符,是URI的一种,现在用的URI几乎都是URL. URN,统一资源名称,是一种新型的URI实现方式,但是目前缺少支撑,它可