javascript - 如何将任何图像转换为 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
}
}
})
无法分配给对象“#”的只读属性“名称”
解决方案
您不能“仅仅”更改文件的名称和类型并完成它。
- 文件名和类型是只读的,你必须在旧文件的基础上创建一个新文件,然后你可以分配一个新的名称和类型。
const myRenamedFile = new File([myOriginalFile], 'my-new-name');
- 更改
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。
推荐阅读
- c# - C# Now() 用字符串表示为带有月日年时和子午线的字符串
- java - 使用带有片段适配器的 Glide 库
- python - 在python的except语句中传递给异常的参数引发TypeError
- c++ - 如果使用向量作为容器,如何弹出队列
- python - 如何使用变量中的值更新嵌套 Python 字典中的键?
- ios - iPhone 本身可以充当 NFC 标签吗?
- r - 使用 knitr::include_graphics 将图像插入 RMarkdown 时替换文本?
- php - 如何使用 MySql 查询返回数组值(来自 PHP)
- c# - 在异步循环中等待上一项
- intellij-idea - 如何关闭 SQL 文件中的数据库导航器建议