如何将BufferedImage RGBA转换为BufferedImage RGB?

时间:2017-05-25 13:56:20

标签: java opencv

所以我尝试寻找解决方案,但找不到可以将<html> <body> <script> window.localStorage.setItem("sss", "test"); console.log(window.localStorage.getItem("sss")); </script> </body> </html> 转换为RGBA格式的解决方案。

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

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

MAT

这会对具有RGBA值的图像抛出错误。因此寻找解决方案。

提前致谢。

2 个答案:

答案 0 :(得分:2)

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

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时,我们可以使用以下内容更改图片类型

enter image description here

RGB使用PNG为我工作。

答案 1 :(得分:0)

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