将图片转换为字节流;将字节流转换为图片
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Dome07 {
public static void main(String[] args) {
byte[] b = FileToByteArray("o.jpg");
System.out.println(b.length);
byteArrayToFile(b,"copy-o.jpg");
}
private static void byteArrayToFile(byte[] b, String str) {
try( InputStream is = new ByteArrayInputStream(b);
OutputStream os = new FileOutputStream(str);) {
byte[] bt = new byte[1024];
int len = -1;
while((len = is.read(bt))!=-1){
os.write(bt);
}
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("resource")
private static byte[] FileToByteArray(String str) {
File f = new File(str);
try(InputStream is = new FileInputStream(f);
ByteArrayOutputStream bos = new ByteArrayOutputStream();) {
byte[] b = new byte[1024];
int len = -1;
while ((len = is.read(b))!= -1){
bos.write(b, 0, len);
}
bos.flush();
return bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}