javatype-conversionbufferedimagejavax.imageio

How to change the image type of a BufferedImage which is loaded from file?


I'm trying to access the pixels in a BufferedImage which is loaded from a file using ImageIO.read(filePath), but I get this error:

Exception in thread "Game" java.lang.ClassCastException: java.awt.image.DataBufferByte cannot be cast to java.awt.image.DataBufferInt
    at com.package.graphics.Texture.<init>(Texture.java:29)
    at com.package.graphics.Texture.loadTexture(Texture.java:40)
    at com.package.Game.run(Game.java:71)
    at java.lang.Thread.run(Unknown Source)

In the code, the line which the error is on, is in the constructor and looks like this:

// Get the pixel array from the BufferedImage
this.pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();

As I understand this, the BufferedImage isn't of the type BufferedImage.TYPE_INT_RGB or BufferedImage.TYPE_INT_ARGB. Because I use these types in the rest of my game, I wonder if there is a way to 'convert' the loaded image from the type it was loaded as, to another.
In my case, I want to convert the image type to BufferedImage.TYPE_INT_ARGB.


Solution

  • Create a new Buffered image with the type you want

    BufferedImage in = ImageIO.read(img);
    BufferedImage newImage = new BufferedImage(in.getWidth(), in.getHeight(), BufferedImage.TYPE_INT_ARGB);
    
    Graphics2D g = newImage.createGraphics();
    g.drawImage(in, 0, 0, in.getWidth(), in.getHeight(), null);
    g.dispose();