2015-08-15 71 views
4

如何將javafx.scene.image.Image轉換爲格式爲bgra的字節數組?如何使用PixelReader的getPixels()方法?

我試着這樣做:

PixelReader pixelReader = img.getPixelReader(); 
int width = (int)img.getWidth(); 
int height = (int)img.getHeight(); 
byte[] buffer = new byte[width * height * 4]; 
pixelReader.getPixels(
     0, 
     0, 
     width, 
     height, 
     PixelFormat.getByteBgraInstance(), 
     buffer, 
     0, 
     width 
); 

,但它沒有工作,我的byte []數組緩衝區仍用零填充。

回答

2

scanlineStride i。即寬度必須乘以4,即i。即

PixelReader pixelReader = img.getPixelReader(); 
int width = (int)img.getWidth(); 
int height = (int)img.getHeight(); 
byte[] buffer = new byte[width * height * 4]; 
pixelReader.getPixels(
     0, 
     0, 
     width, 
     height, 
     PixelFormat.getByteBgraInstance(), 
     buffer, 
     0, 
     width * 4 
); 
+0

好抓,但那不是問題,嘿。無論如何,我解決了它,並感謝您的意見。 – Pavel