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 testCreateLosslessFromImageCMYK() throws IOException
    {
        PDDocument document = new PDDocument();
        BufferedImage image = ImageIO.read(this.getClass().getResourceAsStream("png.png"));

        final ColorSpace targetCS = new ICC_ColorSpace(ICC_Profile
                .getInstance(this.getClass().getResourceAsStream("/org/apache/pdfbox/resources/icc/ISOcoated_v2_300_bas.icc")));
        ColorConvertOp op = new ColorConvertOp(image.getColorModel().getColorSpace(), targetCS, null);
        BufferedImage imageCMYK = op.filter(image, null);

        PDImageXObject ximage = LosslessFactory.createFromImage(document, imageCMYK);
        validate(ximage, 8, imageCMYK.getWidth(), imageCMYK.getHeight(), "png", "ICCBased");

        doWritePDF(document, ximage, TESTRESULTSDIR, "cmyk.pdf");
        
        // still slight difference of 1 color level
        //checkIdent(imageCMYK, ximage.getImage());
    }