Java 更改图像的调色板

Java Change Color Palette of an Image

各位程序员大家好!

我是一个 Java 初学者,我有一个 Java 程序可以拍摄图像,显示未编辑的版本,将其转换为灰度并显示图像,并将不同的调色板应用到图像,然后显示它。虽然我无法将调色板应用于图像,但它会将整个图像更改为颜色。我怎样才能防止它改变整个图像的颜色和我指定区域的颜色?结果应该是这样的:

Results should be similar to this

请在任何代码中附上注释,以便我了解程序中发生的事情。

这是代码。谢谢你帮我!

import java.awt.*;

public class GrayscaleToColor
{
public static void main(String[] args)
{        

    Picture picture = new Picture("WashingtonMonument.jpg");
    picture.show();

    Picture picture2 = new Picture("WashingtonMonument.jpg");
    picture2.show();

    int redValue = 0; int greenValue = 0; int blueValue = 0;

    Pixel targetPixel = new Pixel(picture2, 0,0);
    Color pixelColor = null;

    for(int y=0; y < picture2.getHeight(); y++)
    {
        for(int x = 0; x < picture2.getWidth(); x++)
        {
            targetPixel = picture2.getPixel(x,y);
            pixelColor = targetPixel.getColor();

            redValue = pixelColor.getRed(); 
            greenValue = pixelColor.getGreen();
            blueValue = pixelColor.getBlue();

            redValue = greenValue = blueValue = (redValue + greenValue + blueValue) / 3;

            pixelColor = new Color(redValue, greenValue, blueValue);
            targetPixel.setColor(pixelColor);
        }
    }

    picture2.write("GrayWashingtonMonument.jpg");
    picture2.show();

    Picture picture3 = new Picture("WashingtonMonument.jpg");

    for(int y=0; y < picture3.getHeight(); y++)
    {
        for(int x = 0; x < picture3.getWidth(); x++)
        {
            targetPixel = picture3.getPixel(x,y);
            pixelColor = targetPixel.getColor();

            // It sets the colors, but it sets the color of the whole picture, not
            // the areas I want it to set in the picture.

            if(((redValue > 150) && greenValue > 150) && blueValue > 150)
            {
                blueValue = 130;
                greenValue = 17;
                redValue = 50;
            }
            else if(((redValue < 75) && greenValue < 75) && blueValue < 75)
            {
                redValue = 240;
                blueValue = 43;
                greenValue = 100;
            }
            else if(((redValue < 25) && greenValue < 25) && blueValue < 25)
            {
                redValue = 140;
                greenValue = 250;
                blueValue = 45;
            }

            pixelColor = new Color(redValue, greenValue, blueValue);
            targetPixel.setColor(pixelColor);
        }
    }

    picture3.write("ColorizedWashingtonMonument.jpg");
    picture3.show();

}
}

刚刚尝试编译您的代码 -- 收到很多关于引用 awt 包中不存在的东西的错误,例如: - 图片 - 像素

你想让这里的人帮你做作业吗?

无论如何,你需要复习javax.imageio -- 用于解析图像 http://docs.oracle.com/javase/8/docs/api/javax/imageio/package-summary.html