实现 图片与byte 数组互相转换
作者:互联网
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
//图片文件,与 byte[] 互转
public class TestFile {
static byte[] bytes;
public static void main(String[] args) throws Exception {
File img = new File("W:\\img\\04.jpg");
fileToByte(img);
ByteToFile(bytes);
}
public static void fileToByte(File img) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
BufferedImage bi;
bi = ImageIO.read(img);
ImageIO.write(bi, "jpg", baos);
bytes = baos.toByteArray();
System.err.println(bytes.length);
} catch (Exception e) {
e.printStackTrace();
} finally {
baos.close();
}
}
static void ByteToFile(byte[] bytes)throws Exception{
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
BufferedImage bi1 =ImageIO.read(bais);
try {
File w2 = new File("W:\\img\\00000000003.jpg");//可以是jpg,png,gif格式
ImageIO.write(bi1, "jpg", w2);//不管输出什么格式图片,此处不需改动
} catch (IOException e) {
e.printStackTrace();
}finally{
bais.close();
}
}
}
标签:转换,File,img,ImageIO,bytes,jpg,数组,import,byte 来源: https://blog.csdn.net/LC_Liangchao/article/details/122601723