aboutsummaryrefslogtreecommitdiff
path: root/build/js/io/export.js
blob: 4a536437fb8d2c1e77544d322adca9999b9b7e24 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Image export to PNG, JPEG, WebP, AVIF (when the browser can encode it), GIF, BMP, TIFF and ICO.
import { canvasToBlob, createCanvas } from '../core/util.js';
import { flattenToCanvas } from '../render/compositor.js';
import { resampleCanvas } from '../core/ops.js';
import { encodeBMP } from './encoders/bmp.js';
import { encodeGIF } from './encoders/gif.js';
import { encodeTIFF } from './encoders/tiff.js';
import { encodeICO } from './encoders/ico.js';

export const FORMATS = [
  { id: 'png', label: 'PNG', ext: 'png', mime: 'image/png', alpha: true, lossless: true },
  { id: 'jpeg', label: 'JPEG', ext: 'jpg', mime: 'image/jpeg', alpha: false, quality: true },
  { id: 'webp', label: 'WebP', ext: 'webp', mime: 'image/webp', alpha: true, quality: true, native: true },
  { id: 'avif', label: 'AVIF', ext: 'avif', mime: 'image/avif', alpha: true, quality: true, native: true },
  { id: 'gif', label: 'GIF', ext: 'gif', mime: 'image/gif', alpha: true, palette: true },
  { id: 'bmp', label: 'BMP', ext: 'bmp', mime: 'image/bmp', alpha: true },
  { id: 'tiff', label: 'TIFF', ext: 'tiff', mime: 'image/tiff', alpha: true, lossless: true },
  { id: 'ico', label: 'ICO (favicon)', ext: 'ico', mime: 'image/x-icon', alpha: true, icon: true },
];

const supportCache = new Map();
/** Whether the browser's canvas encoder really produces this mime type. */
export function canEncodeNatively(mime) {
  if (supportCache.has(mime)) return supportCache.get(mime);
  const c = createCanvas(2, 2);
  const ok = c.toDataURL(mime).startsWith(`data:${mime}`);
  supportCache.set(mime, ok);
  return ok;
}

export function availableFormats() {
  return FORMATS.filter((f) => !f.native || canEncodeNatively(f.mime));
}

/**
 * Render the document for export.
 * opts: { format, quality (0..1), scale, background (css or null), dither, colors, icoSizes, bmpAlpha }
 */
export async function exportImage(doc, opts) {
  const fmt = FORMATS.find((f) => f.id === opts.format) || FORMATS[0];
  const needsBg = !fmt.alpha || (opts.background && opts.flattenBackground);
  let canvas = flattenToCanvas(doc, needsBg ? opts.background || '#ffffff' : null);
  const scale = opts.scale || 1;
  if (scale !== 1) canvas = resampleCanvas(canvas, Math.max(1, Math.round(doc.width * scale)), Math.max(1, Math.round(doc.height * scale)));
  const id = () => canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);

  switch (fmt.id) {
    case 'png': return canvasToBlob(canvas, 'image/png');
    case 'jpeg':
    case 'webp':
    case 'avif': return canvasToBlob(canvas, fmt.mime, opts.quality ?? 0.92);
    case 'gif': return encodeGIF(id(), { dither: opts.dither ?? true, colors: opts.colors || 256 });
    case 'bmp': return encodeBMP(id(), { alpha: opts.bmpAlpha ?? true });
    case 'tiff': return encodeTIFF(id(), { compress: opts.compress ?? true });
    case 'ico': {
      const sizes = (opts.icoSizes && opts.icoSizes.length ? opts.icoSizes : [16, 32, 48, 256]).slice().sort((a, b) => a - b);
      const images = [];
      for (const s of sizes) {
        // fit inside a square, centered
        const sq = createCanvas(s, s);
        const k = Math.min(s / canvas.width, s / canvas.height);
        const w = Math.max(1, Math.round(canvas.width * k)), h = Math.max(1, Math.round(canvas.height * k));
        sq.getContext('2d').drawImage(resampleCanvas(canvas, w, h), Math.floor((s - w) / 2), Math.floor((s - h) / 2));
        const blob = await canvasToBlob(sq, 'image/png');
        images.push({ width: s, height: s, png: new Uint8Array(await blob.arrayBuffer()) });
      }
      return encodeICO(images);
    }
    default: throw new Error(`Unknown format ${fmt.id}`);
  }
}