繁体   English   中英

如何将BufferedImage RGBA转换为BufferedImage RGB?

[英]How to convert BufferedImage RGBA to BufferedImage RGB?

因此,我尝试寻找解决方案,但找不到可以将RGBA转换为RGB格式的解决方案。

如果给出了从BufferedImage到BufferedImage转换的简单解决方案,那将是最好的,否则问题如下:

基本上我必须将BufferedImage转换为MAT格式。 它适用于JPG / JPEG图像,但不适用于PNG。 以下代码用于转换::

BufferedImage biImg = ImageIO.read(new File(imgSource));
            mat = new Mat(biImg.getHeight(), biImg.getWidth(),CvType.CV_8UC3); 
            Imgproc.cvtColor(mat,matBGR, Imgproc.COLOR_RGBA2BGR);
            byte[] data = ((DataBufferByte) biImg.getRaster().getDataBuffer()).getData();
            matBGR.put(0, 0, data);

这会对具有RGBA值的图像引发错误。 因此寻求解决方案。

提前致谢。

我找到了这样的解决方案:

BufferedImage oldRGBA= null;
    try {
        oldRGBA= ImageIO.read(new URL("http://yusufcakmak.com/wp-content/uploads/2015/01/java_ee.png"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    final int width = 1200;
    final int height = 800;
    BufferedImage newRGB = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    newRGB .createGraphics().drawImage(oldRGBA, 0, 0, width, height, null);
    try {
        ImageIO.write(newRGB , "PNG", new File("your path"));

    } catch (IOException e) {}

因此,在这里,当我们创建新的BufferedImage ,可以使用以下方式更改图像的类型:

在此处输入图片说明

RGB与PNG一起为我工作。

public static BufferedImage toBufferedImageOfType(BufferedImage original, int type) {
        if (original == null) {
            throw new IllegalArgumentException("original == null");
        }
        if (original.getType() == type) {
            return original;
        }
        BufferedImage image = new BufferedImage(original.getWidth(), original.getHeight(), type);
        Graphics2D g = image.createGraphics();
        try {
            g.setComposite(AlphaComposite.Src);
            g.drawImage(original, 0, 0, null);
        }
        finally {
            g.dispose();
        }
        return image;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM