Convert ImageIcon to BufferedImage (how to set image type)

what i am doing is a very simple image editing program and i have a problem with something. I saved the images in the database and converted it ImageIconso that it could go through the server sockets and such (serializable).

So, through VO, I get ImageIconin the GUI and convert it to BufferedImageso that I can edit it. But since I need to set the type of image, and there are many images with different types of images (at least it seems so), some photos turn into something that I did not want.

So basically I ask if there is another way to convert ImageIconto BufferedImage. Some ways to convert it without installing a single fixed image type. If not, I will have to give this part back.

The following is part of my code:

private class TableSelectEvent extends MouseAdapter {
    @Override
    public void mouseClicked(MouseEvent e) {
        int selectedRow = table.getSelectedRow();
        loadedImageIcon = UserImageReceived.get(selectedRow).getImage();
        originalImage = loadedImageIcon.getImage();

        selectedImageName = UserImageReceived.get(selectedRow).getFileName();
        if (originalImage != null) {
            Image rbi = originalImage.getScaledInstance(lblSelectedImage.getWidth(), lblSelectedImage.getHeight(), Image.SCALE_SMOOTH);
            lblSelectedImage.setIcon(new ImageIcon(rbi));
            bimage = new BufferedImage(originalImage.getWidth(null), originalImage.getHeight(null), BufferedImage.TYPE_INT_ARGB);
            // this, BufferedImage.TYPE_INT_ARGB part is the problem I'm having!
            Graphics2D bgr = bimage.createGraphics();
            bgr.drawImage(originalImage, 0, 0, null);
            bgr.dispose();
        } else {
            System.out.println("originalImage == null");
        }
    }
}
+4
source share
2 answers

If you don't need transparency, you can use BufferedImage.TYPE_INT_RGB , which will solve your problem.

If you want to have transparency, you need to specify the way you want to draw a copy of your image at the destination:

 Graphics2D bgr = bimage.createGraphics();
 bgr.setComposite(AlphaComposite.SRC); // read the doc of this

, , , , BufferedImage TYPE_INT_ARGB , , src, , . src dst, AplhaComposite.

+2
  • . , : , , . Stackoverflow - . -?

  • BufferedImage bi = new BufferedImage (icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_RGB); g = bi.createGraphics(); icon.paintIcon(null, g, 0,0); g.dispose();

+1

Source: https://habr.com/ru/post/1618070/


All Articles