Reading an image file's dimensions from a worker

I love the image resizing’s ability to draw overlays and watermarks. However, I have a need to first make some resizing and placement choices based on original image’s dimensions and aspect ratio. Is there any way to get the origin image’s file dimensions before I perform the fetch() that does the resizing/overlaying?

Every search I’ve tried just results in discussions about general image resizing.

Thanks!

I did see the fetch option “format:json” that’s supposed to return a JSON object with image sizing information, documented at https://developers.cloudflare.com/images/image-resizing/resize-with-workers/#format

Here’s my code:

const options_json = { cf: { image: {} } };
options_json.cf.image.format = 'json';
let response = await fetch('https://domain.com/image/test.jpg', options_json);
if (response.ok || response.status == 304) {
    console.log('Fetch JSON response: '+JSON.stringify(response));
}

Here are the contents of “response” afterward, which sadly only contains basic HTTP response information:

{
	"webSocket":null,
	"url":"https://domain.com/image/test.jpg",
	"redirected":false,
	"ok":true,
	"headers":{},
	"statusText":"OK",
	"status":200,
	"bodyUsed":false,
	"body": {
		"locked":false
	}
}

Where are the image size values that I was promised? :slight_smile:

I’m also concerned that requesting the image twice is very inefficient. It would better if I could request the image, get its sizing information, and then set my resize/overlay options and continue with the image processing without requesting the image a second time. It doesn’t seem Cloudflare set it up to be flexible, assuming that blindly processing our images is all we’ll ever need.

Well, you’re returning the response object.

If you want to access the response body which is JSON, you use the response.json() method.

1 Like

OMG, how did I miss that? I just assumed they would be properties and not methods.

Thank you!

I’ve moved a follow-up question to a new post, since there was no response to it here.