如何使用Java实现图片文件转化成字节数组,再将字节数组转化成文件(程序作为中转)
1、图片读取到字节数组中
图片--->程序:FileInputStream
程序--->字节数组:ByteArrayOutputStream
public static byte[] fileToByteArray(String filePath) {
//1.创建源yu目的地
File file = new File(filePath);
byte[] ds = null;
//选择流
InputStream zp = null;
ByteArrayOutputStream boos = null;
boos = new ByteArrayOutputStream();
try {
zp = new FileInputStream(file);
byte[] frush = new byte[1024];//1024表示1k为一段
int len = -1;
while((len=zp.read(frush))!=-1) {
boos.write(frush,0,len);//写出到字节数组中
}
boos.flush();
return boos.toByteArray();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(zp!=null) {
try {
zp.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
2.字节数组写出到图片
字节数组到程序 ByteArrayInputStream
程序到文件 FileOutStream
public static void byteArrayToFile(byte[] src,String filePath) {
//1.创建源
File file = new File(filePath);
//选择流
InputStream writing = null;
OutputStream os = null;
try {
writing = new ByteArrayInputStream(src);
os = new FileOutputStream(file);
byte[] frush = new byte[5];//3表示0个字节为一段
int len = -1;
while((len=writing.read(frush))!=-1) {
os.write(frush,0,len);
}
os.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(os!=null) {
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
主程序
/**
*1、图片 读取到字节数组中
*2、字节数组写出到文件
* @author 张培
*
*/
public static void main(String[] args) {
byte[] datas = fileToByteArray("desk.jpg");
System.out.println(datas.length);
byteArrayToFile(datas,"deskByte.jpg");
}