arqam
arqam

Reputation: 3779

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.

If a simple solution from BufferedImage to BufferedImage conversion is given then that will be best, otherwise the problem is as follows :

Basically I have to convert BufferedImage into MAT format. It works properly for JPG/JPEG images but not PNGs. 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. So thus looking for a solution.

Thanks in advance.

Upvotes: 2

Views: 2897

Answers (2)

arqam
arqam

Reputation: 3779

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

Upvotes: 0

Coder ACJHP
Coder ACJHP

Reputation: 2194

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 :

enter image description here

The RGB worked for me with PNG.

Upvotes: 3

Related Questions