ITeye博客

convert BufferedImage to byte[]

jiangtie · 2012-06-12 11:26 · JAVA · 编程语言 · Markdown

How to convert BufferedImage to byte in Java

Often times, you need to convert BufferedImage to byte array in order to store the image into database , or some other purpose. Some conversion is required as follow :


BufferedImage originalImage = ImageIO.read(new File("c:\\image\\mypic.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( originalImage, "jpg", baos );
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();

Example This class will load an image from “c:\image\mypic.jpg”, use ImageIO.write to write the BufferedImage into ByteArrayOutputStream object and convert it to byte array.


import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
 
public class ImageTest {
 
   public static void main(String [] args){
 
   try{
 
	BufferedImage originalImage = 
                              ImageIO.read(new File("c:\\image\\mypic.jpg"));
 
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	ImageIO.write( originalImage, "jpg", baos );
	baos.flush();
	byte[] imageInByte = baos.toByteArray();
	baos.close();
 
	}catch(IOException e){
		System.out.println(e.getMessage());
	}		
   }	
}


评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。