How can I check if the size of a PoolByteArray of image data is correct?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By gregöpl

I want to load a PoolByteArray of image data into an Image. I’m using this code:

var img = Image.new()
img.create_from_data(64, 64, false, img_data.format, img_data.data)

The image should always have a size of 64x64 pixels. The problem is that sometimes it has a wrong size (because I get it over network). Then Godot prints an error when I call create_from_data. How can I check if the image data really has a size of 64x64 pixels before I load it?

:bust_in_silhouette: Reply From: AlexTheRegent

You can try to check size of your downloaded image. As far as I know, PNG use 4 bytes per one pixel, so your size should be 64x64x4 = 16384 bytes long. Assuming that img_data is Image.data, you can add next check before create_from_data:

if len(img_data.data) != 16384:
    # this is definitely not an 64x64 image 

That works with PNGs, but not with JPEGs. How can I do the same with JPEG images?

gregöpl | 2021-01-01 12:46

I found it out how to do it with JPEGs. Now I’m using this code:

if !(img_data.format == Image.FORMAT_RGBA8 and len(img_data.data) == 64*64*4) and !(img_data.format == Image.FORMAT_RGB8 and len(img_data.data) == 64*64*3):
    #the image data is not 64x64

Godot doesn’t seem to be using the original image format in data. It uses its own formats: for PNG images Image.FORMAT_RGBA8 and for JPEG images Image.FORMAT_RGB8 (JEPG images have no transparency, so they don’t need the alpha channel).

gregöpl | 2021-01-01 15:04