Wednesday 4 September 2019

java - PNGs not displaying on JPanel



I have a class that extends JFrame. It loads 180 images into an array using the following code




ImageIO.read((getClass().getClassLoader().getResourceAsStream("render/"+constructImageFilename(i))));


The constructImageFilename function creates the filename for each file, located within a folder in the src called "render." It works fine.



The class then creates an ImagePanel with the first image in the array. It adds the ImagePanel, sets its size, and then shows up.



The ImagePanel class is a class that extends JPanel.



public class ImagePanel extends JPanel{

private BufferedImage img; //This is the image that the ImagePanel contains.
public ImagePanel() {
super();
}
public void setImage(BufferedImage i) {img=i;} //Mutator for the image.
public BufferedImage getImage() {return img;} //Accessor for the image.
public void paint(Graphics g) {
super.paint(g); //Paint the normal JPanel stuff.
((Graphics2D)g).drawImage(img,null,0,0); //Draw the image.
}

}


The same program works fine when the images loaded in are JPEGs, but the image doesn't diplay if the images are PNGs. It simply shows the default gray of the JPanel. There are no runtime errors, and the image was clearly loaded, as calling getRGB on the BufferedImage returns values.



What could be causing the PNG not to display?



UPDATE: I tried using a JLabel instead of my ImagePanel class. The JLabel seems to have the same problem. It displays when I use a JPEG, but displays nothing when I use a PNG.


Answer



It seems that the problem was the result of problems with alpha. I had to go back and make sure to check that all of the functions that could modify the image were set up to work properly with alpha. Evidently I had messed it up in some of them.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...