MCPcopy Create free account
hub / github.com/dailydotdev/apps / downscaleImage

Function downscaleImage

packages/shared/src/lib/downscaleImage.ts:30–70  ·  view source on GitHub ↗
(file: File)

Source from the content-addressed store, hash-verified

28// Returns a smaller copy of an image file, or the file itself when it is
29// already small, of a type this does not re-encode, or cannot be decoded here.
30export const downscaleImage = async (file: File): Promise<File> => {
31 const type = outputTypes[file.type];
32 if (
33 !type ||
34 file.size <= DOWNSCALE_MIN_BYTES ||
35 typeof createImageBitmap !== 'function'
36 ) {
37 return file;
38 }
39
40 try {
41 const bitmap = await createImageBitmap(file, {
42 imageOrientation: 'from-image',
43 });
44 const scale = Math.min(
45 1,
46 DOWNSCALE_MAX_DIMENSION / Math.max(bitmap.width, bitmap.height),
47 );
48 const canvas = document.createElement('canvas');
49 canvas.width = Math.round(bitmap.width * scale);
50 canvas.height = Math.round(bitmap.height * scale);
51 canvas
52 .getContext('2d')
53 ?.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
54 bitmap.close();
55
56 const blob = await toBlob(canvas, type);
57 // A browser that cannot encode the type falls back to PNG.
58 if (!blob || blob.type !== type || blob.size >= file.size) {
59 return file;
60 }
61
62 const name = file.name.replace(/\.[^.]+$/, '') || 'cover';
63 return new File([blob], `${name}.${extensions[type]}`, {
64 type,
65 lastModified: file.lastModified,
66 });
67 } catch {
68 return file;
69 }
70};

Callers 2

prepareCoverFunction · 0.90

Calls 2

toBlobFunction · 0.85
replaceMethod · 0.80

Tested by

no test coverage detected