下面列出了怎么用javafx.scene.image.WritablePixelFormat的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public int[] getPixels(Image img, int x, int y, int w, int h)
{
int[] pixels = new int[w * h];
PixelReader reader = img.getPixelReader();
PixelFormat.Type type = reader.getPixelFormat().getType();
WritablePixelFormat<IntBuffer> format = null;
if(type == PixelFormat.Type.INT_ARGB_PRE)
{
format = PixelFormat.getIntArgbPreInstance();
}
else
{
format = PixelFormat.getIntArgbInstance();
}
reader.getPixels(x, y, w, h, format, pixels, 0, w);
return pixels;
}
/**
* Determine the appropriate {@link WritablePixelFormat} type that can be
* used to transfer data into the indicated BufferedImage.
*
* @param bimg
* the BufferedImage that will be used as a destination for a
* {@code PixelReader<IntBuffer>#getPixels()} operation.
* @return
*/
private static WritablePixelFormat<IntBuffer> getAssociatedPixelFormat(BufferedImage bimg) {
switch (bimg.getType()) {
// We lie here for xRGB, but we vetted that the src data was opaque
// so we can ignore the alpha. We use ArgbPre instead of Argb
// just to get a loop that does not have divides in it if the
// PixelReader happens to not know the data is opaque.
case BufferedImage.TYPE_INT_RGB:
case BufferedImage.TYPE_INT_ARGB_PRE:
return PixelFormat.getIntArgbPreInstance();
case BufferedImage.TYPE_INT_ARGB:
return PixelFormat.getIntArgbInstance();
default:
// Should not happen...
throw new InternalError("Failed to validate BufferedImage type");
}
}
/**
* Return OpenCV MAT in CvType.CV_8UC4
*/
public static Mat imageToMat(Image image) {
int width = (int) image.getWidth();
int height = (int) image.getHeight();
byte[] buffer = new byte[width * height * 4];
PixelReader reader = image.getPixelReader();
WritablePixelFormat<ByteBuffer> format = WritablePixelFormat.getByteBgraInstance();
reader.getPixels(0, 0, width, height, format, buffer, 0, width * 4);
Mat mat = new Mat(height, width, CvType.CV_8UC4);
mat.put(0, 0, buffer);
return mat;
}