Javaでbyte []をBufferedImageに変換する方法
byte[]
からBufferedImage
への変換には、次のようにInputStream
とImageIO.read
の使用が含まれます。
InputStream in = new ByteArrayInputStream(imageInByte); BufferedImage bImageFromConvert = ImageIO.read(in);
次の例では、「darksouls.jpg」という名前の画像ファイルを読み取り、バイト配列に変換してから、変換されたバイト配列を再利用し、新しいBufferedImage
に変換して、に保存します。新しい名前「new-darksouls.jpg」。
package com.example.image; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; public class ImageTest { public static void main(String[] args) { try { byte[] imageInByte; BufferedImage originalImage = ImageIO.read(new File( "c:/darksouls.jpg")); // convert BufferedImage to byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(originalImage, "jpg", baos); baos.flush(); imageInByte = baos.toByteArray(); baos.close(); // convert byte array back to BufferedImage InputStream in = new ByteArrayInputStream(imageInByte); BufferedImage bImageFromConvert = ImageIO.read(in); ImageIO.write(bImageFromConvert, "jpg", new File( "c:/new-darksouls.jpg")); } catch (IOException e) { System.out.println(e.getMessage()); } } }