实现 图片与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();
        }
    } 
  
}
上一篇:ehcache2拾遗之copyOnRead,copyOnWrite


下一篇:【spring boot】15.spring boot项目 采用Druid数据库连接池,并启用druid监控功能