Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

composerImageFit.ts

61 lines2.1 KB

1import {
2 downscalableImageMimeType,
3 fitImageAttachmentSize,
4} from "@t3tools/client-runtime/image-attachment-size";
5import {
6 IMAGE_DIMENSIONS_HEADER_BYTES,
7 readImageDimensions,
8} from "@t3tools/shared/imageDimensions";
9​
10const PHOTO_JPEG_QUALITY = 0.85;
11​
12export async function renderPhoto(
13 uri: string,
14 format: "jpeg" | "png" = "jpeg",
15): Promise<{ base64: string; uri: string }> {
16 const { ImageManipulator, SaveFormat } = await import("expo-image-manipulator");
17 let image = await ImageManipulator.manipulate(uri).renderAsync();
18 try {
19 const fittedSize = fitImageAttachmentSize(image);
20 if (fittedSize !== null) {
21 const resized = await ImageManipulator.manipulate(image).resize(fittedSize).renderAsync();
22 image.release();
23 image = resized;
24 }
25 const saved = await image.saveAsync({
26 format: format === "png" ? SaveFormat.PNG : SaveFormat.JPEG,
27 compress: PHOTO_JPEG_QUALITY,
28 base64: true,
29 });
30 if (!saved.base64) {
31 throw new Error("The rendered photo has no bytes.");
32 }
33 return { base64: saved.base64, uri: saved.uri };
34 } finally {
35 image.release();
36 }
38​
39/**
40 * Returns null when the image fits, is another format (GIF, WebP), or the native renderer fails,
41 * so the caller keeps the original bytes.
42 */
43export async function fitComposerImage(image: {
44 readonly uri: string;
45 readonly mimeType: string;
46 readonly base64: string;
47}): Promise<{ base64: string; uri: string } | null> {
48 const mimeType = downscalableImageMimeType(image.mimeType);
49 if (mimeType === null) return null;
50 try {
51 const header = atob(image.base64.slice(0, Math.ceil(IMAGE_DIMENSIONS_HEADER_BYTES / 3) * 4));
52 const bytes = new Uint8Array(header.length);
53 for (let index = 0; index < header.length; index += 1) bytes[index] = header.charCodeAt(index);
54 const dimensions = readImageDimensions(bytes);
55 if (dimensions === null || fitImageAttachmentSize(dimensions) === null) return null;
56 return await renderPhoto(image.uri, mimeType === "image/png" ? "png" : "jpeg");
57 } catch (error) {
58 console.warn("[composer-images] could not scale an oversized image", error);
59 return null;
60 }