ピクチャーurlによって直接にピクチャーbaseを獲得します。
18556 ワード
ネットでたくさん見ましたが、写真urlによって写真を取得するのは面倒くさいです。
下のこれはとても簡単です。下のこのツール類のcopyをベースに戻すだけでいいです。
下のこれはとても簡単です。下のこのツール類のcopyをベースに戻すだけでいいです。
package cn.com.zcits.exchange.modules.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class);
/**
* @Function: Base64
* @param imgSrc -
*/
public static String getImageBase64StrFromUrl(String imgSrc) throws Exception{
URL url = null;
InputStream is = null;
ByteArrayOutputStream outStream = null;
HttpURLConnection httpUrl = null;
try{
url = new URL(imgSrc);
httpUrl = (HttpURLConnection) url.openConnection();
httpUrl.setRequestMethod("GET");
httpUrl.setConnectTimeout(30 * 1000);
httpUrl.connect();
httpUrl.getInputStream();
is = httpUrl.getInputStream();
outStream = new ByteArrayOutputStream();
// Buffer
byte[] buffer = new byte[2048];
// , -1,
int len = 0;
// buffer
while( (len=is.read(buffer)) != -1 ){
// buffer , ,len
outStream.write(buffer, 0, len);
}
// Base64
return java.util.Base64.getEncoder().encodeToString(outStream.toByteArray());
}catch (Exception e) {
throw new Exception(e);
}finally{
if(is != null) {
try {
is.close(); } catch (IOException e) {
e.printStackTrace(); }
}
if(outStream != null) {
try {
outStream.close();} catch (IOException e) {
e.printStackTrace();}
}
if(httpUrl != null){
httpUrl.disconnect();}
}
}
/**
* - GET
* @param strUrl
* @return
*/
public static byte[] getImageFromNetByUrl(String strUrl) throws Exception {
try {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(10 * 1000);
//
InputStream inStream = conn.getInputStream();
//
byte[] btImg = readInputStream(inStream);
return btImg;
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
}
/**
* @Function:
* @param inStream -
* @throws IOException
*/
private static byte[] readInputStream(InputStream inStream) throws IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
}