From bc4d27410c4db84468fa6d0799aa7113fc7586f0 Mon Sep 17 00:00:00 2001 From: Narazaka Date: Fri, 7 Jul 2023 13:44:31 +0900 Subject: [PATCH] feat: webp convert @frontend (#11150) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * webp convert @frontend * 0.85 → 0.90 --------- Co-authored-by: tamaina --- .../frontend/src/scripts/upload/compress-config.ts | 10 +++++++++- .../frontend/src/scripts/upload/isWebpSupported.ts | 10 ++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 packages/frontend/src/scripts/upload/isWebpSupported.ts diff --git a/packages/frontend/src/scripts/upload/compress-config.ts b/packages/frontend/src/scripts/upload/compress-config.ts index 793c78ad20..55d469c5e4 100644 --- a/packages/frontend/src/scripts/upload/compress-config.ts +++ b/packages/frontend/src/scripts/upload/compress-config.ts @@ -1,7 +1,15 @@ import isAnimated from 'is-file-animated'; +import { isWebpSupported } from './isWebpSupported'; import type { BrowserImageResizerConfig } from 'browser-image-resizer'; 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/png': { quality: 1, mimeType: 'image/png' }, 'image/webp': { quality: 0.85, mimeType: 'image/jpeg' }, @@ -9,7 +17,7 @@ const compressTypeMap = { } as const; export async function getCompressionConfig(file: File): Promise { - const imgConfig = compressTypeMap[file.type]; + const imgConfig = (isWebpSupported() ? compressTypeMap : compressTypeMapFallback)[file.type]; if (!imgConfig || await isAnimated(file)) { return; } diff --git a/packages/frontend/src/scripts/upload/isWebpSupported.ts b/packages/frontend/src/scripts/upload/isWebpSupported.ts new file mode 100644 index 0000000000..cde8b9d785 --- /dev/null +++ b/packages/frontend/src/scripts/upload/isWebpSupported.ts @@ -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; +}