The setPixelColor
function below changes the color of pixels.
I need some suggestions to optimize this function.
Example:
public static void main(String[] args) throws IOException {
BufferedImage pic1 = ImageIO.read(new File("Images/Input-1.bmp"));
setPixelColor(pic1, 34, 177, 76, 127, 127, 127);
}
This changes the left image into the right image.
private static void setPixelColor(BufferedImage imgBuf, int red, int green, int blue, int newRed, int newGreen, int newBlue) throws IOException {
int[] RGBarray;
int w;
int h;
//Declare color arrays
int[][] alphaPixels;
int[][] redPixels;
int[][] greenPixels;
int[][] bluePixels;
w = imgBuf.getWidth();
h = imgBuf.getHeight();
alphaPixels = new int[h][w];
redPixels = new int[h][w];
greenPixels = new int[h][w];
bluePixels = new int[h][w];
RGBarray = imgBuf.getRGB(0, 0, w, h, null, 0, w);
//Bit shift values into arrays
int i = 0;
for (int row = 0; row < h; row++) {
for (int col = 0; col < w; col++) {
alphaPixels[row][col] = ((RGBarray[i] >> 24) & 0xff);
redPixels[row][col] = ((RGBarray[i] >> 16) & 0xff);
greenPixels[row][col] = ((RGBarray[i] >> 8) & 0xff);
bluePixels[row][col] = (RGBarray[i] & 0xff);
i++;
}
}
//Set the values back to integers using re-bit shifting
for (int row = 0; row < h; row++) {
for (int col = 0; col < w; col++) {
if (redPixels[row][col] == red && greenPixels[row][col] == green && bluePixels[row][col] == blue) {
int rgb = (alphaPixels[row][col] & 0xff) << 24 |
(redPixels[row][col] & newRed) << 16 |
(greenPixels[row][col] & newGreen) << 8 |
(bluePixels[row][col] & newBlue);
imgBuf.setRGB(col, row, rgb);
}
}
}
//Write back image
ImageIO.write(imgBuf, "bmp", new File("Images/Output2.bmp"));
}