ByteArrayOutputStream baos = null;
try
{
URL u = new URL(strUrl);
BufferedImage image = ImageIO.read(u);
//convert BufferedImage to byte array
baos = new ByteArrayOutputStream();
ImageIO.write( image, "jpg", baos);
baos.flush();
return baos.toByteArray();
}
catch (Exception e)
{
}
finally
{
if(baos != null)
{
try {
baos.close();
} catch (IOException e) {
}
}
}
try
{
URL u = new URL(strUrl);
BufferedImage image = ImageIO.read(u);
//convert BufferedImage to byte array
baos = new ByteArrayOutputStream();
ImageIO.write( image, "jpg", baos);
baos.flush();
return baos.toByteArray();
}
catch (Exception e)
{
}
finally
{
if(baos != null)
{
try {
baos.close();
} catch (IOException e) {
}
}
}
本文详细介绍了如何使用Java从指定的URL获取图像,将其转换为BufferedImage,然后通过ByteArrayOutputStream将其保存为JPEG格式的字节数组。流程包括URL解析、图像读取、类型转换及输出到字节数组。最后确保资源关闭以避免内存泄漏。
1万+

被折叠的 条评论
为什么被折叠?



