2016-05-21 92 views
-1

我有一個數組int[] shadesOfGray大小n*n包含[0,255]中的值。是否有可能從這個數組中創建8位灰度位圖?從java中的[0,255]灰度值數組創建灰度位圖

例如,如果 int[] shadesOfGray = {255, 255, 255, 128, 128, 128, 0, 0, 0}

然後以位圖的對應像素的強度將是:

255 255 255 
128 128 128 
0 0 0 

我已經試過這樣的事情:

private static void generateBMPwithDistribution(int[] shadesOfGray, int sum, String path) throws IOException { 

     int dim = 100; 
     byte[] buffer = new byte[dim * dim];  

     for (int x = 0, i = 0; x < dim; x++)   
      for (int y = 0; y < dim; y++)            
       buffer[(x * dim) + y] = (byte) (shadesOfGray[i]); // problem 

     try { 
      ImageIO.write(getGrayscale(dim, buffer), "bmp", new File(path)); 
     } catch (IOException e) { 
      ... 
     } 

    } 

    public static BufferedImage getGrayscale(int width, byte[] buffer) { 
     int height = buffer.length/width; 
     ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY); 
     int[] nBits = { 8 }; 
     ColorModel cm = new ComponentColorModel(cs, nBits, false, true, 
       Transparency.OPAQUE, DataBuffer.TYPE_BYTE); 
     SampleModel sm = cm.createCompatibleSampleModel(width, height); 
     DataBufferByte db = new DataBufferByte(buffer, buffer.length); 
     WritableRaster raster = Raster.createWritableRaster(sm, db, null); 
     BufferedImage result = new BufferedImage(cm, raster, false, null); 

     return result; 
    } 

因爲我想8位.bmp,我在緩衝區中複製值,然後將緩衝區寫入文件。問題是值大於等於128;字節被認爲具有負值。 Java有沒有辦法克服這個問題?

+0

http://stackoverflow.com/questions/9609394/java-byte-array-contains-negative-numbers – Piglet

+0

謝謝,但問題依然存在;當我想打印具有例如強度值128的像素時,該值被解釋爲-128並且它是確定的。它是灰色的。但是,之後,我再次讀取圖像,這個像素值爲188,而不是128.這就是爲什麼我很困惑。 –

+0

你需要使用RGB - 任何其他模型可能會扭曲值 - 你在getGrayscale中得到了那個複雜的方案? – gpasch

回答

0

你的過程可以是這個樣子:

private static void generateBMPwithDistribution(int[] shadesOfGray, int sum, String path) throws IOException { 

    int dim1 = (int)Math.sqrt(shadesOfGray.length), dim=100*dim1; 
    int[] buffer = new int[dim * dim];  

    int howManyTimes=dim/dim1; 
    for (int x = 0; x < dim; x++)   
     for (int y = 0; y < dim; y++) {            
      int valueToReplicate=shadesOfGray[(x + y*dim)/howManyTimes]; 
      buffer[x + y*dim] = 0xff000000|(valueToReplicate<<16)|(valueToReplicate<<8)|valueToReplicate; 
     } 

    BufferedImage result=new BufferedImage(dim, dim, BufferedImage.TYPE_INT_RGB); 

    try { 
     ImageIO.write(result, "bmp", new File(path)); 
    } catch (IOException e) { 
     ... 
    } 

} 
+0

謝謝你,我理解了這個想法,並對其進行了一些修改,並最終奏效。再次感謝你! –

+0

問題是我總是隻設置一個顏色值,所以它總是_(something,0,0)_。 –