Load png and read pixels

I want to load an png image but not sure how. I’ve found the Image class but I can’t find an usage example for how to load an png and then use that class to read pixels from the loaded png.

Could I please get a hint? :slight_smile:

(I’m using C++ not Lua)

To load a PNG image as an UI element, you could use something like this:

BorderImage* yourImage_ = new BorderImage(context_);

To load a PNG image as a sprite, check the samples 24_Urho2DSprite and 36_Urho2DTileMap.

And to load a PNG image as an “object” on the 3D space, I guess you could load it on a plane object (similar to how it was done on sample 38_SceneAndUILoad), maybe like this:

Node* planeNode_ = scene_->CreateChild("Plane");
planeNode_->SetScale(Vector3(2.0f, 2.0f, 2.0f));
planeNode_->SetRotation(Quaternion(-90.0f, 0.0f, 0.0f));
StaticModel* planeObject = planeNode_->CreateComponent<StaticModel>();

And yourMaterial.xml:

<technique name="Techniques/DiffUnlit.xml"/>
<texture name="yourImage.png" unit="diffuse"/>
<parameter name="MatDiffColor" value="1 1 1 1"/>
<parameter name="MatSpecColor" value="1 1 1 1"/>

I don’t have much experience with the engine yet, so I don’t know how you could read the pixels of the PNG image. But I guess you could use the File API and the Deserializer for that. Maybe something like this:

Something imagePixels = (cache->GetFile("yourImage.png"))->Read();


File imageFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "yourImage.png", FILE_READ);
Something imagePixels = imageFile.Read();
1 Like

You can use Image to load a PNG and read pixels. Pass a Deserializer (such as a File ) to the Load method. You can then call GetPixel() on the image.

1 Like

So I’ve loaded an File, but how do I use that in the Deserializer class? I don’t understand how to make the Deserializer class use the File object, in order to pass it to Image->BeginLoad().

File inherits from Deserializer. Just pass the file to Image->Load(). (Image inherits Load() from Resource, which will call both BeginLoad() and EndLoad()).

File file(context,fname);
Image i;