2012-04-28 161 views
-1

Java中與C#PixelFormat's成員匹配的內容。.Net PixelFormat有Java相當於?

即Format24bppRgb與BufferedImage.TYPE_INT_RGB匹配嗎?

這是我的代碼。我得到了它有淨的的PixelFormat = Format32bppArgb 我創建的BufferedImage這樣一個形象:

 int sizeBytes = width * height; 
     DataBufferByte dataBuffer = new DataBufferByte(myImageBytes, sizeBytes); 

     WritableRaster raster = Raster.createInterleavedRaster(dataBuffer, // dataBuffer 
       width, // width 
       height, // height 
       width * 4, // scanlineStride 
       4, // pixelStride 
       new int[]{0, 1, 2, 3}, // bandOffsets 
       null); // location 

     java.awt.image.ColorModel colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), // ColorSpace 
       new int[]{8, 8, 8, 8}, // bits 
       true, // hasAlpha 
       false, // isPreMultiplied 
       ComponentColorModel.TRANSLUCENT, DataBuffer.TYPE_BYTE); 

     BufferedImage result = new BufferedImage(colorModel, raster, false, null); 

後,我創建一個BufferedImage,紅色和藍色在它交換。

接下來,我試圖創建一個圖片作爲跟隨

 BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); 
     WritableRaster r = result.getRaster(); 
     int[] pixels = byteToInt(bytes); 
     r.setPixels(0, 0, width, height , pixels); // ! Here an exception occures, because after I converted the byte array to int one the width becomes too long. 

字節數組用這種方法

private int[] byteToInt(byte[] pixels) { 
    int[] ints = new int[pixels.length/3]; 
    int byteIdx = 0; 
    for (int pixel = 0; pixel < ints.length; pixel++) { 
     int red = (int) pixels[byteIdx++] & 0xFF; 
     int green = (int) pixels[byteIdx++] & 0xFF; 
     int blue = (int) pixels[byteIdx++] & 0xFF; 
     int rgb = (red << 16) | (green << 8) | blue; 
     ints[pixel] = rgb; 
    } 
    return ints; 
} 

的顏色現在看起來不錯轉換,但我得到異常

java.lang.ArrayIndexOutOfBoundsException: 27600 
at sun.awt.image.ByteInterleavedRaster.setPixels(ByteInterleavedRaster.java:1106) 

如果我使用較小的寬度(例如寬度/ 3),顏色看起來不錯,但圖片本身縮小。

我在這個問題上停滯不前。任何幫助表示讚賞。謝謝。

+0

如果您的問題已經回答了,或者如果它不再有效,請勾選以選擇最合適的答案,以便每個人都知道問題已得到解決。謝謝。 – wattostudios 2012-05-14 13:39:06

回答

1

BufferedImage絕對是一個很好的開始。 PixelFormat中的許多值將與BufferedImage中的值匹配 - 它們各自具有24位和32位RGB/ARGB值,均具有5-5-5和5-6-5組合等等。

如果您遇到問題,請發佈一些代碼,我們會看看它,並嘗試提供幫助。我推薦的方法是在字節順序上(像素爲int s),直到獲得期望的結果 - 嘗試將BufferedImage繪製到JPanel等GUI對象上,以便看到它的外觀。

如果你有一個int數組[]爲你的像素值,這是代碼,我通常用來顯示數組爲圖像...

int[] pixels; 
ColorModel model = new DirectColorModel(32,0x00ff0000,0x0000ff00,0x000000ff,0xff000000); 
Image image = new JLabel().createImage(new MemoryImageSource(width,height,model,pixels,0,width)); 
+0

感謝您的回答。我用我的代碼更新了這篇文章。創建緩衝圖像後,紅色和藍色的顏色互換 – nixspirit 2012-04-28 11:03:22

+0

我肯定會建議你將'byte []'轉換爲'int []''的最新方法 - 這是我以前採用的方法,它的效果最好。我添加了通常用於生成圖像的代碼 - 可能會對您有所幫助。否則,我只是建議你的寬度和高度不太對。 – wattostudios 2012-04-29 03:03:17