Java 字节数组流之图片转成字节数组

Java 字节数组流之图片转成字节数组,相当于图片的复制
在这里插入图片描述
字符串可以直接读取到字节数组中用(getBytes)

 
问题:将一张图片读到字节数组里面(所有的东西都能够读到字节数组里面)

思路:先使用文件输入流,通过程序做一个中转,程序在写出到字节数组中

还原图片的话:
将字节数组读取到程序中,程序在写出道文件中

以程序为中心

在这里插入图片描述
上面为比较清楚的图
上面为比较清楚的图

某某东西转成字节数组除了字符串其他都需要流来对接

文件流一定要释放资源

字节数组流不一定要释放资源

代码示例:

/*
 * 1、图片读取到字节数组中
 * 2、字节数组写出到文件(图片)
 */
public class IOTest09 {
	
	public static void main(String[] args) {
		// 图片转成字节数组
		byte[] datas = fileToByteArray("E:/gongfang/JavaDemo/linweimao/javaWork/Demo/IO_study02/src/com/lwm/io/p.pngp.png");
		System.out.println(datas.length);
		byteArrayToFile(datas, "p-byte.png");
	}
	/*
	 * 1、图片读取到字节数组中
	 * 	  1)、图片到程序		FileInputStream
	 *    2)、程序到字节数组   ByteArrayOutputStream
	 */
	public static byte[] fileToByteArray(String filePath) {
		// 1、创建源与目的地
		File src = new File(filePath);
		byte[] dest = null;
		// 2、选择流
		InputStream is = null;
		// 有新增方法不能发生多态
		ByteArrayOutputStream baos = null;
		try {
			is = new FileInputStream(src);
			baos = new ByteArrayOutputStream();
			// 3、操作(分段读取)
			byte[] flush = new byte[1024 * 10];// 缓冲容器
			int len = -1;// 接收长度
			try {
				while ((len = is.read(flush)) != -1) {
					// 写出到字节数组中
					baos.write(flush,0,len);
				}
				baos.flush();
				// 返回回来,上面调用时就有了
				return baos.toByteArray();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			// 4、释放资源
			try {
				if (null != is) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();

			}
		}
		return null;
	}
	
	/*
	 * 2、字节数组写出到文件(图片)
	 * 	  1)、字节数组读取到程序  ByteArrayInputStream
	 *    2)、程序到文件  FileOutputStream
	 */
	public static void byteArrayToFile(byte[] src,String filePath) {
		// 1、创建源
		File dest = new File(filePath);
		// 2、选择流
		InputStream is = null;
		OutputStream os = null;
		try {
			is = new ByteArrayInputStream(src);
			os = new FileOutputStream(dest);
			// 3、操作(分段读取)
			byte[] flush = new byte[5];// 缓冲容器
			int len = -1;// 接收长度
			while ((len = is.read(flush)) != -1) {
				os.write(flush,0,len);
			}
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 释放资源
			try {
				if (null != os) {
					os.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}
}
发布了45 篇原创文章 · 获赞 1 · 访问量 5231

猜你喜欢

转载自blog.csdn.net/weixin_42814000/article/details/104346216