SPB Git

Repository Public

images.ts 2.1 KB 46 lines typescript

1// Images insérées dans le texte : réduction côté navigateur (canvas) des photos trop grandes avant téléversement.23export interface ScaledImage {4  blob: Blob5  width: number6  height: number7  /** vrai si l'image a été réduite (sinon `blob` est le fichier d'origine) */8  scaled: boolean9}10/** Largeur maximale envoyée : le double du plus grand affichage proposé, pour rester nette sur un écran dense. */11export const MAX_INLINE_WIDTH = 16001213/**14 * Réduit une image à `maxWidth` pixels de large (jamais agrandie, orientation EXIF appliquée). Les GIF (animés) et les15 * images déjà assez petites sont rendus tels quels ; si le navigateur ne sait pas décoder le fichier, il est rendu intact.16 */17export async function downscale(file: Blob, maxWidth = MAX_INLINE_WIDTH): Promise<ScaledImage> {18  const same = (width = 0, height = 0): ScaledImage => ({ blob: file, width, height, scaled: false })19  if (typeof createImageBitmap !== "function" || /^image\/gif$/i.test(file.type)) return same()20  let bitmap: ImageBitmap21  try {22    bitmap = await createImageBitmap(file, { imageOrientation: "from-image" })23  } catch {24    return same()25  }26  try {27    if (bitmap.width <= maxWidth) return same(bitmap.width, bitmap.height)28    const width = maxWidth29    const height = Math.max(1, Math.round((bitmap.height * maxWidth) / bitmap.width))30    const canvas = document.createElement("canvas")31    canvas.width = width32    canvas.height = height33    const ctx = canvas.getContext("2d")34    if (!ctx) return same(bitmap.width, bitmap.height)35    ctx.imageSmoothingQuality = "high"36    ctx.drawImage(bitmap, 0, 0, width, height)37    // une photo reste en JPEG ; le reste (captures, transparence) en PNG38    const type = /^image\/jpeg$/i.test(file.type) ? "image/jpeg" : /^image\/webp$/i.test(file.type) ? "image/webp" : "image/png"39    const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, type, 0.86))40    if (!blob || blob.size >= file.size) return same(bitmap.width, bitmap.height)41    return { blob, width, height, scaled: true }42  } finally {43    bitmap.close()44  }45}46
Files main
Menu

Theme