feat: webp convert @frontend (#11150)

* webp convert @frontend

* 0.85 → 0.90

---------

Co-authored-by: tamaina <tamaina@hotmail.co.jp>
This commit is contained in:
Narazaka 2023-07-07 13:44:31 +09:00 committed by GitHub
parent d5c4e77c44
commit bc4d27410c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 1 deletions

View File

@ -1,7 +1,15 @@
import isAnimated from 'is-file-animated'; import isAnimated from 'is-file-animated';
import { isWebpSupported } from './isWebpSupported';
import type { BrowserImageResizerConfig } from 'browser-image-resizer'; import type { BrowserImageResizerConfig } from 'browser-image-resizer';
const compressTypeMap = { const compressTypeMap = {
'image/jpeg': { quality: 0.90, mimeType: 'image/webp' },
'image/png': { quality: 1, mimeType: 'image/webp' },
'image/webp': { quality: 0.90, mimeType: 'image/webp' },
'image/svg+xml': { quality: 1, mimeType: 'image/webp' },
} as const;
const compressTypeMapFallback = {
'image/jpeg': { quality: 0.85, mimeType: 'image/jpeg' }, 'image/jpeg': { quality: 0.85, mimeType: 'image/jpeg' },
'image/png': { quality: 1, mimeType: 'image/png' }, 'image/png': { quality: 1, mimeType: 'image/png' },
'image/webp': { quality: 0.85, mimeType: 'image/jpeg' }, 'image/webp': { quality: 0.85, mimeType: 'image/jpeg' },
@ -9,7 +17,7 @@ const compressTypeMap = {
} as const; } as const;
export async function getCompressionConfig(file: File): Promise<BrowserImageResizerConfig | undefined> { export async function getCompressionConfig(file: File): Promise<BrowserImageResizerConfig | undefined> {
const imgConfig = compressTypeMap[file.type]; const imgConfig = (isWebpSupported() ? compressTypeMap : compressTypeMapFallback)[file.type];
if (!imgConfig || await isAnimated(file)) { if (!imgConfig || await isAnimated(file)) {
return; return;
} }

View File

@ -0,0 +1,10 @@
let isWebpSupportedCache: boolean | undefined;
export function isWebpSupported() {
if (isWebpSupportedCache === undefined) {
const canvas = document.createElement('canvas');
canvas.width = 1;
canvas.height = 1;
isWebpSupportedCache = canvas.toDataURL('image/webp').startsWith('data:image/webp');
}
return isWebpSupportedCache;
}