Reputation: 129
what I'm making is very simple image editing program and I have a problem with something. I saved the images in DB and converted it as a ImageIcon
so that it can go through server sockets and such (serializable).
So through the VO I get the ImageIcon
to GUI and convert it to BufferedImage
so that I can edit that. But since I have to set the image type and there are a lot of pictures with different image types (at least it seems so), some pictures turn into something I didn't want them to be.
So, basically I'm asking if there's is another way to convert ImageIcon
to BufferedImage
. Some ways to convert it without setting the one single, fixed image type. If there is none I'll have to give that part up.
Below is some 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");
}
}
}
Upvotes: 4
Views: 1875
Reputation: 55
It is always a good practice to store only the image links in the DB. But this still depends on the scenario of your application such as - you have a fixed set of images, need an easy way to do backups, images change very frequently. There are many articles in Stackoverflow - so go ahead and read it. Store pictures as files or in the database for a web app?
One solution is BufferedImage bi = new BufferedImage(icon.getIconWidth(),icon.getIconHeight(),BufferedImage.TYPE_INT_RGB); Graphics g = bi.createGraphics(); icon.paintIcon(null, g, 0,0); g.dispose();
Upvotes: 1
Reputation: 6414
If you don't need transparency, you can use BufferedImage.TYPE_INT_RGB that will solve your problem.
If you wish to have tranparency, then you need to set the way you wish to draw a copy of your image into destination by:
Graphics2D bgr = bimage.createGraphics();
bgr.setComposite(AlphaComposite.SRC); // read the doc of this
the problem you have is probably because when you create a new BufferedImage of type TYPE_INT_ARGB all pixels in that image are transparent, so when yoou draw your src image to it it will mix with these tranparent pixels and all image will be transparent. The resolution is to use other mode of merging src and dst images by setting the apropriate AplhaComposite.
Upvotes: 2