0 votes

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?

Godot version 3.1
in Engine by (15 points)

1 Answer

+1 vote
Best answer

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 
by (1,114 points)
selected by

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

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).

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.