Reputation: 1
How do I convert a javafx.scene.image.Image to a byte array in the format bgra?
I tried doing:
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
);
but it didn't work, my byte[] array buffer is still filled with zeros.
Upvotes: 4
Views: 2512
Reputation: 18415
The scanlineStride i. e. width must be multiplied by 4, i. e.
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
);
Upvotes: 3