将一张图片读入字节数组在将其还原为图片
因为图片不能直接读入直接数组当中,所以要先使用文件输入流在由将其变成字节在放入数组
图片转成字节数组
/**
* 定义图片到字节数组中的方法
* 形参为图片路径
* 1、图片到程序 FileInputStream
* 2、程序到字节数组 ByteArrayOutputStream
* 这样会保存在内存当中
*/
public static byte[] fileToByteArray(String filePath){
//创建源文件与目的路径
File src = new File(filePath);
byte[] dest = null;
//选择流--->由新增方法不能发生多态
InputStream is = null;
ByteArrayOutputStream baos = null;
/*进行文件操作*/
try {
is = new FileInputStream(src);
baos = new ByteArrayOutputStream();
//创建字节数组缓存区
byte[] flush = new byte[1024*10]; //10K
//每次读取的字节数量
int temp = -1;
//开始读取操作
while ((temp=is.read(flush))!=-1){
baos.write(flush, 0, temp); //写出到字节数组中
}
baos.flush();
//返回数据
return baos.toByteArray();
}catch (FileNotFoundException e){
System.out.println(e.getMessage());
e.printStackTrace();
}catch (IOException e){
System.out.println(e.getMessage());
e.printStackTrace();
}finally {
//关闭资源
try {
if (null!=is){
is.close();
}
}catch (Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
return null;
}
字节输出转输出成图片
/**
* 字节数组写出到图片
* 形参是字节数组和文件路径
* 1、字节数组读取到程序中 ByteArrayInputStream
* 2、程序写出到文件 FileOutputStream
*/
public static void byteArrayToFile(byte[] src, String filePath){
//文件源路径
File dest = new File(filePath);
//因为已经有了文件源路径所以直接进行选择流
InputStream is = null;
//需要进行文件输出
OutputStream os = null;
/*进行文件操作*/
try {
is = new ByteArrayInputStream(src);
os = new FileOutputStream(dest);
//进行分段读取操作
byte[] flush = new byte[1024*50]; //图片大小有50k,为了保证一次性读完所以一次性读取50k
int temp = -1;
while ((temp=is.read(flush))!=-1){
//分段读取写出
os.write(flush, 0, temp); //注意形参--->write的形参最后一个是文件实际的长度,可能比字节数组要长或者要短
}
//刷新文件
os.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
//释放文件流
try {
if (null!=os){
os.close();
}
}catch (IOException e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
这一切东西的本质就是流与流之间的对接,除了字符串,其他的都使用字节来进行对接--->很类似与文件的拷贝--->将文件或者任何东西转成字节然后再写出(一切的中心都是程序)