2015-12-22 51 views
0

我正在爲每個像素寫入值爲15的PNG圖像。當我讀取書面圖像時,我沒有收到垃圾值。爲什麼這樣? 由於我想恢復相同的值,我選擇了無損的PNG格式。我仍然得到垃圾價值。 這是代碼。爲什麼讀取PNG圖像時出現垃圾值

public static void main(String args[]) 
    { 
     BufferedImage img = new BufferedImage(512, 512, BufferedImage.TYPE_INT_RGB); 

     int[] RGBarray = null; 
     int col = 0; 
     int row = 0; 

     col = img.getWidth(); 
     row = img.getHeight(); 
     RGBarray = img.getRGB(0,0,col,row,null,0,col); // Now RGBarray has all the values 

     byte[] data = new byte[512*512]; 

     for(int k = 0; k < 262144; k++) 
     { 

       data[k] = 15; 

     } 

     int count = 0; 
     for(int ro = 0; ro < 512 ; ro++) 
     { 
      for(int co = 0;co < 512; co++) 
      { 
       img.setRGB(co, ro, data[count++]); 
      } 
     } 

     try{ 
       ImageIO.write(img, "png", new File("Test3.png")); 
      } 
     catch(Exception e) 
      { 
       e.printStackTrace(); 
      } 
    BufferedImage img1 = null; 

    File f = new File("Test3.png"); 
    try 
    { 
     img1 = ImageIO.read(f); 
    } 
    catch(Exception e) 
    { 
     e.printStackTrace(); 
    } 

     int[] RGBarray1 = null; 
     int col1 = 0; 
     int row1 = 0; 

     col1 = img1.getWidth(); 
     row1 = img1.getHeight(); 
     RGBarray1 = img1.getRGB(0,0,col1,row1,null,0,col1); // Now RGBarray has all the values 

     for(int p = 0; p < 5; p++) 
     { 
      for(int j = 0; j < 5 ; j++) 
      { 
       System.out.print(img1.getRGB(p,j) + "\t"); 
      } 
      System.out.println(""); 
     } 
    } 

僅供參考我打印了五個值來檢查我是否會得到15。但輸出 -16777216 -16777216 -16777216 -16777216 -16777216
-16777216 -16777216 -16777216 -16777216 -16777216
-16777216 -16777216 -16777216 -16777216 -16777216
-16777216 -16777216 -16777216 -16777216 - 16777216
-16777216 -16777216 -16777216 -16777216 -16777216

+0

你能把這個降到最小的例子嗎?例如不需要創建512x512字節的圖像,將它們複製到圖像中,然後提取5x5位;爲什麼不只是做一個1x1圖像,不創建'數據',然後看看1像素是否具有相同的「垃圾」值? –

回答

1

你寫了一個byte和閱讀int。試試這個吧 -

System.out.print((byte)img1.getRGB(p,j) + "\t"); 
+0

謝謝@TDG。有效。 –