当前位置:网站首页>实现图片的复制
实现图片的复制
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
边栏推荐
- IT industry salary has been far ahead! Ten years later, is the programmer still a high paying profession?
- 解决go get下载包失败问题
- 简明 VIM 练级攻略
- 200 programmers interview experience, all here
- 给大家介绍下,这是我的流程图软件 —— draw.io
- Process thread coroutine
- 【杂谈】JS相关的线程模型整理
- C/C++知识分享: 函数指针与指针函数,看完这篇你还能不懂?
- 解决IE、firefox浏览器下JS的new Date()的值为Invalid Date、NaN-NaN的问题
- MongoDB数据库
猜你喜欢
随机推荐
【杂谈】JS相关的线程模型整理
Looking for a small immutable dictionary with better performance
Wechat applet related
使用基于GAN的过采样技术提高非平衡COVID-19死亡率预测的模型准确性
进程 线程 协程
Countdownlatch explodes instantly! Based on AQS, why can cyclicbarrier be so popular?
趣文分享:C 语言和 C++、C# 的区别在什么地方?
Package subsystem in Simulink
接口测试工具Eolinker进行post请求
在Python中创建文字云或标签云
Creating a text cloud or label cloud in Python
【Elasticsearch 技术分享】—— 十张图带大家看懂 ES 原理 !明白为什么说:ES 是准实时的!
Swagger介绍和应用
Five design schemes of singleton mode
[cloud service] there are so many ECS instances on alicloud server, how to select the type? Best practice note
Regular backup of WordPress website program and database to qiniu cloud
An online accident caused by improper use of thread pool
Deep copy
RSA非对称加密算法
Array acquaintance