sea said:
I have binary images in grayscale (shades of black and white) -- is
there some way I can convert this to a specific color? Thank you very
much for any help with this!
I am assuming you want to convert the file "testgrey.jpg" to the file
"testcolor.jpg". Before we start:
import java.awt.*;
import java.awt.image.*;
import java.io.*;
First, get an ImageFilter, as La'ie Techie suggested. You probably want
something like this:
public class MixerFilter extends RGBImageFilter
{
float ratioR, ratioG, ratioB;
public BlendingFilter(Color color)
{
ratioR = color.getRed() / 255f;
ratioG = color.getGreen() / 255f;
ratioB = color.getBlue() / 255f;
}
public int filterRGB(int x, int y, int rgb)
{
int
b = rgb & 0xff,
g = (rgb >>= 8) & 0xff,
r = (rgb >>= 8) & 0xff;
r = (int) Math.round(r * ratioR);
g = (int) Math.round(g * ratioG);
b = (int) Math.round(b * ratioB);
if (r < 0) r = 0; else if (r > 255) r = 255;
if (g < 0) g = 0; else if (g > 255) g = 255;
if (b < 0) b = 0; else if (b > 255) b = 255;
return (rgb & 0xff000000) + ((((r << 8) + g) << 8) + b);
}
}
Create an instance of this filter by supplying your 'specific color' to the
constructor. Name it "myFilter".
Then, create an instance of the source Image:
Image imSrc = Toolkit.getDefaultToolkit().createImage("testgrey.jpg");
Now, filter the Image:
Image imDst = Toolkit.getDefaultToolkit().createImage(new
FilteredImageSource(imSrc.getSource(), myFilter));
Normally, a RenderedImage is returned. Writing an Image can then be very
straightforward:
ImageIO.write((RenderedImage)imDst, "JPG", new File("testcolor.jpg"));
Now you have your filtered image! Enjoy!
Once you get the hang of it, you can create weird filters and then watch the
result on some images!