将BufferedImage转为byte数组,在传输中,图片是不能直接传的,因此需要把图片变为字节数组,然后传输比较方便;只需要一般输出流的write方法即可;而字节数组变成BufferedImage能够还原图像。如何取得BufferedImage,如下:
BufferedImage image = ImageIO.read(new File( path ));
BufferedImage image = ImageIO.read( InputStream inputStream );
1.BufferedImage ---->byte[]
1.1 方法 : ImageIO.write(BufferedImage image,String format,OutputStream out);
参数image表示获得的BufferedImage;参数format表示图片的格式,比如“gif”等;
参数out表示输出流,如果要转成Byte数组,则输出流为ByteArrayOutputStream即可;
执行完后,只需要toByteArray()就能得到byte[];
1.2 例子:
BufferedImage imageNew= ImageIO.read(inputStream);
ByteArrayOutputStream outStream =new ByteArrayOutputStream();
ImageIO.write(imageNew, "JPEG", outStream);
//把outStream里的数据写入内存
return outStream.toByteArray() ;
2. byte[] ------>BufferedImage
//将b作为输入流;
ByteArrayInputStream in = new ByteArrayInputStream (byte[] b );
//将in作为输入流,读取图片存入image中,而这里in可以为ByteArrayInputStream();
BufferedImage image = ImageIO.read(InputStream in);