package imageView;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 从网络获取图片到本地
*/
public class GetImage {
/**
* 测试
*
* @param args
*/
public static void main(String[] args) {
String url = "http://www.iteye.com/upload/logo/user/1134656/d44c2b36-9869-360a-9c87-e88eaf8db3a5.jpg";
byte[] btImg = getImageFromNetByUrl(url);
if (null != btImg && btImg.length > 0) {
System.out.println("读取到:" + btImg.length + "字节");
String fileName = "abc.jpg";
writeImageToDisk(btImg, fileName);
} else {
System.out.println("没有从该连接获得内容");
}
}
/**
* 从输入流中获取数据
*
* @param inStream
* 输入流
* @return ByteArray
* @throws Exception
*/
public static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// 设置数据缓冲区
byte[] buffer = new byte[1024 * 2];
// 读取到数据的长度
int len;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
outStream.close();
inStream.close();
return outStream.toByteArray();
}
/**
* 根据地址获得数据的字节流
*
* @param strUrl
* 网络连接地址
* @return
*/
public static byte[] getImageFromNetByUrl(String strUrl) {
try {
URL url = new URL(strUrl);
// 处理以http开头的地址
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(10 * 1000);// 设置链接超时时间为10s
InputStream inStream = conn.getInputStream();// 通过输入流获取图片数据
byte[] btImg = readInputStream(inStream);// 得到图片的二进制数据
inStream.close();
return btImg;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
/**
* 将图片写入到磁盘
*
* @param img
* 图片数据流
* @param fileName
* 文件保存时的名称
*/
public static void writeImageToDisk(byte[] img, String fileName) {
try {
File file = new File("E:\\" + fileName);
FileOutputStream fops = new FileOutputStream(file);
fops.write(img);
fops.flush();
fops.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
Java保存网络图片到本地图片损毁
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-