Help with Image-Transformation Worker

Hello there, I am new to Cloudflare and wanted to use it for a small project. Since someone non-tech related will upload images I thought I could use a worker which transforms the images into webp for example and also changes their dimensions based on requests.
From what I have right now. I made a R2 Bucket and a worker - both free tier.
This is my worker code:
export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    console.log("Request URL:", url);
    const key = url.pathname.slice(1);
    console.log('url search params = ',url.searchParams)
    const width = url.searchParams.get("width");

    let object = await env.my_bucket.get(key);
    if (!object) {
      return new Response("Not found in R2", { status: 404 });
    }

    let transformOptions = {};
    console.log('width: ',width);
    if (width) {
      transformOptions = {
        width: width ? parseInt(width) : undefined,
        "fit": "cover", 
        "format": "auto",
        gravity: "center"
      };
    }
    console.log('transformoptions: ',transformOptions)

    return new Response(object.body, {
      headers: { "Content-Type": "image/jpeg" },
      cf: {
        image: transformOptions,
      },
    });
  },
};


I have deployed this worker but when I am trying to fetch a image which I have stored in the R2 I only get the original image back - no different file extension or size. Clearly I am doing something wrong so I wanted to to ask if this worker code is wrong or if I am missing some bit of configuration. (Overall feel free to correct me if this is not the correct setup at all - since I saw there is also some Service called "Images".
Thanks for any help :)
Was this page helpful?