有什么方法可以使用 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
}
}
})
Cannot assign to read only property 'name' of object '#'
最佳答案
您不能“仅仅”更改文件的名称和类型就完事了。
- 文件名和类型是只读的,你必须create a new file基于旧的,然后您可以分配一个新的名称和类型。
const myRenamedFile = new File([myOriginalFile], 'my-new-name');
- 更改
type
属性不会更改实际的文件数据。将.png
重命名为.jpeg
,文件数据(位
)仍将是 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 .
关于javascript - 如何将任何图像转换为 webp?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62209609/