117.对接流:图片文件和字节流之间转换

废话少说,直接上测试代码

package cn.yzy.io;

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 pictureToByteArray {

	public static void main(String[] args) {
		//图片转为字节数组
		byte[] datas = fileToByteArray("whale.jpg");
		System.out.println(datas.length);
		//将字节数组写回图片文件
		byteArrayToFile(datas, "b2p.png");
	}
	
	//图片转为字节数组
	public static byte[] fileToByteArray(String filePath) {
		//创建源与目的地
		File src = new File(filePath);
		//选择流
		InputStream is = null;
		ByteArrayOutputStream baos = null;
		try {
			is = new FileInputStream(src);
			baos = new ByteArrayOutputStream();
			//分段读取
			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 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[5]; //缓冲容器
			int len = -1;
			while((len = is.read(flush)) != -1) {
				os.write(flush, 0, len);
			}
			os.flush();
		}catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}finally {
			//释放资源
			try {
				if(null != os)
					os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			try {
				if(null != is) {
					is.close();
				}
			}catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

可见以上代码正常的将whale.jpg图片转换为字节流,并且计算得大小是938872Bytes,再通过字节流可以正常转换为图片输出b2p.jpg:如下图:

其中发现如果将字节流转换为b2p.png就会出现图片损坏(图片->字节流->图片 前后图片格式要保持不变才能保证图片正常),如下图损坏:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值