简体   繁体   English

如何将BufferedImage RGBA转换为BufferedImage RGB?

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

So I tried looking for the solution but could not find a solution where I can convert the RGBA to RGB format. 因此,我尝试寻找解决方案,但找不到可以将RGBA转换为RGB格式的解决方案。

If a simple solution from BufferedImage to BufferedImage conversion is given then that will be best, otherwise the problem is as follows : 如果给出了从BufferedImage到BufferedImage转换的简单解决方案,那将是最好的,否则问题如下:

Basically I have to convert BufferedImage into MAT format. 基本上我必须将BufferedImage转换为MAT格式。 It works properly for JPG/JPEG images but not PNGs. 它适用于JPG / JPEG图像,但不适用于PNG。 Following code I use for the conversion :: 以下代码用于转换::

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);

This throws error for images with RGBA values. 这会对具有RGBA值的图像引发错误。 So thus looking for a solution. 因此寻求解决方案。

Thanks in advance. 提前致谢。

I found a solution like this : 我找到了这样的解决方案:

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) {}

So here when we creating new BufferedImage we can change type of the image with : 因此,在这里,当我们创建新的BufferedImage ,可以使用以下方式更改图像的类型:

在此处输入图片说明

The RGB worked for me with PNG. 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