Java中如何将图片转字节数组呢?
下文笔者讲述将图片转字节数组的方法及示例分享,如下所示
图片转字节数组的实现思路
方式1: 使用ImageIO即可将图片转字节数组 方式2: 使用字节流的方式将图片转字节数组例:图片转字节数组
使用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 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;
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


