2015-06-21 93 views
2

在以下代碼中,我試圖讀取灰度圖像,將像素值存儲在二維數組中,並用不同的名稱重寫圖像。 代碼是寫入灰度圖像時出錯

package dct; 

    import java.awt.image.BufferedImage; 
    import java.awt.image.DataBufferByte; 
    import java.awt.image.Raster; 
    import java.io.File; 
    import javax.imageio.ImageIO; 

    public class writeGrayScale 
    { 

     public static void main(String[] args) 
     { 
      File file = new File("lightning.jpg"); 
      BufferedImage img = null; 
      try 
      { 
       img = ImageIO.read(file); 
      } 
      catch(Exception e) 
      { 
       e.printStackTrace(); 
      } 

      int width = img.getWidth(); 
      int height = img.getHeight(); 
      int[][] arr = new int[width][height]; 

      Raster raster = img.getData(); 

      for (int i = 0; i < width; i++) 
      { 
       for (int j = 0; j < height; j++) 
       { 
        arr[i][j] = raster.getSample(i, j, 0); 
       } 
      } 

      BufferedImage image = new BufferedImage(256, 256, BufferedImage.TYPE_BYTE_GRAY); 
      byte[] raster1 = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); 
      System.arraycopy(arr,0,raster1,0,raster1.length); 
      // 
      BufferedImage image1 = image; 
      try 
      { 
       File ouptut = new File("grayscale.jpg"); 
       ImageIO.write(image1, "jpg", ouptut); 
      } 
      catch(Exception e) 
      { 
       e.printStackTrace(); 
      }  
     }// main 
    }// class 

對於此代碼,錯誤的是

Exception in thread "main" java.lang.ArrayStoreException 
at java.lang.System.arraycopy(Native Method) 
at dct.writeGrayScale.main(writeGrayScale.java:49) 
Java Result: 1 

如何消除這種錯誤寫的灰度圖像?

+1

你試圖從一個二維數組複製('INT [] [] arr')轉換成一維('字節[] raster1'),這可能是造成問題的原因。 –

+0

好的......我試着讓byte [] [] ..它的方法的語法錯誤看起來...任何幫助重寫語句「byte [] raster1 =((DataBufferByte)image.getRaster()。getDataBuffer ())。getData();「.. –

回答

1

我發現這個:「ArrayStoreException - 如果src數組中的元素由於類型不匹配而無法存儲到dest數組中。」 http://www.tutorialspoint.com/java/lang/system_arraycopy.htm

兩個想法:

  1. 你複製一個int數組到一個字節數組。
  2. 這不是例外的一部分,但是維度是正確的嗎? arr是一個二維數組,raster1是一維數組。

而且你不能只改變二維字節數組而忽略你調用的方法的輸出。

+0

你現在想改變什麼? –

+0

我強烈建議你重新考慮你想要做的事情。將值複製到raster1後,您甚至不再在代碼中使用raster1。因此,評論這兩行代碼甚至不會改變你的代碼的行爲。 – itmuckel

1

int[][] arr更改爲​​這樣。

byte[] arr = new byte[width * height * 4]; 
    for (int i = 0, z = 0; i < width; i++) { 
     for (int j = 0; j < height; j++, z += 4) { 
      int v = getSample(i, j, 0); 
      for (int k = 3; k >= 0; --k) { 
       arr[z + k] = (byte)(v & 0xff); 
       v >>= 8; 
      } 
     } 
    }