This question already has an answer here:
- Resizing an image in swing 4 answers
I am loading an image in Java Swing and want to display it in JPanel..The problem I am facing is that despite of image being loaded, it is not showing in JPanel..I can say that image is successfully loaded because it is showing me the correct path of the loaded image in my label..
Here is my code..
private static final int IMG_WIDTH = 120;
private static final int IMG_HEIGHT = 120;
JLabel label;
ImageIcon photo;
WritableRaster raster;
DataBufferByte data;
File image;
JFileChooser chooser;
FileNameExtensionFilter filter;
chooser = new JFileChooser();
chooser.setCurrentDirectory(image);
filter = new FileNameExtensionFilter("jpeg, gif and png files", "jpg", "gif", "png");
chooser.addChoosableFileFilter(filter);
int i = chooser.showOpenDialog(this);
if (i == JFileChooser.APPROVE_OPTION) {
image = chooser.getSelectedFile();
jLabel8.setText(image.getAbsolutePath());
try {
BufferedImage originalImage = ImageIO.read(image);
int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
BufferedImage resizeImageJpg = resizeImage(originalImage, type);
photo = new ImageIcon(toImage(resizeImageJpg));
jPanel2.removeAll();
label = new JLabel("", photo, JLabel.CENTER);
label.setIcon(photo);
jPanel2.add(label);
setVisible(true);
//converting buffered image to byte array
raster = resizeImageJpg.getRaster();
data = (DataBufferByte) raster.getDataBuffer();
} catch (IOException e) {
System.out.println(e.getMessage());
}
repaint();
chooser.setCurrentDirectory(image);
}
public Image toImage(BufferedImage bufferedImage) {
return Toolkit.getDefaultToolkit().createImage(bufferedImage.getSource());
}
private static BufferedImage resizeImage(BufferedImage originalImage, int type) {
BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
g.dispose();
return resizedImage;
}