我用Java先生成了一张图片,显然,这张图片是一个256*1灰度图像,颜色是从0到255每隔一像素增加1的
BufferedImage b=new BufferedImage(256,1,BufferedImage.TYPE_BYTE_GRAY);
for(int i=0;i<256;i++){
b.setRGB(i, 0, i*256*256+i*256+i);
}
try{
ImageIO.write(b, "BMP", new File("standard.bmp"));
}catch(Exception e){}
下面是用Java读取这张图片并得到颜色的代码
                for (int i = minx; i < width; i++) {
for (int j = miny; j < height; j++) {
int pixel = sourceImage.getRGB(i, j);
System.out.print(pixel+" ");
answer[i][j] = (pixel & 0xff);
System.out.println(pixel & 0xff);
}
}
由于输出太长,我只把最后一部分的输出拷过来:
-855310 242
-789517 243
-723724 244
-657931 245
-592138 246
-526345 247
-460552 248
-394759 249
-328966 250
-263173 251
-197380 252
-131587 253
-65794 254
-1 255
显然这个颜色值是依次递增的。
但是在看图软件上显示出来的颜色并不是这样,最后几个颜色是跳变的。为了验证,我用C#写了个程序读取生成的standard.bmp:
            Bitmap b = (Bitmap)Image.FromFile("standard.bmp");
            for (int i = 0; i < b.Width; i++)
            {
                Color c = b.GetPixel(i, 0);                
                Debug.WriteLine(c);
            }
但是结果(只有最后一部分)是
Color [A=255, R=233, G=233, B=233]
Color [A=255, R=235, G=235, B=235]
Color [A=255, R=237, G=237, B=237]
Color [A=255, R=239, G=239, B=239]
Color [A=255, R=242, G=242, B=242]
Color [A=255, R=244, G=244, B=244]
Color [A=255, R=246, G=246, B=246]
Color [A=255, R=248, G=248, B=248]
Color [A=255, R=250, G=250, B=250]
Color [A=255, R=253, G=253, B=253]
Color [A=255, R=255, G=255, B=255]
最后几个Color是跳变的,这个跟Fireworks和Photoshop看到的结果是一样的……
这是为什么?哪位大虾遇到过!谢了……

解决方案 »

  1.   

    把TYPE_BYTE_GRAY改成TYPE_INT_RGB试试
      

  2.   

    用TYPE_INT_RGB按你的赋值也是灰度图像把
      

  3.   

    你定义时用了TYPE_BYTE_GRAY(byte),赋值时用了setRGB(int)
      

  4.   

    那不用setRGB(int)用什么呢?
      

  5.   

    是 pixel & 0xffffff
    而不是 pixel & 0xff
      

  6.   

    RGB转灰度图应该由公式计算。
    b.setRGB(i, 0, i*256*256+i*256+i)是设置像素矩阵的RGB,改为直接设置灰度值,灰度值可以由RGB值计算得到。
    不同的RGB颜色空间,灰度值(也就是亮度值)的计算公式是不同滴~~
      

  7.   

    有转换系数的原因RGB值对应到亮度值,不是线性的。不同的颜色空间计算亮度值其伽玛值系数,R的系数,G的系数,B的系数是不同的。RGB依次加1递增,其像素的亮度值Y不会是按你的规律递增,就是这样的原因。
      

  8.   

    TYPE_BYTE_GRAY
    public static final int TYPE_BYTE_GRAY
    Represents a unsigned byte grayscale image, non-indexed. This image has a ComponentColorModel with a CS_GRAY ColorSpace. When data with non-opaque alpha is stored in an image of this type, the color data must be adjusted to a non-premultiplied form and the alpha discarded, as described in the AlphaComposite documentation. 
    用了这个就是有些转换的吧