如何使图像成为 itext 中合格的蒙版候选者?

How to make an image a qualified mask candidate in itext?

我打算使用另一张本地图片遮盖图片,例如 A.jpg B.jpgitext 中,首先我尝试直接将 imageB 设为遮罩,但我得到了 DocumentException: This image cannot be an image mask,所以我尝试 B.jpg a rawimage 这是我的代码:

RandomAccessFile rf = new RandomAccessFile("B.jpg", "rw");
        int size = (int)rf.length();
        byte imagedata[] = new byte[size];
        rf.readFully(data);
        rf.close();
Image mask = Image.getInstance("B.jpg");
        int w =(int) Math.ceil(mask.getWidth());
        int h =(int) Math.ceil(mask.getHeight()); 
mask = Image.getInstance(w,h,1,1,data); 
mask.makemask();

我从 B.jpg 得到了 byte[] 数据并尝试重建 B.jpg,但它不起作用我无法获得正确的图像,那么我怎样才能使图像成为合格的图像蒙版?有没有其他方法可以从itext中的另一个图像中蒙版图像?看起来像如何裁剪图像,但遮罩清晰度可能非常复杂,不仅可以使用 ContentByte 绘制矩形或圆形。

图像遮罩必须是单色或灰度,彩色不行。

请看一下MakeJpgMask example. In this example, I took two normal JPG files and I used one as mask for the other, resulting in a rather spooky PDF: jpg_mask.pdf

为此,我需要将一张彩色 JPEG 图像更改为黑白图像:

public void createPdf(String dest) throws IOException, DocumentException {
    Document document = new Document(PageSize.A4.rotate());
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();
    Image image = Image.getInstance(IMAGE);
    Image mask = makeBlackAndWhitePng(MASK);
    mask.makeMask();
    image.setImageMask(mask);
    image.scaleAbsolute(PageSize.A4.rotate());
    image.setAbsolutePosition(0, 0);
    document.add(image);
    document.close();
}

public static Image makeBlackAndWhitePng(String image) throws IOException, DocumentException {
    BufferedImage bi = ImageIO.read(new File(image));
    BufferedImage newBi = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_USHORT_GRAY);
    newBi.getGraphics().drawImage(bi, 0, 0, null);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(newBi, "png", baos);
    return Image.getInstance(baos.toByteArray());
}

如您所见,我们已将 berlin2013.jpg 转换为黑白图像,并将其用作彩色 javaone2013.jpg 图像的遮罩。