java中图片和字节数组相互转化
方案一:使用ImageIO来实现
将图片转化为字节数组
/**
* 通过图片路径将图片文件转化为字符数组
*
* @param url 图片路径
* @return byte[]
*/
public static byte[] imageToBytes(String url){
ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
BufferedImage bufferedImage = null;
try {
bufferedImage = ImageIO.read(new File(url));
ImageIO.write(bufferedImage,"jpg",byteOutput);
return byteOutput.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (byteOutput != null)
byteOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
将图片的字节数组转化为图片
/**
* 将图片字节数组转化为图片,存放到指定路径
*
* @param bytes 图片字节数组
* @param 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();
}
}
}
这种方法虽然快捷方便,但是有一定的问题,使用ImageIO.read()方法会在生成图片时给图片背景蒙上一片红色,不过根据笔者发现背景是白色的图片会出现这种情况,暂时还未发现还有什么条件下发生这种问题。还有就是使用ImageIO.write()方法会造成图片质量的损耗,生成的图片清晰度会下降。
方案二:利用字节流来实现
将图片转化为字节数组
/**
* 通过图片路径将图片文件转化为字符数组
*
* @param url 图片路径
* @return byte[]
*/
public static byte[] ImageToBytes(String url){
FileImageInputStream input = null;
ByteArrayOutputStream output = null;
try {
input = new FileImageInputStream(new File(url));
output = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int numBytesRead = 0;
while ((numBytesRead = input.read(buf)) != -1) {
output.write(buf, 0, numBytesRead);
}
return output.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (input != null)
input.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (output != null)
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
将图片的字节数组转化为图片
/**
* 将图片字节数组转化为图片,存放到指定路径
*
* @param bytes 图片字节数组
* @param 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();
}
}
}
使用字节流来实现图片和字节数组的相互转化,就不会有方案一的问题了。不得不说,字节流yyds呀!