java读取图片写入图片 java获取图片
原创
©著作权归作者所有:来自51CTO博客作者误会一场的原创作品,请联系作者获取转载授权,否则将追究法律责任
Java获取网络图片
public class ImageRequest {
public static void main(String[] args) throws Exception{
URL url = new URL(
"http://a.hiphotos.baidu.com/image/pic/item/b3b7d0a20cf431adb35c8e304936acaf2edd9829.jpg");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inputStream = conn.getInputStream();//通过输入流获取图片数据
byte[] data = readInputStream(inputStream);//得到图片的二进制数据
File imageFile = new File("test.jpg");
FileOutputStream fileOutputStream = new FileOutputStream(imageFile);
fileOutputStream.write(data);
fileOutputStream.close();
}
public static byte[] readInputStream(InputStream inputStream) throws Exception {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);//写到内存
}
inputStream.close();
return outputStream.toByteArray();
}
}
本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。