/**
*
*/
package de.tutorials;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageProducer;
import java.awt.image.RGBImageFilter;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class Transparency {
public static void main(String[] args) {
JFrame window = new JFrame("Transparency");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new FlowLayout( ));
JLabel jpgLabel = new JLabel("jpg", new ImageIcon("eurofighter.jpg"),
SwingConstants.CENTER);
jpgLabel.setBackground(Color.RED);
jpgLabel.setOpaque(true);
window.getContentPane( ).add(jpgLabel);
JLabel pngLabel = new JLabel("png", new ImageIcon("eurofighter.png"),
SwingConstants.CENTER);
pngLabel.setBackground(Color.RED);
pngLabel.setOpaque(true);
window.getContentPane( ).add(pngLabel);
BufferedImage tmp;
try {
tmp = ImageIO.read(new File("eurofighter.jpg"));
final ColorRange range = new ColorRange(238, 238, 238, 238, 238,
238);
ImageFilter transparencyFilter = new RGBImageFilter( ) {
public final int filterRGB(int x, int y, int rgb) {
if (range.contains(rgb | 0xFF000000)) {
return 0x00FFFFFF & rgb;
}
else {
return rgb;
}
}
};
ImageProducer imageProducer = new FilteredImageSource(tmp
.getSource( ), transparencyFilter);
Image filtered = Toolkit.getDefaultToolkit( ).createImage(
imageProducer);
JLabel filteredLabel = new JLabel("filtered", new ImageIcon(
filtered), SwingConstants.CENTER);
filteredLabel.setBackground(Color.RED);
filteredLabel.setOpaque(true);
window.getContentPane( ).add(filteredLabel);
}
catch (IOException e) {
e.printStackTrace( );
}
window.setSize(300, 300);
window.pack( );
window.setVisible(true);
}
static class ColorRange {
int redStart;
int redEnd;
int greenStart;
int greenEnd;
int blueStart;
int blueEnd;
public ColorRange(int redStart, int redEnd, int greenStart,
int greenEnd, int blueStart, int blueEnd) {
this.redStart = redStart;
this.redEnd = redEnd;
this.greenStart = greenStart;
this.greenEnd = greenEnd;
this.blueStart = blueStart;
this.blueEnd = blueEnd;
}
public boolean contains(int rgb) {
Color color = new Color(rgb);
return isInRange(color.getRed( ), redStart, redEnd)
&& isInRange(color.getGreen( ), greenStart, greenEnd)
&& isInRange(color.getBlue( ), blueStart, blueEnd);
}
private boolean isInRange(int value, int start, int end) {
return value >= start && value <= end;
}
}
}