Friday, May 17, 2013

Image background transparent

When you create an image (e.g. an image button to be placed on a web page), the image may have background color (e.g white or red background). Placing the image on the web page or viewing it on the area that does not have the same background color will make the image button look not so good. The ImageBackgroundTransparent program allows you to select an image file. When the image displays on the black background program window, to make the image background transparent just click the background area of the image.

Original image with white background

Original image

 Image after making its background transparent

Image background transparent

ImageBackgroundTransparent source code:

import javax.imageio.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.awt.color.*;
import javax.swing.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.filechooser.*;

class ShowImg extends Canvas implements ImageObserver{
            Color c;
            BufferedImage bi;
            Dimension ds;
            public void paint(Graphics g){
                           Graphics2D gd=(Graphics2D)g;
                            if(bi!=null){ //no image data is transfered from the ProgramWindow class
                                    int x=(int)ds.getWidth()/2-bi.getWidth()/2;
                                    int y=(int)ds.getHeight()/2-bi.getHeight()/2;
                                    if(c==null){ //If there is no color transfered from the ProgramWindow class
                                                    //just shows it
                                    else{ //There is a color transfered from the ProgramWindow class--user clicks the background area of the image
1                                             Image image=makeTransparency(bi,c);
2                                             BufferedImage resultImage= createBufferedImageFromImage(image, bi.getWidth(this), bi.getHeight(this));
3                                              gd.drawImage(resultImage,x,y,bi.getWidth(),bi.getHeight(),this);
4                                              String newImgFile=new String(System.currentTimeMillis()+".png");                                    
5                                             ImageIO.write(resultImage,"png",new File(newImgFile));
                                    }catch(IOException e){}
6          public void setColor(Color color){
7          public void setImageData(BufferedImage bim){

8          private BufferedImage  createBufferedImageFromImage(Image image, int width, int height)
                        BufferedImage dest = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
                        Graphics2D g2 = dest.createGraphics();
                        g2.drawImage(image, 0, 0, null);
                        g2.dispose(); //just clean the Graphics2D object coz it is no longer use
                        return dest;

9          public Image makeTransparency(Image bi, final Color col){
                        ImageFilter filter = new RGBImageFilter() {
                                    int imageRGB = col.getRGB();
                                    public final int filterRGB(int x, int y, int rgb) {
                                                 if (rgb==imageRGB ) { //matching selected background color
                                                            return 0x00FFFFFF & rgb; //make it transparent
                                                else {
                                                            return rgb; //no change
                        ImageProducer ip = new FilteredImageSource(bi.getSource(), filter); //create image producer object with image color filter object
                        return getToolkit().createImage(ip);           //create the image with transparent background

class ProgramWindow extends JFrame implements ActionListener{
                        ShowImg si;
                        Robot rb;
                        JLabel lblhelp;
                        ProgramWindow()  throws Exception{
                        setTitle("Image Background Transparency Maker");
                        JMenuBar mainmenu=new JMenuBar();
                        JMenu menu=new JMenu("File");
                        JMenuItem mopen=new JMenuItem("Open...");
                        JMenuItem mexit=new JMenuItem("Exit");

                        si=new ShowImg();
                        si.addMouseListener(new Mousexy());
                        add(si, BorderLayout.CENTER);
                        JPanel panel=new JPanel();
                        lblhelp=new JLabel();
                        setExtendedState(this.getExtendedState() | this.MAXIMIZED_BOTH);        
                        rb=new Robot();                  

            public void actionPerformed(ActionEvent e){
                                    JMenuItem source = (JMenuItem)(e.getSource());
10                                                                    setImage();
11                                                                    si.repaint();
12                                                                    validate();
                                                else if(source.getText().compareTo("Exit")==0)

            public void setImage(){
                        JFileChooser chooser = new JFileChooser();
                        FileNameExtensionFilter filter = new FileNameExtensionFilter("PNG & JPG images","png","jpg");
                        int returnVal = chooser.showOpenDialog(this);
                        if(returnVal == JFileChooser.APPROVE_OPTION) {                           
                                    String filename=chooser.getSelectedFile().toString();
                                    si.setImageData( File(filename)));               
                         }catch(Exception e){}  

13        class Mousexy extends MouseAdapter{
                                    public void mousePressed(MouseEvent e){
                                                Color color=rb.getPixelColor(e.getX(),e.getY());

 public class ImageBackgroundTransparent{

            public static void main(String[] args)  throws Exception{
                        new ProgramWindow();

Code Explanation:
1 The makeTransparency method is invoked to create an image with transparent background. This method has two arguements: bi (image) and c (color). The bi argument is the BufferedImage object that stores the image selected by the user. The c argument is the color fetched by the Robot object rb when the user clicks the background area of the image shown on the program window.
2 The makeTransparency method returns the image object. You can not manipulate or write the image object directly to the file so the createBufferedImageFromImage method is invoked to convert the image object back to the BufferedImage object.
3 Draw the result image on the Canvas area so you are able to see the change on the image background.
4 Create  newImgFile String object. It is file name of the image to be writren to your local disk drive.
5 Write the image file to the local disk drive. This is the result image with transparent background.
6 The setColor method is invoked when the user clicks the background area of the image. The Robot rb object fetches the color at the point that the user clicked then  this color value is transfered to c variable of the ShowImage si object through the setColor method.
7 The setImageData method transfers the image selected by the user to the ShowImage si object to display.
This method is invoked from the setImage method of the ProgramWindow class when the user selects the image from file dialog.
8 The createBufferedImageFromImage has code to create a BufferedImage object from the Image object.
To do this, first you will need to create a blank BufferedImage object dest. Then get the Graphics2D object from this BufferedImage object. The next step is placing the Image object image in the BufferedImage object by invoking the drawImage method of the Graphics2D object.
9 The makeTransparency method has code to create an image object with transparent background from the original image.
10 The setImage method is invoked to allow the user selects the image from the file dialog. The image will be
transfered to the BufferedImage bi of the ShowImg si object by invoking its setImageData method.
11 The repaint method of the si object is invoked to display the image.
12 To make use the components on the program window display correctly after the image shows, you need to invoke the validate method.
13 The Mousexy extends MouseAdapter class. The MouseAdapter class has the mousePressed method that can be implemented to detect a point on the image where the user clicks. The Robot object rb has the getPixelColor method that can be invoked to get the color value at the clicked point. The color value is then transfered to the ShowImge si object through its setColor method so the image is ready for making background transparenct and writing to the file.


  1. It is a great website.. If you are games lover and love to play games word cookies game download is the most easiest way to get latest games hill climb racing 2 anytime you need to follow just few simple steps five nights at freddys 4 | hotmail login

  2. I would like more information about this. Thanks for sharing. | super mechs 2 | supermechs | wingsio