2017-05-25 20 views
1

解決策を探してみましたが、RGBARGB形式に変換できる解決策が見つかりませんでした。BufferedImage RGBAをBufferedImage RGBに変換するには?

のBufferedImageへの変換のBufferedImageから、簡単な解決策が最善になるよう指定された場合、次のようにそれ以外の問題がある:

基本的に私はMAT形式にBufferedImageを変換する必要があります。 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値の画像では、このエラーが発生します。だから、解決策を探しています。

ありがとうございます。

+0

"これはRGBA値の画像ではエラーをスローします。"エラーは秘密ですか? |あなたはそのコードをちょっと詳しく説明できますか? 2行目では、biImgと同じサイズのマットを3チャンネル作成し、データは設定しません。次に、このブランクマットを4チャンネル(RGBA)から3チャンネル(BGR)に変換します。入力は3チャンネルなので、私はそれが不満の理由だと考えます。 |次に、 'biImg'のデータを結果の' Mat'にコピーします...最初はRGBAのデータではありませんでしたか? |そのコードは大変混乱しています... –

答えて

2

私はこのような解決策が見つかりました:そこでここでは、新しいBufferedImageを作成する際に、我々は、画像の種類を変更することができて

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

を:RGBはPNGと私のために働いた

enter image description here

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; 
    } 
関連する問題