话不读说 直接上代码
1 package cn.kgc.ssm.common; 2 3 import java.io.*; 4 5 /** 6 * @author 7 * @create 2019-08-15 9:36 8 **/ 9 public class DDD { 10 /** 11 * 读取图片 返回一个图片的字节数组 12 * @param path 13 * @return 14 */ 15 public static byte[] imgArray(String path) { 16 //字节输入流 17 InputStream inputStream = null; 18 //字节缓冲流数组 19 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 20 try { 21 inputStream = new FileInputStream(path); 22 byte[] b = new byte[1024]; 23 int len = -1; 24 //循环读取 25 while ((len = inputStream.read(b)) != 1) { 26 byteArrayOutputStream.write(b, 0, len); 27 } 28 //返回byteArrayOutputStream数组 29 return byteArrayOutputStream.toByteArray(); 30 } catch (FileNotFoundException e) { 31 e.printStackTrace(); 32 } catch (IOException e) { 33 e.printStackTrace(); 34 } finally { 35 try { 36 //关闭流 37 inputStream.close(); 38 } catch (IOException e) { 39 e.printStackTrace(); 40 } 41 } 42 return null; 43 } 44 45 public static void writeImg(byte[]array,String path){ 46 //创建一个字节输出流 47 DataOutputStream dataOutputStream = null; 48 try { 49 dataOutputStream = new DataOutputStream(new FileOutputStream(path)); 50 //将字节数组 51 dataOutputStream.write(array); 52 } catch (IOException e) { 53 e.printStackTrace(); 54 }finally { 55 try { 56 //关闭 57 dataOutputStream.close(); 58 } catch (IOException e) { 59 e.printStackTrace(); 60 } 61 } 62 } 63 64 /** 65 * 读取二进制保存的图片 放到数组里 66 * @param path 67 * @return 68 */ 69 public static byte[] imageIn(String path){ 70 //创建一个字节输出流 71 DataInputStream dataInputStream = null; 72 try { 73 dataInputStream = new DataInputStream(new FileInputStream(path)); 74 //创建一个字节数组 byte的长度等于二进制图片的返回的实际字节数 75 byte[] b = new byte[dataInputStream.available()]; 76 //读取图片信息放入这个b数组 77 dataInputStream.read(b); 78 return b; 79 } catch (FileNotFoundException e) { 80 e.printStackTrace(); 81 } catch (IOException e) { 82 e.printStackTrace(); 83 }finally { 84 try { 85 //关闭流 86 dataInputStream.close(); 87 } catch (IOException e) { 88 e.printStackTrace(); 89 } 90 } 91 return null; 92 } 93 94 /** 95 * 读取二进制保存的图片 输出图片 96 * @param img 97 * @param path 98 */ 99 public static void writImg(byte[]img,String path){ 100 //创建一个字节输出流 101 OutputStream outputStream = null; 102 try { 103 outputStream = new FileOutputStream(path); 104 //将图片输处到流中 105 outputStream.write(img); 106 //刷新 107 outputStream.flush(); 108 } catch (FileNotFoundException e) { 109 e.printStackTrace(); 110 } catch (IOException e) { 111 e.printStackTrace(); 112 }finally { 113 try { 114 //关闭 115 outputStream.close(); 116 } catch (IOException e) { 117 e.printStackTrace(); 118 } 119 } 120 } 121 122 /** 123 * main方法 124 * @param args 125 */ 126 public static void main(String[] args) { 127 //获取图片 将图片信息把存到数组b中 128 byte[] b = DDD.imgArray("D:\5.JPG"); 129 //通过数组B写到文件中 130 DDD.writImg(b,"img.txt"); 131 //读取二进制文件保存到一个数组中 132 byte[] c = DDD.imageIn("img.txt"); 133 //通过数组c 输出图片 134 DDD.writImg(c,"img.jpg"); 135 } 136 }