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 testCreateLosslessFrom16BitPNG() throws IOException
    {
        PDDocument document = new PDDocument();
        BufferedImage image = ImageIO.read(new File("target/imgs", "PDFBOX-4184-16bit.png"));

        assertEquals(64, image.getColorModel().getPixelSize());
        assertEquals(Transparency.TRANSLUCENT, image.getColorModel().getTransparency());
        assertEquals(4, image.getRaster().getNumDataElements());
        assertEquals(java.awt.image.DataBuffer.TYPE_USHORT, image.getRaster().getDataBuffer().getDataType());

        PDImageXObject ximage = LosslessFactory.createFromImage(document, image);

        int w = image.getWidth();
        int h = image.getHeight();
        validate(ximage, 16, w, h, "png", PDDeviceRGB.INSTANCE.getName());
        checkIdent(image, ximage.getImage());
        checkIdentRGB(image, ximage.getOpaqueImage(null, 1));
        checkIdentRaw(image, ximage);

        assertNotNull(ximage.getSoftMask());
        validate(ximage.getSoftMask(), 16, w, h, "png", PDDeviceGray.INSTANCE.getName());
        assertEquals(35, colorCount(ximage.getSoftMask().getImage()));

        doWritePDF(document, ximage, TESTRESULTSDIR, "png16bit.pdf");
    }