将某些像素的RGB颜色转换为另一种颜色

时间:2016-10-04 01:51:09

标签: java image loops rgb pixel

  

编程语言:Java

我正在尝试将此图像的某些像素转换为不同的颜色以显示“秘密消息”。

Original Image

  

大多数像素是:

     

红色= 0,绿色= 64,蓝色= 0

     

我想要的像素更改为R = 255,G = 255,B = 255:

     

红色= 5,绿色= 64,蓝色= 5

import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.awt.Color;

public class ASSN2p2
{

  private static int makeRGBColor(int red, int green, int blue)
{
int rgb = 0;
rgb = red*65536 + green*256 + blue;
return rgb;
}
private static int getRed(int pixel)
{
return (pixel >> 16) & 0xFF;
}
private static int getGreen(int pixel)
{
return (pixel >> 8) & 0xFF;
}
private static int getBlue(int pixel)
{
return (pixel) & 0xFF;
}




  public static void main(String args[]) throws IOException
  {
   // int width = 300;
   // int height = 200;    
   BufferedImage image = null;
   File f = null;

    try
     {
       f = new File("D:\\2016-2017\\Fall2016\\201_CSCE_Programming\\Assignment 2\\secretmessage.png");
       image = ImageIO.read(f);
       image = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
       System.out.println("Reading Complete");
       BufferedImage output = new BufferedImage(image.getWidth(), image.getHeight(),BufferedImage.TYPE_INT_ARGB);

       //--------------------------------------


      //-------------------------------------------


for (int y = 0; y < image.getHeight(); y++)
{
 for (int x = 0; x < image.getWidth(); x++)
 {
int pixel = image.getRGB(x, y);
 int r,g,b;
 r = getRed(pixel);
 g = getGreen(pixel);
 b = getBlue(pixel);
if ((r == 5) && (g == 64) && (b == 5))
{
r = 64;
b = 64;
b = 64;
image.setRGB(x,y,makeRGBColor(r,g,b));
} }
}
     }
    catch(IOException e)
    {
      System.out.println("Error: "+e);
    }



       // printPixelARGB(pixel);
       // System.out.println("");







    try
    {
      f = new File("D:\\2016-2017\\Fall2016\\201_CSCE_Programming\\Assignment 2\\output.png");
      ImageIO.write(image, "png", f);
      System.out.println("Writing Complete");
    }
    catch(IOException e)
    {
      System.out.println("Error: "+e);
    }

  }
}

这产生了这个:

Output

我无法理解出了什么问题!

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

我相信你错过了新颜色的alpha分量。将您的代码更改为:

private static int makeRGBColor(int red, int green, int blue) {
  int rgb = 0xff000000 | (red << 16) | (green << 8) | blue;
  return rgb;
}

确保将alpha设置为full,否则您的图像将看起来完全透明。