首页 > 解决方案 > 如何将任何图像转换为 webp?

问题描述

有什么方法可以使用 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
    }
  }
})

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

标签: javascriptfilepond

解决方案


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

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

更多关于重命名文件

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

要转换数据,您需要读取原始文件,然后将其转换为WEBP格式。.toBlob()您可以使用 canvas 元素上可用的方法来做到这一点。

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 图像不适用于不支持 WEBP的浏览器,例如 Safari 13.x、IE11 和 Edge 17。自 2019 年初开始支持 Firefox,Chrome 支持 WEBP 已有很长时间了。

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


推荐阅读