使用AffineTransform

时间:2017-05-10 10:11:37

标签: java graphics2d

我想用Java中的AffineTransform剪切我的图像。如果我这样做,我总是得到黑色的界限。

        for (File input : inputImages) {
        if (!input.getName().contains(".DS_Store")) {
            BufferedImage buffer = ImageIO.read(input);
            for (int i = 0; i <= 2; i++) {
                AffineTransform tx = new AffineTransform();
                tx.translate(buffer.getHeight() / 2, buffer.getWidth() / 2);
                tx.shear(0.3, 0);
                tx.translate(-buffer.getWidth() / 2, -buffer.getHeight() / 2);

                AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);

                BufferedImage newImage = new BufferedImage(buffer.getHeight(), buffer.getWidth(), buffer.getType());
                op.filter(buffer, newImage);

                File output = new File("output/" + FilenameUtils.getBaseName(input.getName()) + i + ".png");
                ImageIO.write(newImage, "png", output);
            }
        }
    }

是否有办法避免这些黑色边界并获得白色或透明背景?

1 个答案:

答案 0 :(得分:1)

使用BufferedImage.TYPE_INT_ARGB作为图像类型来创建透明图像

  

如果我使用TYPE_ARGB,我的输出图像是完全透明的

可以正常使用

Shared Transparent Image

BufferedImage buffer = ImageIO.read(...);
AffineTransform tx = new AffineTransform();
tx.translate(buffer.getHeight() / 2, buffer.getWidth() / 2);
tx.shear(0.3, 0);
tx.translate(-buffer.getWidth() / 2, -buffer.getHeight() / 2);

AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);

BufferedImage newImage = new BufferedImage(buffer.getHeight(), buffer.getWidth(), BufferedImage.TYPE_INT_ARGB);
op.filter(buffer, newImage);

JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(newImage)));

如果您愿意,可以使用默认颜色填充newImage