Convert image uploads into webp files unless it's a gif (closes #11)
This commit is contained in:
parent
4a2c40397f
commit
73601c579c
4 changed files with 54 additions and 8 deletions
|
|
@ -1,3 +1,4 @@
|
|||
import { config } from "../config.mjs";
|
||||
import { __ID__, devMode, filePath } from "../consts.mjs";
|
||||
|
||||
const { fetchJsonWithTimeout } = foundry.utils;
|
||||
|
|
@ -28,6 +29,41 @@ export async function hashFile(file) {
|
|||
.join(``);
|
||||
};
|
||||
|
||||
/**
|
||||
* Converts an image file into a webp file unless it is already a webp file or
|
||||
* cannot be converted to a webp, in which case it doesn't modify the file at all.
|
||||
*
|
||||
* @param {File} file The file to convert
|
||||
* @returns {Promise<File>}
|
||||
*/
|
||||
export async function convertToWebp(file) {
|
||||
if (file.type === `image/webp`) { return null };
|
||||
if (config.WEBP_IGNORE.includes(file.type)) { return null };
|
||||
|
||||
/** @type {HTMLImageElement} */
|
||||
const image = document.createElement(`img`);
|
||||
const url = URL.createObjectURL(file);
|
||||
image.src = url;
|
||||
await image.decode();
|
||||
|
||||
/** @type {HTMLCanvasElement} */
|
||||
const canvas = document.createElement(`canvas`);
|
||||
canvas.width = image.naturalWidth;
|
||||
canvas.height = image.naturalHeight;
|
||||
canvas.getContext(`2d`).drawImage(image, 0, 0);
|
||||
|
||||
return new Promise((resolve) => {
|
||||
canvas.toBlob(
|
||||
(blob) => {
|
||||
const name = file.name.split(`.`).slice(0, -1).join(`.`);
|
||||
const webp = new File([blob], `${name}.webp`, { type: blob.type });
|
||||
resolve(webp);
|
||||
},
|
||||
`image/webp`,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
export async function lastModifiedAt(path) {
|
||||
try {
|
||||
const response = await fetch(filePath(path), { method: `HEAD` });
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue