package com.cloud.common.utils;
|
|
|
import org.apache.commons.io.IOUtils;
|
import org.springframework.http.HttpStatus;
|
|
import java.io.FileOutputStream;
|
import java.io.IOException;
|
import java.io.InputStream;
|
import java.net.HttpURLConnection;
|
import java.net.URL;
|
|
/**
|
* @author lp
|
* @date 2018-08-05
|
*/
|
public class ReadUrlImg {
|
|
public static InputStream getInputStream(String imgUrl) {
|
InputStream inputStream = null;
|
HttpURLConnection httpURLConnection = null;
|
try {
|
URL url = new URL(imgUrl);
|
if (url != null) {
|
httpURLConnection = (HttpURLConnection) url.openConnection();
|
httpURLConnection.setConnectTimeout(3000);
|
httpURLConnection.setRequestMethod("GET");
|
int responseCode = httpURLConnection.getResponseCode();
|
if (responseCode == HttpStatus.OK.value()) {
|
inputStream = httpURLConnection.getInputStream();
|
}
|
}
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
return inputStream;
|
|
}
|
|
public static void saveImage() {
|
InputStream inputStream = getInputStream("");
|
FileOutputStream fileOutputStream = null;
|
byte[] data = new byte[1024];
|
int len = 0;
|
try {
|
fileOutputStream = new FileOutputStream("D:\\2.jpg");
|
while ((len = inputStream.read(data)) != -1) {
|
fileOutputStream.write(data, 0, len);
|
}
|
|
} catch (Exception e) {
|
e.printStackTrace();
|
} finally {
|
try {
|
inputStream.close();
|
fileOutputStream.close();
|
} catch (IOException e) {
|
// TODO Auto-generated catch block
|
e.printStackTrace();
|
}
|
}
|
|
}
|
|
|
/**
|
* 根据图片路径获取Byte数组
|
* @param imgUrl
|
* @return
|
* @throws IOException
|
*/
|
public static byte[] getImgByte(String imgUrl) throws IOException {
|
InputStream inputStream = getInputStream(imgUrl);
|
if (inputStream != null) {
|
return IOUtils.toByteArray(inputStream);
|
}
|
return null;
|
}
|
|
/**
|
* @param args
|
*/
|
public static void main(String[] args) {
|
// TODO Auto-generated method stub
|
saveImage();
|
}
|
|
}
|