Java中如何将字节数组转换为图片呢?
下文笔者讲述将字节数组转图片的方法及示例分享,如下所示
字节数组转图片的实现思路
方式1:
使用ImageIO
即可将字节数组写入到文件流中
然后就转换为图片文件
方式2:
使用FileImageOutputStream将字节数组写入
并转换为图片文件
笔者推荐大家使用“方式2”,因为我们对流的操作非常熟悉
例:字节数组转图片
使用ImageIO的方式将字节数组转换为图片文件
//bytes:字节数组
//url:待写入的图片文件路径
public static void bytesToImage(byte[] bytes, String url){
ByteArrayInputStream byteInput = new ByteArrayInputStream(bytes);
BufferedImage bufferedImage = null;
try {
bufferedImage = ImageIO.read(byteInput);
File file = new File(url);//可以是jpg,png,gif格式
ImageIO.write(bufferedImage, "jpg", file);//不管输出什么格式图片,此处不需改动
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if (byteInput != null)
byteInput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用字节流的方式将字节数组转换为图片文件
//bytes:字节数组
//url:待写入的图片文件路径
public static void BytesToImage(byte[] bytes, String url){
FileImageOutputStream imageOutput = null;//打开输入流
try {
imageOutput = new FileImageOutputStream(new File(url));
imageOutput.write(bytes, 0, bytes.length);//将byte写入硬盘
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (imageOutput != null)
imageOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


