How can I get width and height values of the image

2019-09-16 09:02发布

问题:

I create an application on Google App Engine. We keep all images on Google Cloud Storage. This app serves photos with using get_serving_url method. The application does size manipulations by changing the serving url. At this point, we need to get image width and height values.

I can do it in this way:

blob_key = blobstore.create_gs_key(_gspath)
data = blobstore.fetch_data(blob_key, 0, 50000)
raw_image = images.Image(image_data=data)

After doing that, I can get width and height values via raw_image variable. But I guess this way isn't good. I don't want to fetch all data because some images are too big. How can I get this information without fetch data operation?

回答1:

Google App Engine does not provide a built-in way to get dimensions of an image without loading it into memory. There are some alternatives you could use:

  1. You could create a service running on GCE that will fetch an image from GCS, and return the size. Your GAE app could then call this. This moves the memory requirement to GCE, which is much more able to handle it.

  2. If you only use PNG, GIF, BMP and ICO formats (not JPEG or TIFF) then you can just fetch the first 26 bytes of the image and pass it as image_data. That is enough for the Images class to be able to get width and height.

  3. If you control the upload process, you could store the width and height as metadata in GCS. Then you don't need to fetch the GCS object, just it's metadata in order to get the dimensions.