【问题标题】:How to convert any image to webp?如何将任何图像转换为 webp?
【发布时间】:2020-09-24 07:43:34
【问题描述】:

有什么方法可以使用 filepond 将任何图像转换为 webp?

这是我的代码:

import vueFilePond, { setOptions } from 'vue-filepond'

// ...

setOptions({
  server: {
    process: (field, file) => {
      file.name = String(file.name.substr(0, file.name.lastIndexOf('.'))) + '.webp';
      file.type = 'image/webp';
      // ... upload to firebase storage
    }
  }
})

无法分配给对象“#”的只读属性“名称”

【问题讨论】:

标签: javascript filepond


【解决方案1】:

您不能“仅仅”更改文件的名称和类型并完成它。

  1. 文件名和类型是只读的,你必须在旧的基础上create a new file然后你可以分配一个新的名称和类型。
const myRenamedFile = new File([myOriginalFile], 'my-new-name');

More on renaming files

  1. 更改type 属性不会更改实际文件数据。将 .png 重命名为 .jpeg,文件数据(bits)仍将是 JPEG 压缩图像。

要转换数据,您需要读取原始文件,然后将其转换为WEBP 格式。您可以使用.toBlob() method available on the canvas element 进行操作。

const image = new Image();
image.onload = () => {

  const canvas = document.createElement('canvas');
  canvas.width = image.naturalWidth;
  canvas.height = image.naturalHeight;
  canvas.getContext('2d').drawImage(image, 0, 0);
  canvas.toBlob((blob) => {
    
    // Now we have a `blob` containing webp data

    // Use the file rename trick to turn it back into a file
    const myImage = new File([blob], 'my-new-name.webp', { type: blob.type });

  }, 'image/webp');

};

image.src = URL.createObjectURL(myFile);

显然,创建 WEBP 图像不适用于不支持 support WEBP 的浏览器,例如 Safari 13.x、IE11 和 Edge 17。自 2019 年初开始支持 Firefox,Chrome 支持 WEBP 已有很长时间了.

如果您需要支持这些浏览器,您可以使用单独的 JavaScript 库来进行图像编码。例如webpjs。

【讨论】:

  • 目前这在 Firefox 84 中不起作用。即使假设支持 webp,带有 image/webp 的 toBlob 也会退回到 png 编码的 blob。
猜你喜欢
  • 1970-01-01
  • 2018-05-10
  • 2022-07-07
  • 2012-10-24
  • 2017-09-10
  • 2019-01-31
  • 1970-01-01
  • 2019-11-18
  • 2017-04-24
相关资源
最近更新 更多