たとえば、PNGのバイト配列に変換する例。
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
public class ImageBytes {
public static void main(String[] args) throws IOException {
BufferedImage image = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB);
byte[] b = getImageBytes(image, "png");
System.out.println(b.length);
}
/**
* 画像オブジェクトを指定した画像フォーマットのバイナリ表現に変換します。
* @param image 画像オブジェクト
* @param imageFormat 画像フォーマット
* @return バイナリ表現
*/
public static byte[] getImageBytes(BufferedImage image, String imageFormat) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
BufferedOutputStream os = new BufferedOutputStream(bos);
image.flush();
ImageIO.write(image, imageFormat, os);
os.flush();
os.close();
return bos.toByteArray();
}
}
tags: zlashdot Java Java
Posted by NI-Lab. (@nilab)