Create professional demos and 3D mockups in seconds, directly in your browser
feat: implement image export API with support for multiple formats using sharp
CristianOlivera14af16a059ebb
diff --git a/app/api/export-image/route.ts b/app/api/export-image/route.tsnew file mode 100644index 0000000..e87801e--- /dev/null+++ b/app/api/export-image/route.ts@@ -0,0 +1,76 @@+import { NextRequest, NextResponse } from "next/server";+import sharp from "sharp";++export const runtime = "nodejs";+export const dynamic = "force-dynamic";++const FORMATS = {+ avif: { mime: "image/avif", ext: "avif" },+ webp: { mime: "image/webp", ext: "webp" },+ jpeg: { mime: "image/jpeg", ext: "jpg" },+ png: { mime: "image/png", ext: "png" },+} as const;++type ServerFormat = keyof typeof FORMATS;++const MAX_INPUT_BYTES = 32 * 1024 * 1024;++export async function POST(request: NextRequest) {+ let format: string | null = null;+ try {+ const formData = await request.formData();+ const file = formData.get("image");+ format = formData.get("format") as string | null;+ const qualityRaw = formData.get("quality");++ if (!(file instanceof Blob)) {+ return NextResponse.json({ error: "Missing image file" }, { status: 400 });+ }+ if (file.size > MAX_INPUT_BYTES) {+ return NextResponse.json({ error: "Image too large" }, { status: 413 });+ }+ if (!format || !(format in FORMATS)) {+ return NextResponse.json(+ { error: `Unsupported format: ${format ?? "(none)"}` },+ { status: 400 }+ );+ }+ const quality = Math.min(100, Math.max(1, Number(qualityRaw) || 80));++ const inputBuffer = Buffer.from(await file.arrayBuffer());+ const pipeline = sharp(inputBuffer, { failOn: "none" });+ const meta = await pipeline.metadata();+ if (!meta.width || !meta.height) {+ return NextResponse.json({ error: "Unreadable image" }, { status: 400 });+ }++ const target = FORMATS[format as ServerFormat];+ let output: Buffer;+ switch (format as ServerFormat) {+ case "avif":+ output = await pipeline.avif({ quality }).toBuffer();+ break;+ case "webp":+ output = await pipeline.webp({ quality }).toBuffer();+ break;+ case "jpeg":+ output = await pipeline.jpeg({ quality }).toBuffer();+ break;+ case "png":+ output = await pipeline.png().toBuffer();+ break;+ }++ return new NextResponse(new Uint8Array(output), {+ status: 200,+ headers: {+ "Content-Type": target.mime,+ "Content-Disposition": `attachment; filename="openvid-export.${target.ext}"`,+ "Cache-Control": "no-store",+ },+ });+ } catch (error) {+ console.error(`Image export encoding failed (${format}):`, error);+ return NextResponse.json({ error: "Encoding failed" }, { status: 500 });+ }+}diff --git a/lib/image-codecs/exportEncoders.ts b/lib/image-codecs/exportEncoders.tsindex 1853049..2ad3bda 100644--- a/lib/image-codecs/exportEncoders.ts+++ b/lib/image-codecs/exportEncoders.ts@@ -1,57 +1,89 @@type EncodableImage = ImageData;-let jpegEncodeReady: Promise<typeof import("@jsquash/jpeg")["encode"]> | null = null;-function getJpegEncode() {- if (!jpegEncodeReady) {- jpegEncodeReady = import("@jsquash/jpeg").then((m) => m.encode);- }- return jpegEncodeReady;+function toCanvasBlob(canvas: HTMLCanvasElement, type: string, quality?: number): Promise<Blob> {+ return new Promise((resolve, reject) => {+ canvas.toBlob(+ (blob) => (blob ? resolve(blob) : reject(new Error(`Failed to encode ${type}`))),+ type,+ quality+ );+ });}-export async function encodeJpeg(image: EncodableImage, quality: number): Promise<Blob> {- const encode = await getJpegEncode();- const buffer = await encode(image, { quality: Math.round(quality * 100) });- return new Blob([buffer], { type: "image/jpeg" });+function imageDataToCanvas(image: EncodableImage): HTMLCanvasElement {+ const canvas = document.createElement("canvas");+ canvas.width = image.width;+ canvas.height = image.height;+ const ctx = canvas.getContext("2d");+ if (!ctx) throw new Error("No 2D context available");+ ctx.putImageData(image, 0, 0);+ return canvas;+}++function hasWebpSignature(blob: Blob): Promise<boolean> {+ return blob.slice(0, 12).arrayBuffer().then((buffer) => {+ const bytes = new Uint8Array(buffer);+ return bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 &&+ bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50;+ });+}++let avifSupport: Promise<boolean> | null = null;++function detectAvifSupport(): Promise<boolean> {+ if (!avifSupport) {+ avifSupport = (async () => {+ try {+ const probe = document.createElement("canvas");+ probe.width = 1;+ probe.height = 1;+ const ctx = probe.getContext("2d");+ if (!ctx) return false;+ ctx.fillRect(0, 0, 1, 1);+ const blob = await new Promise<Blob | null>((resolve) => probe.toBlob(resolve, "image/avif"));+ return !!blob && blob.type === "image/avif";+ } catch {+ return false;+ }+ })();+ }+ return avifSupport;}-let pngEncodeReady: Promise<typeof import("@jsquash/png")["encode"]> | null = null;-function getPngEncode() {- if (!pngEncodeReady) {- pngEncodeReady = import("@jsquash/png").then((m) => m.encode);+async function encodeViaServer(canvas: HTMLCanvasElement, format: "webp" | "avif", quality: number): Promise<Blob> {+ const intermediate = await toCanvasBlob(canvas, "image/png");+ const formData = new FormData();+ formData.append("image", intermediate, "export.png");+ formData.append("format", format);+ formData.append("quality", String(Math.round(quality * 100)));++ const response = await fetch("/api/export-image", { method: "POST", body: formData });+ if (!response.ok) {+ throw new Error(`Server encoding failed (${response.status})`);}- return pngEncodeReady;+ const mime = format === "avif" ? "image/avif" : "image/webp";+ return new Blob([await response.blob()], { type: mime });}export async function encodePng(image: EncodableImage): Promise<Blob> {- const encode = await getPngEncode();- const buffer = await encode(image);- return new Blob([buffer], { type: "image/png" });+ return toCanvasBlob(imageDataToCanvas(image), "image/png");}-let webpEncodeReady: Promise<typeof import("@jsquash/webp")["encode"]> | null = null;-function getWebpEncode() {- if (!webpEncodeReady) {- webpEncodeReady = import("@jsquash/webp").then((m) => m.encode);- }- return webpEncodeReady;+export async function encodeJpeg(image: EncodableImage, quality: number): Promise<Blob> {+ return toCanvasBlob(imageDataToCanvas(image), "image/jpeg", quality);}export async function encodeWebp(image: EncodableImage, quality: number): Promise<Blob> {- const encode = await getWebpEncode();- const buffer = await encode(image, { quality: Math.round(quality * 100) });- return new Blob([buffer], { type: "image/webp" });+ const canvas = imageDataToCanvas(image);+ const blob = await toCanvasBlob(canvas, "image/webp", quality);+ if (await hasWebpSignature(blob)) return blob;++ return encodeViaServer(canvas, "webp", quality);}-let avifEncodeReady: Promise<typeof import("@jsquash/avif")["encode"]> | null = null;-function getAvifEncode() {- if (!avifEncodeReady) {- avifEncodeReady = import("@jsquash/avif").then((m) => m.encode);+export async function encodeAvif(image: EncodableImage, quality: number): Promise<Blob> {+ if (await detectAvifSupport()) {+ return toCanvasBlob(imageDataToCanvas(image), "image/avif", quality);}- return avifEncodeReady;+ return encodeViaServer(imageDataToCanvas(image), "avif", quality);}--export async function encodeAvif(image: EncodableImage, quality: number): Promise<Blob> {- const encode = await getAvifEncode();- const buffer = await encode(image, { quality: Math.round(quality * 100) });- return new Blob([buffer], { type: "image/avif" });-}\ No newline at end of filediff --git a/package.json b/package.jsonindex 54fda54..af4e365 100644--- a/package.json+++ b/package.json@@ -13,10 +13,6 @@"@ffmpeg/core": "^0.12.10","@ffmpeg/ffmpeg": "^0.12.15","@ffmpeg/util": "^0.12.2",- "@jsquash/avif": "^2.1.1",- "@jsquash/jpeg": "^1.6.0",- "@jsquash/png": "^3.1.1",- "@jsquash/webp": "^1.5.0","@next/third-parties": "^16.3.0","@radix-ui/react-dialog": "^1.1.15","@radix-ui/react-dropdown-menu": "^2.1.16",@@ -41,6 +37,7 @@"react": "19.2.3","react-dom": "19.2.3","resend": "^6.18.0",+ "sharp": "^0.35.3","swapy": "^1.0.5","tailwind-merge": "^3.4.0","three": "^0.184.0",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 51a70f3..f0087ed 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -17,18 +17,6 @@ importers:'@ffmpeg/util':specifier: ^0.12.2version: 0.12.2- '@jsquash/avif':- specifier: ^2.1.1- version: 2.1.1- '@jsquash/jpeg':- specifier: ^1.6.0- version: 1.6.0- '@jsquash/png':- specifier: ^3.1.1- version: 3.1.1- '@jsquash/webp':- specifier: ^1.5.0- version: 1.5.0'@next/third-parties':specifier: ^16.3.0version: 16.3.2([email protected](@babel/[email protected])([email protected]([email protected]))([email protected]))([email protected])@@ -101,6 +89,9 @@ importers:resend:specifier: ^6.18.0version: 6.22.0(@react-email/[email protected]([email protected]([email protected]))([email protected]))+ sharp:+ specifier: ^0.35.3+ version: 0.35.3(@types/[email protected])swapy:specifier: ^1.0.5version: 1.0.5@@ -1117,18 +1108,6 @@ packages:'@jridgewell/[email protected]':resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}- '@jsquash/[email protected]':- resolution: {integrity: sha512-LMRxd0fMgfCLtobDh0/sFYJMMiRJTNYSEEWvRDKXlAeZ08t3gI5V+1thIT0XjXJ+SVG7Zug9B0XPyx0Ti5VRNA==}-- '@jsquash/[email protected]':- resolution: {integrity: sha512-zwN46Awh1VM6gXlIcALwb5WzqK5H2e6+Awcs1QP8AvS8ohsK/sbE4esvmH4jhlhW7+CgiUUww66vg0aTnlSIMA==}-- '@jsquash/[email protected]':- resolution: {integrity: sha512-C10pc+0H6j0h8fENOfnGOvkXCmvpSQTDGlfGd0sHphZhPSGTyLjIrHba0FaZZdsKqA/wlmhYicUHb92vfZphaw==}-- '@jsquash/[email protected]':- resolution: {integrity: sha512-KggLoj2MnRSfIqTeKe1EmbljTX2vuV7mh79k89PCL1pyqiDULcPM1L47twxXt0hkb68F70bXiL31MxsuoZtKFw==}-'@mediapipe/[email protected]':resolution: {integrity: sha512-CZWV/q6TTe8ta61cZXjfnnHsfWIdFhms03M9T7Cnd5y2mdpylJM0rF1qRq+wsQVRMLz1OYPVEBU9ph2Bx8cxrg==}@@ -5355,9 +5334,6 @@ packages:resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==}engines: {node: '>= 0.8'}- resolution: {integrity: sha512-zonE+xlIIYtxPy++L24ow0hAD8CICb4+FgPyROd3buyXIqsJvUEDkBgfCCoXOd1Hu3DUr0GOfnPIdcGV+YpNaA==}-resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==}engines: {node: '>= 8'}@@ -6037,8 +6013,7 @@ snapshots:'@iconify/[email protected]': {}- '@img/[email protected]':- optional: true+ '@img/[email protected]': {}'@img/[email protected]':optionalDependencies:@@ -6284,18 +6259,6 @@ snapshots:'@jridgewell/resolve-uri': 3.1.2'@jridgewell/sourcemap-codec': 1.5.5- '@jsquash/[email protected]':- dependencies:- wasm-feature-detect: 1.9.0-- '@jsquash/[email protected]': {}-- '@jsquash/[email protected]': {}-- '@jsquash/[email protected]':- dependencies:- wasm-feature-detect: 1.9.0-'@mediapipe/[email protected]': {}'@modelcontextprotocol/[email protected]([email protected])':@@ -10393,7 +10356,6 @@ snapshots:'@img/sharp-win32-ia32': 0.35.3'@img/sharp-win32-x64': 0.35.3'@types/node': 20.19.43- optional: truedependencies:@@ -10864,8 +10826,6 @@ snapshots:- [email protected]: {}-