Java で byte 型配列に格納した画像データの情報に対して、幅や高さを調べたり、少し手を加えたりする目的でいったん BufferedImage 型に変換したり、その逆の変換を行う機会があったので、その時の作業メモです。
byte 型配列から BufferedImage 型への変換
BufferedImage 型から byte 型配列への変換
byte 型配列から BufferedImage 型への変換は ImageIO クラスを使って一発でできますが、逆の BufferedImage 型から byte 型配列へはフォーマット(上記の場合だと PNG)を指定する必要がある、という点に注意です。
byte 型配列から BufferedImage 型への変換
byte[] img = new byte[];
:
(img にデータを格納する処理(省略))
:
try{
BufferedImage image = ImageIO.read( new ByteArrayInputStream( img ) );
:
}catch( Exception e ){
}
BufferedImage 型から byte 型配列への変換
byte[] img = new byte[];
BufferedImage image = null;
:
(image にデータを格納する処理(省略))
:
try{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
BufferedOutputStream os = new BufferedOutputStream( bos );
image.flush();
ImageIO.write( image, "png", os ); //. png 型
img = bos.toByteArray();
:
}catch( Exception e ){
}
byte 型配列から BufferedImage 型への変換は ImageIO クラスを使って一発でできますが、逆の BufferedImage 型から byte 型配列へはフォーマット(上記の場合だと PNG)を指定する必要がある、という点に注意です。
