public static PDImageXObject createFromImage(PDDocument document, BufferedImage image)
            throws IOException
    {
        if (isGrayImage(image))
        {
            return createFromGrayImage(image, document);
        }

        // We try to encode the image with predictor
        if (USE_PREDICTOR_ENCODER)
        {
            PDImageXObject pdImageXObject = new PredictorEncoder(document, image).encode();
            if (pdImageXObject != null)
            {
                if (pdImageXObject.getColorSpace() == PDDeviceRGB.INSTANCE &&
                    pdImageXObject.getBitsPerComponent() < 16 &&
                    image.getWidth() * image.getHeight() <= 50 * 50)
                {
                    // also create classic compressed image, compare sizes
                    PDImageXObject pdImageXObjectClassic = createFromRGBImage(image, document);
                    if (pdImageXObjectClassic.getCOSObject().getLength() < 
                        pdImageXObject.getCOSObject().getLength())
                    {
                        pdImageXObject.getCOSObject().close();
                        return pdImageXObjectClassic;
                    }
                    else
                    {
                        pdImageXObjectClassic.getCOSObject().close();
                    }
                }
                return pdImageXObject;
            }
        }

        // Fallback: We export the image as 8-bit sRGB and might lose color information
        return createFromRGBImage(image, document);
    }
@Test
    void testCreateLosslessFrom16Bit() throws IOException
    {
        PDDocument document = new PDDocument();
        BufferedImage image = ImageIO.read(this.getClass().getResourceAsStream("png.png"));

        ColorSpace targetCS = ColorSpace.getInstance(ColorSpace.CS_sRGB);
        int dataBufferType = DataBuffer.TYPE_USHORT;
        final ColorModel colorModel = new ComponentColorModel(targetCS, false, false,
                ColorModel.OPAQUE, dataBufferType);
        WritableRaster targetRaster = Raster.createInterleavedRaster(dataBufferType, image.getWidth(), image.getHeight(),
                targetCS.getNumComponents(), new Point(0, 0));
        BufferedImage img16Bit = new BufferedImage(colorModel, targetRaster, false,
                new Hashtable<>());
        ColorConvertOp op = new ColorConvertOp(image.getColorModel().getColorSpace(), targetCS, null);
        op.filter(image, img16Bit);

        PDImageXObject ximage = LosslessFactory.createFromImage(document, img16Bit);
        validate(ximage, 16, img16Bit.getWidth(), img16Bit.getHeight(), "png", PDDeviceRGB.INSTANCE.getName());
        checkIdent(image, ximage.getImage());
        doWritePDF(document, ximage, TESTRESULTSDIR, "misc-16bit.pdf");
    }