当前位置:网站首页>实现图片的复制
实现图片的复制
2020-11-08 21:03:00 【8Years】
public class TestBytesInputStream {
public static void main(String[] args) {
//复制a.jpg图片
byte[] datas=fileToBytesArray("D:\\a.jpg");
byteArrayToFile(datas,"D:\\b.jpg");
}
//1.图片读取到字节数组中
// 1.图片到程序——FileInputStream
// 2.程序到字节数组——byteArrayOutputStream
public static byte[] fileToBytesArray(String path) {
//创建源头与目的地
File src = new File(path);
byte[] dest = null;
//选择流
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
//也可以使用 is = new BufferedInputStream(FileInputStream(src));
is = new FileInputStream(src);
//也可以使用baos = new BufferedOutputStream(teArrayOutputStream());
baos = new ByteArrayOutputStream();
//3.分段读取
byte[] flush = new byte[1024 * 10];//缓冲容器
int len = -1;
while ((len = is.read(flush)) != -1) {
baos.write(flush, 0, len);//写到字节数组中
}
baos.flush();
return baos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static void byteArrayToFile(byte[]src,String path){
File dest=new File(path);
InputStream is=null;
OutputStream os=null;
try {
is = new ByteArrayInputStream(src);
os = new FileOutputStream(dest);
byte[] flush = new byte[5];
int len = -1;
while ((len = is.read(flush)) != -1) {
os.write(flush, 0, len);
}
}catch (IOException e) {
e.printStackTrace();
} finally {
try{
if(os!=null){
os.close();
}
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
值得提醒的是,当is.read()没有传入参数的时候,复制的图片会无法打开,因为它只能一个字节一个字节地读,所以最好还是传入数组
提高性能的两个地方(1.缓冲容器的使用(相当于小卡车) 2.还可以使用字节缓冲流(相当于大卡车))
版权声明
本文为[8Years]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/4583813/blog/4708021
边栏推荐
- 使用Fastai开发和部署图像分类器应用
- Using GaN based oversampling technique to improve the accuracy of model for mortality prediction of unbalanced covid-19
- Array acquaintance
- PAT_甲级_1056 Mice and Rice
- Problem solving templates for subsequence problems in dynamic programming
- go语言参数传递到底是传值还是传引用?
- experiment
- Development and deployment of image classifier application with fastai
- Exercise 5
- Not a programmer, code can't be too ugly! The official writing standard of Python: pep8 everyone should know
猜你喜欢
随机推荐
experiment
Problem solving templates for subsequence problems in dynamic programming
CMS garbage collector
给大家介绍下,这是我的流程图软件 —— draw.io
使用Fastai开发和部署图像分类器应用
Creating a text cloud or label cloud in Python
C/C++知识分享: 函数指针与指针函数,看完这篇你还能不懂?
Programmers should know the URI, a comprehensive understanding of the article
在Python中创建文字云或标签云
进程 线程 协程
To introduce to you, this is my flow chart software—— draw.io
net.sf.json . jsonobject's format processing of time stamp
Iterm2 configuration and beautification
在Python中创建文字云或标签云
AI perfume is coming. Will you buy it?
SQL quick query
getBytes之 LengthFieldBasedFrameDecoder服务端解析
解决IE、firefox浏览器下JS的new Date()的值为Invalid Date、NaN-NaN的问题
JVM真香系列:轻松理解class文件到虚拟机(上)
都说程序员钱多空少,程序员真的忙到没时间回信息了吗?