Java更改图像的调色板

时间:2016-07-16 15:56:40

标签: java image if-statement for-loop getpixel

Hello其他程序员!

我是一名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();

}
}

1 个答案:

答案 0 :(得分:0)

只是试图编译你的代码 - 收到许多关于引用a​​wt包中不存在的东西的错误,例如: - 图片 - 像素

你是不是想让这里的人为你做功课?

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