When i draw in image on a canvas, the white pixels surrounding the image are there too to the image boundries. Any tips on how to prevent this?
Asked
Active
Viewed 934 times
1
-
1You need to draw a transparent image: http://stackoverflow.com/questions/8272583/drawing-transparent-images-in-java-graphics2d – zebediah49 Dec 17 '12 at 04:53
-
I read that and I'm still confused x.x – Tikitaco Dec 17 '12 at 04:59
-
If the image isn't transparent to begin with, you can filter it so that the white pixels become transparent, but this will also occur with internal white pixels and so must be done with care. – Hovercraft Full Of Eels Dec 17 '12 at 05:00
-
I don't have any internal white pixels, so how do I filter it? – Tikitaco Dec 17 '12 at 05:01
3 Answers
1
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.net.URL;
class ImageTransparencyByColor {
public static BufferedImage getTransparentImage(
BufferedImage image, Color transparent) {
// must have a transparent image
BufferedImage img = new BufferedImage(
image.getWidth(),image.getHeight(),BufferedImage.TYPE_INT_ARGB);
Graphics2D g= img.createGraphics();
for (int x=0; x<img.getWidth(); x++) {
for (int y=0; y<img.getHeight(); y++) {
if (image.getRGB(x,y)!=transparent.getRGB()) {
img.setRGB( x,y, image.getRGB(x,y) );
}
}
}
g.dispose();
return img;
}
public static void main(String[] args) throws Exception {
URL url = new URL ("http://www.gravatar.com/avatar" +
"/ab5193916ccf152f96b0a69323e934a1?s=128&d=identicon&r=PG");
final BufferedImage trans = getTransparentImage(
ImageIO.read(url), Color.WHITE);
Runnable r = new Runnable() {
@Override
public void run() {
JLabel gui = new JLabel(new ImageIcon(trans));
JOptionPane.showMessageDialog(null, gui);
}
};
SwingUtilities.invokeLater(r);
}
}

Andrew Thompson
- 168,117
- 40
- 217
- 433
0
Insert your image on a JPanel instead. Canvas is a heavyweight component. Alternatively, try to change alpha of your Canvas. this.setBackground(new Color( 0,0,0,0 );
EDIT: Try this. Create a class for your image. The way you initialize your Image doesn't matter.
public class MyImage extends JPanel {
private final URL IMG_DIRECTORY = Main.class.getResource("/res/yourImage.png"); // Image directory
public MyImage() {
try {
img = ImageIO.read(IMG_DIRECTORY);
} catch (Exception e) {
e.printStackTrace();
}
this.setSize(img.getWidth(null), img.getHeight(null);
}
@Override
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
}
On your Frame class, declare your image class MyImage yourImage = new MyImage();
, then add it to whatever your ContentPane was.

Michael 'Maik' Ardan
- 4,213
- 9
- 37
- 60
-
If any of my 2 answer didn't help you, please post your SSCCE – Michael 'Maik' Ardan Dec 17 '12 at 05:21
-
The picture im loading is being overlayed over a series of different colored backgrounds, so i would need to the white pixels to be transparent somehow... – Tikitaco Dec 17 '12 at 07:04