How to make drawn images transparent in Java
Asked Answered
R

5

7

I got the animation to work in my Snake Clone Game. But the problem based on the picture is that the images do not have transparency(notice the white background of the circle pictures. Programming-wise, is there a fix to be able to include transparency to these drawn images?

Here's a picture containing my code and the output of the program.

enter image description here

P.S. On a side note, I decided to paste the direct link instead of the IMG code because I cannot seem to get it to display on StackOverFlow. I put an exclamation point in the front of the IMG code but it did not work so here's the direct link.

Ruiz answered 31/12, 2012 at 4:20 Comment(3)
Is your image's background is transparent?Mobilize
The image background has no transparency. The background is simply setting the JPanel's background to Color.BLACK like this: setBackground(Color.black)Ruiz
FYI, when asking a question, don't take screenshots of your code in your editor. Put text snippets of your code in your question.Kareykari
S
11

As the other answer mentioned, the easiest way would probably be to simply use PNG images which have a transparent background (you can create these with an image editor like GIMP). Alternatively, if you are limited to PNG images with a solid background, here's an example of how to change a given color (e.g. white) in the PNG to transparent:

enter image description here

import java.awt.*;
import java.awt.image.*;
import javax.swing.*;

public class SimpleFrame extends JFrame {
   JPanel mainPanel = new JPanel() {
      ImageIcon originalIcon = new ImageIcon("~/Pictures/apple.png");

      ImageFilter filter = new RGBImageFilter() {
         int transparentColor = Color.white.getRGB() | 0xFF000000;

         public final int filterRGB(int x, int y, int rgb) {
            if ((rgb | 0xFF000000) == transparentColor) {
               return 0x00FFFFFF & rgb;
            } else {
               return rgb;
            }
         }
      };

      ImageProducer filteredImgProd = new FilteredImageSource(originalIcon.getImage().getSource(), filter);
      Image transparentImg = Toolkit.getDefaultToolkit().createImage(filteredImgProd);

      public void paintComponent(Graphics g) {
         g.setColor(getBackground());
         g.fillRect(0, 0, getSize().width, getSize().height);

         // draw the original icon
         g.drawImage(originalIcon.getImage(), 100, 10, this);
         // draw the transparent icon
         g.drawImage(transparentImg, 140, 10, this);
      }
   };

   public SimpleFrame() {
      super("Transparency Example");

      JPanel content = (JPanel)getContentPane();
      mainPanel.setBackground(Color.black);
      content.add("Center", mainPanel);
   }

   public static void main(String[] argv) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            SimpleFrame c = new SimpleFrame();
            c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            c.setSize(280,100);
            c.setVisible(true);
         }
      });
   }
}
Stav answered 31/12, 2012 at 5:2 Comment(4)
I notice you used single or two letters for your variable names. Is this practice in naming only for this given example?Ruiz
My variable naming is not really very good here, as this is just an example. More descriptive variable names could be chosen.Stav
I see thanks! It looks like a really elegant example. Personally,the introductory Java class I took never delved into the Java classes you used in your example or image transparency. I will look into your example. =] Appreciate the given example, 808sound!Ruiz
Sure, glad to help. BTW I edited the code to make it a bit more readable.Stav
E
4

Don't use paint to draw your images. Use some other program that uses alpha like Paint.net or Photoshop... If your going to use circles forever then you can use g.drawOval(x, y, w, h).

Exposed answered 31/12, 2012 at 4:38 Comment(1)
but the issue comes up in that I need to add alpha channels to every single images. This is fine if I just used 3 pictures. But what happens in the event if my project uses a lot of pictures like 1000 images?Ruiz
G
2

Simple use type to ARGB like this

BufferedImage image = new BufferedImage(
                 width, height,
                 BufferedImage.TYPE_INT_ARGB);

I hope it should work.

Gorki answered 27/4, 2015 at 12:37 Comment(0)
G
0
  public BufferedImage makeTransparentImage(BufferedImage br) {
    for (int i = 0; i < br.getHeight(); i++) {
        for (int j = 0; j < br.getWidth(); j++) {
            Color c = new Color(br.getRGB(j, i));
            int r = c.getRed();
            int b = c.getBlue();
            int g = c.getGreen();
            if ((r == 255 && b == 255 && g == 255)) {
                System.out.println("r g b " + r + g + b);
                br.setRGB(j, i, 0xFF000000);
            }
        }
    }
    return br;
}
Gleich answered 12/12, 2014 at 15:13 Comment(1)
Not sure if I use to wrong, but, this doesn't work for me.Hydrargyrum
E
0

If you draw a simple picture, The easiest and fastest way I know... Draw a picture in Macrosoft PowerPoint and click "Save as Picture" to get a transparent background. Next...

public class Node {
Image nodeImage[] = new Image[3];


public Node() {
    try {
        String address = "C:\\Users\\Desktop\\practice\\Simulation\\img\\";
        nodeImage[0] = ImageIO.read(new File(address + "Node_noVehicle.png"));
        nodeImage[1] = ImageIO.read(new File(address + "Node_setVehicle.png"));
        nodeImage[2] = ImageIO.read(new File(address + "Node_inVehicle.png"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

@Override
protected void paintComponent(Graphics g) {
  super.paintComponent(g);  
  Graphics2D g2dtemp = (Graphics2D) g.create();
  g2dtemp.drawImage(Node.nodeImage[0],(int)x,(int)y,width,height,this);
}

}

Draw a picture in Macrosoft PowerPoint and click "Save as Picture" to get a transparent background.

Ewing answered 30/8, 2019 at 6:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.