Unable to cast object of type 'Godot.CompressedTexture2D' to type 'Godot.Image'

I am trying to import an image from my code, but I keep getting the error “Unable to cast object of type ‘Godot.CompressedTexture2D’ to type ‘Godot.Image’”

I have this code written

var spriteToGet = (Sprite2D)GetNode(“picture”);
Godot.Image img = (Godot.Image)GD.Load(filepath);
img3.Resize(289, 404);
spriteToGet.Texture = ImageTexture.CreateFromImage(img);

I also tried

var spriteToGet = (Sprite2D)GetNode(“picture”);
Godot.Image img3 = (Godot.Image)GD.Load(filepath);
img.Resize(289, 404);
ImageTexture txtr = new ImageTexture();
txtr.SetImage(img);
spriteToGet.Texture = txtr;

But that gives me the same error.

Even without Resize() it doesn’t work.

I want to process the image trough a few more functions then Resize(), so importing with the filepath would not work.

How do I fix this?

Images are imported as Texture2D by default, you need to re-import your desired images in the editor as “Image” first.

2024-07-03-124912_3840x1080_scrot

1 Like

I guess I forgot to mention this, but filepath will is used with a FileDialog to select from the entire file browser. Thus the filepath looks something like
" E:\folders\picture.png ".
The selected file is not imported into Godot when I want it to be displayed, only present in the memory of the code.
The code does recognize the image, as I had code run through it before which ended up saving the image, and it did appear in my files as I wanted to.
I just am unable to display it.

Then you will want to use the Image.Load function directly. Not super familiar with Godot in C#, I presume this is the final code you want

var spriteToGet = (Sprite2D)GetNode(“picture”);

Godot.Image img = Godot.Image.new(); // not sure on creating new instances like this
// maybe it's `new Godot.Image;`
var loadError = img.Load(filepath); // check your errors :^)

img.Resize(289, 404);
spriteToGet.Texture = ImageTexture.CreateFromImage(img);
1 Like

This works.

I still get a Debugger error stating a loader is not found for the resource, but the image is displayed, and I am able to continue opening different images so it has no influence.
The scale also works on it, so I presume all the code I want to process will work as well.

Thanks

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.