Original image with white background
Image after making its background transparent
ImageBackgroundTransparent source code:
import
javax.imageio.*;
import
javax.imageio.stream.*;
import
java.io.*;
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;
ShowImg(){
ds=getToolkit().getScreenSize();
}
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;
try{
if(c==null){
//If there is no color transfered from the ProgramWindow class
//just shows it
gd.drawImage(bi,x,y,bi.getWidth(),bi.getHeight(),this);
}
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){
c=color;
}
7 public void setImageData(BufferedImage
bim){
bi=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");
setIconImage(getToolkit().getImage("winicon.png"));
JMenuBar mainmenu=new
JMenuBar();
JMenu menu=new
JMenu("File");
JMenuItem mopen=new
JMenuItem("Open...");
mopen.setMnemonic(KeyEvent.VK_O);
mopen.addActionListener(this);
JMenuItem mexit=new
JMenuItem("Exit");
mexit.setMnemonic(KeyEvent.VK_X);
mexit.addActionListener(this);
menu.add(mopen);
menu.add(mexit);
mainmenu.add(menu);
setJMenuBar(mainmenu);
si=new ShowImg();
si.setBackground(Color.BLACK);
si.addMouseListener(new
Mousexy());
add(si,
BorderLayout.CENTER);
JPanel panel=new
JPanel();
lblhelp=new JLabel();
lblhelp.setForeground(Color.BLUE);
panel.add(lblhelp);
panel.setBackground(Color.BLACK);
add(panel,BorderLayout.SOUTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setExtendedState(this.getExtendedState()
| this.MAXIMIZED_BOTH);
setVisible(true);
rb=new Robot();
}
public void
actionPerformed(ActionEvent e){
JMenuItem
source = (JMenuItem)(e.getSource());
if(source.getText().compareTo("Open...")==0)
{
10 setImage();
11 si.repaint();
12 validate();
}
else
if(source.getText().compareTo("Exit")==0)
System.exit(0);
}
public void setImage(){
try{
JFileChooser chooser =
new JFileChooser();
FileNameExtensionFilter
filter = new FileNameExtensionFilter("PNG & JPG
images","png","jpg");
chooser.setFileFilter(filter);
chooser.setMultiSelectionEnabled(false);
int
returnVal = chooser.showOpenDialog(this);
if(returnVal
== JFileChooser.APPROVE_OPTION) {
String
filename=chooser.getSelectedFile().toString();
si.setImageData(ImageIO.read(new
File(filename)));
}
}catch(Exception e){}
}
13 class Mousexy extends MouseAdapter{
public void
mousePressed(MouseEvent e){
Color
color=rb.getPixelColor(e.getX(),e.getY());
si.setColor(color);
si.repaint();
}
}
}
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.
I would like more information about this. Thanks for sharing.
ReplyDeletewings.io | super mechs 2 | supermechs | wingsio