1

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Tikitaco
  • 69
  • 7

3 Answers3

1

enter image description here

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

Use a .png image. A .gif image has only total/no transpancy.

underscore
  • 6,495
  • 6
  • 39
  • 78
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