How to save texture as an image

I’m encountering some texture glitches in my game, so I figured I’d save the texture as a png and check to see if I can figure out where the problem is.

Here’s the code that I use to save the texture:

Texture2D tex = /*code that gets the texture*/; BinaryExporter exporter = new BinaryExporter(); try { exporter.save(tex, new File("sweetSpotMap.png")); } catch (IOException e1) { e1.printStackTrace(); }

Thing is, when I try to open the file I created, my computer doesn’t know what it is.
How do I tell BinaryExporter the right way to format the file as a png?

The BinaryExporter is an object serializer, so what you are saving is an object that contains an image and not a png image.
I don’t know if there is a faster way, but what i do is convert the Texture.getImage() to a BufferedImage with ImageToAwt.convert and then save it with ImageIO.write

It’s not even as complicated as all that…

    public void savePng( File f, Image img ) throws IOException {
        OutputStream out = new FileOutputStream(f);
        try {            
            JmeSystem.writeImageFile(out, "png", img.getData(0), img.getWidth(), img.getHeight());  
        } finally {
            out.close();
        }             
    }

Edit: for the record, I cut and pasted that from here: SimArboreal-Editor/FileActionsState.java at master · Simsilica/SimArboreal-Editor · GitHub
…since I generate texture atlases you may find other useful bits in that project also.

5 Likes