素材巴巴 > 程序开发 >

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

程序开发 2023-09-14 08:44:00

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

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就会出现图片损坏(图片->字节流->图片 前后图片格式要保持不变才能保证图片正常),如下图损坏:


标签:

上一篇: JAVA与前端如何进行交互? 下一篇:
素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。