1- // file: netlify/edge-functions/crop-image.ts
21import { multiParser } from "https://deno.land/x/multiparser@0.114.0/mod.ts" ;
32import {
43 ImageMagick ,
54 initialize ,
65 MagickImage ,
76 MagickGeometry ,
8- } from "https://deno.land/x/imagemagick_deno/mod.ts" ;
7+ MagickFormat ,
8+ } from "https://deno.land/x/imagemagick_deno@0.0.26/mod.ts" ;
99
1010await initialize ( ) ;
1111
1212export default async ( request : Request ) => {
1313 if ( request . method === "POST" ) {
1414 try {
1515 const form = await multiParser ( request ) ;
16+
1617 const fileData = form . files . file . content ;
1718 const x = parseInt ( form . fields . x ) || 0 ;
1819 const y = parseInt ( form . fields . y ) || 0 ;
@@ -32,17 +33,32 @@ export default async (request: Request) => {
3233 headers : { "Content-Type" : "application/json" } ,
3334 } ) ;
3435 }
35- console . log ( "about to crop" ) ;
36+
3637 const cropped = await ImageMagick . read (
3738 fileData ,
3839 async ( image : MagickImage ) => {
39- const geometry = new MagickGeometry ( width , height , x , y ) ;
40+ // Ensure the cropping area does not exceed the original image dimensions
41+ const cropWidth = Math . min ( width , image . width - x ) ;
42+ const cropHeight = Math . min ( height , image . height - y ) ;
43+
44+ if ( cropWidth <= 0 || cropHeight <= 0 ) {
45+ throw new Error ( "Invalid cropping dimensions" ) ;
46+ }
47+
48+ const geometry = new MagickGeometry ( x , y , cropWidth , cropHeight ) ;
49+
4050 image . crop ( geometry ) ;
41- return await image . write ( ( data : Uint8Array ) => data ) ;
51+
52+ const data = await image . write (
53+ MagickFormat . Png ,
54+ ( data : Uint8Array ) => data
55+ ) ;
56+
57+ return data ;
4258 }
4359 ) ;
44- console . log ( cropped ) ;
45- if ( ! cropped ) {
60+
61+ if ( ! cropped || cropped . length === 0 ) {
4662 return new Response ( JSON . stringify ( { error : "Failed cropping" } ) , {
4763 status : 400 ,
4864 headers : { "Content-Type" : "application/json" } ,
@@ -52,7 +68,8 @@ export default async (request: Request) => {
5268 return new Response ( cropped , {
5369 status : 200 ,
5470 headers : {
55- "Content-Type" : "image/jpeg" ,
71+ "Content-Type" : "image/png" ,
72+ "Content-Length" : cropped . length . toString ( ) ,
5673 } ,
5774 } ) ;
5875 } catch ( error ) {
@@ -64,6 +81,7 @@ export default async (request: Request) => {
6481 } ) ;
6582 }
6683 }
84+
6785 return new Response ( "Method Not Allowed" , { status : 405 } ) ;
6886} ;
6987
0 commit comments