| 1 |
/* |
| 2 |
* @(#)MaskFilter.java |
| 3 |
* |
| 4 |
* Copyright 2002-2003 JIDE Software Inc. All rights reserved. |
| 5 |
*/ |
| 6 |
package com.jidesoft.icons; |
| 7 |
|
| 8 |
import java.awt.*; |
| 9 |
import java.awt.image.FilteredImageSource; |
| 10 |
import java.awt.image.ImageProducer; |
| 11 |
import java.awt.image.RGBImageFilter; |
| 12 |
|
| 13 |
/** |
| 14 |
* An image filter that replaces one color in an image with another color. |
| 15 |
*/ |
| 16 |
public class MaskFilter extends RGBImageFilter { |
| 17 |
private Color _newColor; |
| 18 |
private Color _oldColor; |
| 19 |
|
| 20 |
private static MaskFilter _maskFilter = null; |
| 21 |
|
| 22 |
public static MaskFilter getInstance(Color oldColor, Color newColor) { |
| 23 |
if (_maskFilter == null) { |
| 24 |
_maskFilter = new MaskFilter(oldColor, newColor); |
| 25 |
} |
| 26 |
else { |
| 27 |
_maskFilter.setOldColor(oldColor); |
| 28 |
_maskFilter.setNewColor(newColor); |
| 29 |
} |
| 30 |
return _maskFilter; |
| 31 |
} |
| 32 |
|
| 33 |
private void setNewColor(Color newColor) { |
| 34 |
_newColor = newColor; |
| 35 |
} |
| 36 |
|
| 37 |
private void setOldColor(Color oldColor) { |
| 38 |
_oldColor = oldColor; |
| 39 |
} |
| 40 |
|
| 41 |
/** |
| 42 |
* Creates an image from an existing one by replacing the old color with the new color. |
| 43 |
*/ |
| 44 |
public static Image createImage(Image i, Color oldColor, Color newColor) { |
| 45 |
MaskFilter filter = MaskFilter.getInstance(oldColor, newColor); |
| 46 |
ImageProducer prod = new FilteredImageSource(i.getSource(), filter); |
| 47 |
Image image = Toolkit.getDefaultToolkit().createImage(prod); |
| 48 |
return image; |
| 49 |
} |
| 50 |
|
| 51 |
/** |
| 52 |
* Creates an image as negative of an existing one. It will basically replace the black color with white color. |
| 53 |
*/ |
| 54 |
public static Image createNegativeImage(Image i) { |
| 55 |
return createImage(i, Color.black, Color.white); |
| 56 |
} |
| 57 |
|
| 58 |
/** |
| 59 |
* Constructs a MaskFilter object that filters color of image to another color Please note, you can also use {@link |
| 60 |
* #getInstance(java.awt.Color, java.awt.Color)} to reuse the same instance of MaskFilter. |
| 61 |
* |
| 62 |
* @param oldColor old color in exist image that needs to be replaced by new color |
| 63 |
* @param newColor new color to replace the old color |
| 64 |
*/ |
| 65 |
public MaskFilter(Color oldColor, Color newColor) { |
| 66 |
_newColor = newColor; |
| 67 |
_oldColor = oldColor; |
| 68 |
canFilterIndexColorModel = true; |
| 69 |
} |
| 70 |
|
| 71 |
/** |
| 72 |
* Overrides <code>RGBImageFilter.filterRGB</code>. |
| 73 |
*/ |
| 74 |
@Override |
| 75 |
public int filterRGB(int x, int y, int rgb) { |
| 76 |
if (_newColor != null && _oldColor != null) { |
| 77 |
if (rgb == _oldColor.getRGB()) { |
| 78 |
return _newColor.getRGB(); |
| 79 |
} |
| 80 |
} |
| 81 |
return rgb; |
| 82 |
} |
| 83 |
} |
| 84 |
|