01: /*
02: * @(#)MaskFilter.java
03: *
04: * Copyright 2002-2003 JIDE Software Inc. All rights reserved.
05: */
06: package com.jidesoft.icons;
07:
08: import java.awt.*;
09: import java.awt.image.FilteredImageSource;
10: import java.awt.image.ImageProducer;
11: import java.awt.image.RGBImageFilter;
12:
13: /**
14: * An image filter that will replace one color in an image
15: * with another color.
16: */
17: public class MaskFilter extends RGBImageFilter {
18: private Color _newColor;
19: private Color _oldColor;
20:
21: private static MaskFilter _maskFilter = null;
22:
23: public static MaskFilter getInstance(Color oldColor, Color newColor) {
24: if (_maskFilter == null) {
25: _maskFilter = new MaskFilter(oldColor, newColor);
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,
45: Color newColor) {
46: MaskFilter filter = MaskFilter.getInstance(oldColor, newColor);
47: ImageProducer prod = new FilteredImageSource(i.getSource(),
48: filter);
49: Image image = Toolkit.getDefaultToolkit().createImage(prod);
50: return image;
51: }
52:
53: /**
54: * Creates an image as negative of an existing one. It will
55: * basically replace the black color with white color.
56: */
57: public static Image createNegativeImage(Image i) {
58: return createImage(i, Color.black, Color.white);
59: }
60:
61: /**
62: * Constructs a MaskFilter object that filters color of image to another color
63: *
64: * @param oldColor old color in exist image that needs to be replaced by new color
65: * @param newColor new color to replace the old color
66: * @deprecated use getInstance instead to reuse the same instance
67: */
68: public MaskFilter(Color oldColor, Color newColor) {
69: _newColor = newColor;
70: _oldColor = oldColor;
71: canFilterIndexColorModel = true;
72: }
73:
74: /**
75: * Overrides <code>RGBImageFilter.filterRGB</code>.
76: */
77: @Override
78: public int filterRGB(int x, int y, int rgb) {
79: if (_newColor != null && _oldColor != null) {
80: if (rgb == _oldColor.getRGB()) {
81: return _newColor.getRGB();
82: }
83: }
84: return rgb;
85: }
86: }
|