resize an image in a cloudflare worker in javascript

To resize an image in a Cloudflare worker, you can use the Sharp library. Sharp is a high-performance image processing library that works in both Node.js and browser environments.

Here's an example of how to resize an image using Sharp in a Cloudflare worker:

index.tsx
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  const url = new URL(request.url)
  const imageUrl = url.searchParams.get('url')

  const response = await fetch(imageUrl)
  const imageBuffer = await response.arrayBuffer()

  // Use Sharp to resize the image
  const resizedImageBuffer = await sharp(imageBuffer)
    .resize({ width: 500 })
    .toBuffer()

  return new Response(resizedImageBuffer, { headers: { 'Content-Type': 'image/jpeg' } })
}
532 chars
19 lines

In this example, we listen for incoming fetch events, where we expect the URL of the image to be resized to be passed as a query parameter (?url=<image_url>).

We then fetch the image using the fetch API, and convert the response to an ArrayBuffer. This is because Sharp requires the image data to be in the form of a Buffer.

We then use Sharp to resize the image, specifying the desired width of the resized image (500 in this case). We then convert the resulting Buffer back to an ArrayBuffer.

Finally, we return a new Response object with the resized image data and a Content-Type header of image/jpeg.

Note that this example assumes that the input image is in JPEG format. If you're working with a different image format, you may need to adjust the Content-Type header accordingly.

gistlibby LogSnag