Java/2D Graphics GUI/Color Model — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 06:55, 1 июня 2010
Содержание
Checking for Color Models
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DirectColorModel;
import java.awt.image.IndexColorModel;
import javax.swing.JFrame;
public class GraphicsInfo extends JFrame {
private void printModelType(ColorModel cm) {
if (cm instanceof DirectColorModel) {
System.out.println("DirectColorModel");
} else if (cm instanceof IndexColorModel) {
System.out.println("IndexColorModel");
} else {
System.out.println("Unknown ColorModel");
}
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
GraphicsConfiguration gc = g2d.getDeviceConfiguration();
printModelType(gc.getColorModel());
BufferedImage bi = new BufferedImage(20, 20,
BufferedImage.TYPE_BYTE_INDEXED);
Graphics2D g2d2 = bi.createGraphics();
GraphicsConfiguration gc2 = g2d2.getDeviceConfiguration();
printModelType(gc2.getColorModel());
bi = new BufferedImage(20, 20, BufferedImage.TYPE_INT_ARGB);
g2d2 = bi.createGraphics();
gc2 = g2d2.getDeviceConfiguration();
printModelType(gc2.getColorModel());
bi = new BufferedImage(20, 20, BufferedImage.TYPE_USHORT_565_RGB);
g2d2 = bi.createGraphics();
gc2 = g2d2.getDeviceConfiguration();
printModelType(gc2.getColorModel());
}
public static void main(String args[]) {
Frame f = new GraphicsInfo();
f.setTitle("GraphicsInfo");
f.setSize(300, 250);
f.show();
}
}
Color Composite
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.TexturePaint;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ColorComposite extends JFrame {
MyCanvas canvas;
JTextField textField;
float alphaValue = 0.65f;
public ColorComposite() {
super();
Container container = getContentPane();
canvas = new MyCanvas();
container.add(canvas);
JPanel panel = new JPanel();
JLabel label = new JLabel("Color-Composite: ");
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 65);
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JSlider tempSlider = (JSlider) e.getSource();
alphaValue = (float) (tempSlider.getValue() / 100.0);
textField.setText(Float.toString(alphaValue));
canvas.repaint();
}
});
textField = new JTextField("0.65", 4);
panel.add(label);
panel.add(slider);
panel.add(textField);
container.add(BorderLayout.SOUTH, panel);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setSize(450,450);
setVisible(true);
}
public static void main(String arg[]) {
new ColorComposite();
}
class MyCanvas extends JLabel {
Rectangle2D rec1, rec2, rec3, rec4, rec5;
MyCanvas() {
rec1 = new Rectangle2D.Float(25, 25, 75, 150);
rec2 = new Rectangle2D.Float(125, 25, 100, 75);
rec3 = new Rectangle2D.Float(75, 125, 125, 75);
rec4 = new Rectangle2D.Float(225, 125, 125, 75);
rec5 = new Rectangle2D.Float(150, 50, 125, 175);
setBackground(Color.white);
setSize(400, 225);
}
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
AlphaComposite ac = AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, alphaValue);
g2D.setComposite(ac);
g2D.setStroke(new BasicStroke(5.0f));
g2D.draw(rec1);
GradientPaint gp = new GradientPaint(125f, 25f, Color.yellow, 225f,
100f, Color.blue);
g2D.setPaint(gp);
g2D.fill(rec2);
BufferedImage bi = new BufferedImage(5, 5,
BufferedImage.TYPE_INT_RGB);
Graphics2D big = bi.createGraphics();
big.setColor(Color.magenta);
big.fillRect(0, 0, 5, 5);
big.setColor(Color.black);
big.drawLine(0, 0, 5, 5);
Rectangle r = new Rectangle(0, 0, 5, 5);
TexturePaint tp = new TexturePaint(bi, r);
g2D.setPaint(tp);
g2D.fill(rec3);
g2D.setColor(Color.green);
g2D.fill(rec4);
g2D.setColor(Color.red);
g2D.fill(rec5);
}
}
}
Color model demo
import java.awt.Color;
import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.awt.image.ColorModel;
import java.awt.image.ruponentColorModel;
import java.awt.image.DataBuffer;
public class ComponentTest {
public static void main(String[] args) {
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
ColorModel cm = new ComponentColorModel(cs, new int[] { 5, 6, 5 },
false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
Color fifty = new Color(cs, new float[] { 1.0f, 1.0f, 1.0f }, 0);
float[] components = fifty.getComponents(null);
System.out.print("Original normalized components: ");
for (int i = 0; i < 3; i++)
System.out.print(components[i] + " ");
System.out.println();
int[] unnormalized = cm.getUnnormalizedComponents(components, 0, null,
0);
System.out.print("Original unnormalized components: ");
for (int i = 0; i < 3; i++)
System.out.print(unnormalized[i] + " ");
System.out.println();
Object pixel = cm.getDataElements(unnormalized, 0, (Object) null);
System.out.print("Pixel samples: ");
byte[] pixelBytes = (byte[]) pixel;
for (int i = 0; i < 3; i++)
System.out.print(pixelBytes[i] + " ");
System.out.println();
unnormalized = cm.getComponents(pixel, null, 0);
System.out.print("Derived unnormalized components: ");
for (int i = 0; i < 3; i++)
System.out.print(unnormalized[i] + " ");
System.out.println();
components = cm.getNormalizedComponents(unnormalized, 0, null, 0);
System.out.print("Derived normalized components: ");
for (int i = 0; i < 3; i++)
System.out.print(components[i] + " ");
System.out.println();
}
}
Color Schema Generator
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
// Revised from jaspersoft ireport designer
import java.awt.Color;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
*
* @author gtoffoli
*/
public class ColorSchemaGenerator {
public final static String SCHEMA_DEFAULT = "default";
public final static String SCHEMA_PASTEL = "pastel";
public final static String SCHEMA_SOFT = "soft";
public final static String SCHEMA_HARD = "hard";
public final static String SCHEMA_LIGHT = "light";
public final static String SCHEMA_PALE = "pale";
private static float[] schema_default = new float[]{ -1f,-1f, 1f,-0.7f, 0.25f,1f, 0.5f,1f };
private static float[] schema_pastel = new float[]{ 0.5f,-0.9f, 0.5f,0.5f, 0.1f,0.9f, 0.75f,0.75f };
private static float[] schema_soft = new float[]{ 0.3f,-0.8f, 0.3f,0.5f, 0.1f,0.9f, 0.5f,0.75f };
private static float[] schema_hard = new float[]{ 1f,-1f, 1f,-0.6f, 0.1f,1f, 0.6f,1f };
private static float[] schema_light = new float[]{ 0.25f,1f, 0.5f,0.75f, 0.1f,1f, 0.5f,1f };
private static float[] schema_pale = new float[]{ 0.1f,-0.85f, 0.1f,0.5f, 0.1f,1f, 0.1f,0.75f };
private static java.util.Map<String, float[]> schemas = new HashMap<String, float[]>();
static {
schemas.put(SCHEMA_DEFAULT, schema_default);
schemas.put(SCHEMA_PASTEL, schema_pastel);
schemas.put(SCHEMA_SOFT, schema_soft);
schemas.put(SCHEMA_HARD, schema_hard);
schemas.put(SCHEMA_LIGHT, schema_light);
schemas.put(SCHEMA_PALE, schema_pale);
}
/**
* Create the schema color.
*
* @param base
* @param i (a color between 0 and 3)
* @param schemaName
* @return
*/
public static Color createColor(Color base, int i, String schemaName)
{
i = Math.abs(i %= 3);
if (schemaName == null) schemaName = SCHEMA_SOFT;
float[] schema = schemas.get(schemaName);
float[] components = Color.RGBtoHSB(base.getRed(), base.getGreen(), base.getBlue(), null);
components[1] = (schema[i*2] < 0) ? -schema[i*2] * components[1] : schema[i*2];
if (components[1] > 1) components[1] = 1.0f;
if (components[1] < 0) components[1] = 0;
components[2] = (schema[i*2+1] < 0) ? -schema[i*2+1] * components[2] : schema[i*2+1];
if (components[2] > 1) components[2] = 1.0f;
if (components[2] < 0) components[2] = 0;
return new Color( Color.HSBtoRGB(components[0], components[1], components[2]));
}
public static List<String> getColors()
{
if (colorsList == null)
{
colorsList = new ArrayList<String>();
colorsMap = new HashMap<String,String>();
for (int i=0; i<colors.length/2; ++i)
{
colorsList.add( colors[i*2] );
colorsMap.put(colors[i*2], colors[(i*2)+1]);
}
}
return colorsList;
}
public static Color getColor(String name)
{
if (colorsMap == null)
{
getColors();
}
String rgb = colorsMap.get(name);
return decodeColor("#"+rgb);
}
public static java.awt.Color decodeColor(String colorString)
{
java.awt.Color color = null;
char firstChar = colorString.charAt(0);
if (firstChar == "#")
{
color = new java.awt.Color(Integer.parseInt(colorString.substring(1), 16));
}
else if ("0" <= firstChar && firstChar <= "9")
{
color = new java.awt.Color(Integer.parseInt(colorString));
}
else
{
color = java.awt.Color.black;
}
return color;
}
static private List<String> colorsList = null;
static private HashMap<String, String> colorsMap = null;
static private String[] colors = new String[]{
"Aliceblue","F0F8FF",
"Antiquewhite","FAEBD7",
"Aqua","00FFFF",
"Aquamarine","7FFFD4",
"Azure","F0FFFF",
"Beige","F5F5DC",
"Bisque","FFE4C4",
"Black","000000",
"Blanchedalmond","FFEBCD",
"Blue","0000FF",
"Blueviolet","8A2BE2",
"Brown","A52A2A",
"Burlywood","DEB887",
"Cadetblue","5F9EA0",
"Chartreuse","7FFF00",
"Chocolate","D2691E",
"Coral","FF7F50",
"Cornflowerblue","6495ED",
"Cornsilk","FFF8DC",
"Crimson","DC143C",
"Cyan","00FFFF",
"Darkblue","00008B",
"Darkcyan","008B8B",
"Darkgoldenrod","B8860B",
"Darkgray","A9A9A9",
"Darkgreen","006400",
"Darkkhaki","BDB76B",
"Darkmagenta","8B008B",
"Darkolivegreen","556B2F",
"Darkorange","FF8C00",
"Darkorchid","9932CC",
"Darkred","8B0000",
"Darksalmon","E9967A",
"Darkseagreen","8FBC8F",
"Darkslateblue","483D8B",
"Darkturqoise","00CED1",
"Darkslategray","2F4F4F",
"Darkviolet","9400D3",
"Deeppink","FF1493",
"Deepskyblue","00BFFF",
"Dimgray","696969",
"Dodgerblue","1E90FF",
"Firebrick","B22222",
"Floralwhite","FFFAF0",
"Forestgreen","228B22",
"Fuchsia","FF00FF",
"Gainsboro","DCDCDC",
"Ghostwhite","F8F8FF",
"Gold","FFD700",
"Goldenrod","DAA520",
"Gray","808080",
"Green","008000",
"Greenyellow","ADFF2F",
"Honeydew","F0FFF0",
"Hotpink","FF69B4",
"Indianred","CD5C5C",
"Indigo","4B0082",
"Ivory","FFFFF0",
"Khaki","F0E68C",
"Lavender","E6E6FA",
"Lavenderblush","FFF0F5",
"Lawngreen","7CFC00",
"Lemonchiffon","FFFACD",
"Lightblue","ADD8E6",
"Lightcoral","F08080",
"Lightcyan","E0FFFF",
"Lightgoldenrodyellow","FAFAD2",
"Lightgreen","90EE90",
"Lightgrey","D3D3D3",
"Lightpink","FFB6C1",
"Lightsalmon","FFA07A",
"Lightseagreen","20B2AA",
"Lightskyblue","87CEFA",
"Lightslategray","778899",
"Lisghtsteelblue","B0C4DE",
"Lightyellow","FFFFE0",
"Lime","00FF00",
"Limegreen","32CD32",
"Linen","FAF0E6",
"Magenta","FF00FF",
"Maroon","800000",
"Mediumaquamarine","66CDAA",
"Mediumblue","0000CD",
"Mediumorchid","BA55D3",
"Mediumpurple","9370DB",
"Mediumseagreen","3CB371",
"Mediumslateblue","7B68EE",
"Mediumspringgreen","00FA9A",
"Mediumturquoise","48D1CC",
"Mediumvioletred","C71585",
"Midnightblue","191970",
"Mintcream","F5FFFA",
"Mistyrose","FFE4E1",
"Moccasin","FFE4B5",
"Navajowhite","FFDEAD",
"Navy","000080",
"Navyblue","9FAFDF",
"Oldlace","FDF5E6",
"Olive","808000",
"Olivedrab","6B8E23",
"Orange","FFA500",
"Orangered","FF4500",
"Orchid","DA70D6",
"Palegoldenrod","EEE8AA",
"Palegreen","98FB98",
"Paleturquoise","AFEEEE",
"Palevioletred","DB7093",
"Papayawhip","FFEFD5",
"Peachpuff","FFDAB9",
"Peru","CD853F",
"Pink","FFC0CB",
"Plum","DDA0DD",
"Powderblue","B0E0E6",
"Purple","800080",
"Red","FF0000",
"Rosybrown","BC8F8F",
"Royalblue","4169E1",
"Saddlebrown","8B4513",
"Salmon","FA8072",
"Sandybrown","F4A460",
"Seagreen","2E8B57",
"Seashell","FFF5EE",
"Sienna","A0522D",
"Silver","C0C0C0",
"Skyblue","87CEEB",
"Slateblue","6A5ACD",
"Snow","FFFAFA",
"Springgreen","00FF7F",
"Steelblue","4682B4",
"Tan","D2B48C",
"Teal","008080",
"Thistle","D8BFD8",
"Tomato","FF6347",
"Turquoise","40E0D0",
"Violet","EE82EE",
"Wheat","F5DEB3",
"White","FFFFFF",
"Whitesmoke","F5F5F5",
"Yellow","FFFF00",
"Yellowgreen","9ACD32"};
}
Convert HSB to RGB value
import java.awt.Color;
public class Main {
public static void main() {
float hue = 12;
float saturation = 13;
float brightness = 14;
int rgb = Color.HSBtoRGB(hue, saturation, brightness);
int red = (rgb >> 16) & 0xFF;
int green = (rgb >> 8) & 0xFF;
int blue = rgb & 0xFF;
}
}
Convert RGB to HSB
import java.awt.Color;
public class Main {
public static void main() {
int red = 23;
int green = 66;
int blue = 99;
float[] hsb = Color.RGBtoHSB(red, green, blue, null);
float hue = hsb[0];
float saturation = hsb[1];
float brightness = hsb[2];
}
}
Image Color Effect: Brightness, Contrast, Negative
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.awt.image.ByteLookupTable;
import java.awt.image.LookupOp;
import java.awt.image.LookupTable;
import java.awt.image.ShortLookupTable;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
public class ColorApp extends JFrame {
DisplayPanel displayPanel;
JButton brightenButton, darkenButton, contrastIncButton, contrastDecButton,
reverseButton, resetButton;
public ColorApp() {
super();
Container container = getContentPane();
displayPanel = new DisplayPanel();
container.add(displayPanel);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
panel
.setBorder(new TitledBorder(
"Click a Button to Perform the Associated Operation and Reset..."));
brightenButton = new JButton("Brightness >>");
brightenButton.addActionListener(new ButtonListener());
darkenButton = new JButton("Darkness >>");
darkenButton.addActionListener(new ButtonListener());
contrastIncButton = new JButton("Contrast >>");
contrastIncButton.addActionListener(new ButtonListener());
contrastDecButton = new JButton("Contrast <<");
contrastDecButton.addActionListener(new ButtonListener());
reverseButton = new JButton("Negative");
reverseButton.addActionListener(new ButtonListener());
resetButton = new JButton("Reset");
resetButton.addActionListener(new ButtonListener());
panel.add(brightenButton);
panel.add(darkenButton);
panel.add(contrastIncButton);
panel.add(contrastDecButton);
panel.add(reverseButton);
panel.add(resetButton);
container.add(BorderLayout.SOUTH, panel);
addWindowListener(new WindowEventHandler());
setSize(displayPanel.getWidth(), displayPanel.getHeight() + 25);
show();
}
class WindowEventHandler extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
public static void main(String arg[]) {
new ColorApp();
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button.equals(brightenButton)) {
displayPanel.brightenLUT();
displayPanel.applyFilter();
displayPanel.repaint();
} else if (button.equals(darkenButton)) {
displayPanel.darkenLUT();
displayPanel.applyFilter();
displayPanel.repaint();
} else if (button.equals(contrastIncButton)) {
displayPanel.contrastIncLUT();
displayPanel.applyFilter();
displayPanel.repaint();
} else if (button.equals(contrastDecButton)) {
displayPanel.contrastDecLUT();
displayPanel.applyFilter();
displayPanel.repaint();
} else if (button.equals(reverseButton)) {
displayPanel.reverseLUT();
displayPanel.applyFilter();
displayPanel.repaint();
} else if (button.equals(resetButton)) {
displayPanel.reset();
displayPanel.repaint();
}
}
}
}
class DisplayPanel extends JPanel {
Image displayImage;
BufferedImage bi;
Graphics2D big;
LookupTable lookupTable;
DisplayPanel() {
setBackground(Color.black); // panel background color
loadImage();
setSize(displayImage.getWidth(this), displayImage.getWidth(this)); // panel
createBufferedImage();
}
public void loadImage() {
displayImage = Toolkit.getDefaultToolkit().getImage(
"largejexpLogo.jpg");
MediaTracker mt = new MediaTracker(this);
mt.addImage(displayImage, 1);
try {
mt.waitForAll();
} catch (Exception e) {
System.out.println("Exception while loading.");
}
if (displayImage.getWidth(this) == -1) {
System.out.println("No jpg file");
System.exit(0);
}
}
public void createBufferedImage() {
bi = new BufferedImage(displayImage.getWidth(this), displayImage
.getHeight(this), BufferedImage.TYPE_INT_ARGB);
big = bi.createGraphics();
big.drawImage(displayImage, 0, 0, this);
}
public void brightenLUT() {
short brighten[] = new short[256];
for (int i = 0; i < 256; i++) {
short pixelValue = (short) (i + 10);
if (pixelValue > 255)
pixelValue = 255;
else if (pixelValue < 0)
pixelValue = 0;
brighten[i] = pixelValue;
}
lookupTable = new ShortLookupTable(0, brighten);
}
public void darkenLUT() {
short brighten[] = new short[256];
for (int i = 0; i < 256; i++) {
short pixelValue = (short) (i - 10);
if (pixelValue > 255)
pixelValue = 255;
else if (pixelValue < 0)
pixelValue = 0;
brighten[i] = pixelValue;
}
lookupTable = new ShortLookupTable(0, brighten);
}
public void contrastIncLUT() {
short brighten[] = new short[256];
for (int i = 0; i < 256; i++) {
short pixelValue = (short) (i * 1.2);
if (pixelValue > 255)
pixelValue = 255;
else if (pixelValue < 0)
pixelValue = 0;
brighten[i] = pixelValue;
}
lookupTable = new ShortLookupTable(0, brighten);
}
public void contrastDecLUT() {
short brighten[] = new short[256];
for (int i = 0; i < 256; i++) {
short pixelValue = (short) (i / 1.2);
if (pixelValue > 255)
pixelValue = 255;
else if (pixelValue < 0)
pixelValue = 0;
brighten[i] = pixelValue;
}
lookupTable = new ShortLookupTable(0, brighten);
}
public void reverseLUT() {
byte reverse[] = new byte[256];
for (int i = 0; i < 256; i++) {
reverse[i] = (byte) (255 - i);
}
lookupTable = new ByteLookupTable(0, reverse);
}
public void reset() {
big.setColor(Color.black);
big.clearRect(0, 0, bi.getWidth(this), bi.getHeight(this));
big.drawImage(displayImage, 0, 0, this);
}
public void applyFilter() {
LookupOp lop = new LookupOp(lookupTable, null);
lop.filter(bi, bi);
}
public void update(Graphics g) {
g.clearRect(0, 0, getWidth(), getHeight());
paintComponent(g);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2D = (Graphics2D) g;
g2D.drawImage(bi, 0, 0, this);
}
}
IndexColorModel
import java.awt.Color;
import java.awt.image.ColorModel;
import java.awt.image.IndexColorModel;
public class IndexTest {
public static void main(String[] args) {
byte ff = (byte) 0xff;
byte[] r = { ff, 0, 0, ff, 0 };
byte[] g = { 0, ff, 0, ff, 0 };
byte[] b = { 0, 0, ff, ff, 0 };
ColorModel cm = new IndexColorModel(3, 5, r, g, b);
Color[] colors = { new Color(255, 0, 0), new Color(0, 255, 0),
new Color(0, 0, 255), new Color(64, 255, 64),
new Color(255, 255, 0), new Color(0, 255, 255) };
for (int i = 0; i < colors.length; i++) {
float[] normalizedComponents = colors[i].getComponents(null);
int[] unnormalizedComponents = cm.getUnnormalizedComponents(
normalizedComponents, 0, null, 0);
int rgb = colors[i].getRGB();
Object pixel = cm.getDataElements(rgb, null);
System.out.println(colors[i] + " -> " + ((byte[]) pixel)[0]);
}
for (byte i = 0; i < 5; i++) {
int[] unnormalizedComponents = cm.getComponents(i, null, 0);
System.out.print(i + " -> unnormalized components");
for (int j = 0; j < unnormalizedComponents.length; j++)
System.out.print(" " + unnormalizedComponents[j]);
System.out.println();
}
}
}
RGB Gray Filter
/*
* Copyright (c) 2001-2009 JGoodies Karsten Lentzsch. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* o Neither the name of JGoodies Karsten Lentzsch nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.awt.Image;
import java.awt.image.*;
import javax.swing.GrayFilter;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
/**
* An image filter that turns an icon into a grayscale icon. Used by
* the JGoodies Windows and Plastic L&Fs to create a disabled icon.<p>
*
* The high-resolution gray filter can be disabled globally using
* {@link Options#setHiResGrayFilterEnabled(boolean)}; it is enabled by default.
* The global setting can be overridden per component by setting
* the client property key {@link Options#HI_RES_DISABLED_ICON_CLIENT_KEY}
* to <code>Boolean.FALSE</code>.<p>
*
* Thanks to Andrej Golovnin for suggesting a simpler filter formula.
*
* @author Karsten Lentzsch
* @version $Revision: 1.10 $
*/
public final class RGBGrayFilter extends RGBImageFilter {
/**
* Overrides default constructor; prevents instantiation.
*/
private RGBGrayFilter() {
canFilterIndexColorModel = true;
}
/**
* Returns an icon with a disabled appearance. This method is used
* to generate a disabled icon when one has not been specified.
*
* @param component the component that will display the icon, may be null.
* @param icon the icon to generate disabled icon from.
* @return disabled icon, or null if a suitable icon can not be generated.
*/
public static Icon getDisabledIcon(JComponent component, Icon icon) {
if ( (icon == null)
|| (component == null)
|| (icon.getIconWidth() == 0)
|| (icon.getIconHeight() == 0)) {
return null;
}
Image img;
if (icon instanceof ImageIcon) {
img = ((ImageIcon) icon).getImage();
} else {
img = new BufferedImage(
icon.getIconWidth(),
icon.getIconHeight(),
BufferedImage.TYPE_INT_ARGB);
icon.paintIcon(component, img.getGraphics(), 0, 0);
}
ImageProducer producer =
new FilteredImageSource(img.getSource(), new RGBGrayFilter());
return new ImageIcon(component.createImage(producer));
}
/**
* Converts a single input pixel in the default RGB ColorModel to a single
* gray pixel.
*
* @param x the horizontal pixel coordinate
* @param y the vertical pixel coordinate
* @param rgb the integer pixel representation in the default RGB color model
* @return a gray pixel in the default RGB color model.
*
* @see ColorModel#getRGBdefault
* @see #filterRGBPixels
*/
public int filterRGB(int x, int y, int rgb) {
// Find the average of red, green, and blue.
float avg = (((rgb >> 16) & 0xff) / 255f +
((rgb >> 8) & 0xff) / 255f +
(rgb & 0xff) / 255f) / 3;
// Pull out the alpha channel.
float alpha = (((rgb >> 24) & 0xff) / 255f);
// Calculate the average.
// Sun"s formula: Math.min(1.0f, (1f - avg) / (100.0f / 35.0f) + avg);
// The following formula uses less operations and hence is faster.
avg = Math.min(1.0f, 0.35f + 0.65f * avg);
// Convert back into RGB.
return (int) (alpha * 255f) << 24 |
(int) (avg * 255f) << 16 |
(int) (avg * 255f) << 8 |
(int) (avg * 255f);
}
}