/**
* 通过url获取图片并保存至本地
*/
public String getImgFromUrl(String urlstr) {
String head_path = ConfigManager.get("head_path");
String head_path_db = ConfigManager.get("head_path_db");
int num = urlstr.indexOf('/',8);
int extnum = urlstr.lastIndexOf('.');
String u = urlstr.substring(0,num);
String ext = urlstr.substring(extnum+1,urlstr.length());
if(ext.equals("jpg") || ext.equals("jpeg") || ext.equals("jpe") || ext.equals("jfif") ||ext.equals("png") ||ext.equals("gif")){
}else{
ext = "jpg";
}
try{
// long curTime = System.currentTimeMillis();
// Random random = new Random(100000000);
String uuid = UUID.randomUUID().toString().replace("-","");
// 图片的路径
String path = head_path + uuid + "." + ext;
//入库路径
String dataPath = head_path_db + uuid + "." + ext;
// String fileName = String.valueOf(curTime) + "_"
// + random.nextInt(100000000) + ext;
URL url = new URL(urlstr);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("referer", u);
//通过这个http头的伪装来反盗链
BufferedImage image = ImageIO.read(connection.getInputStream());
FileOutputStream fout=new FileOutputStream(path);
if("gif".equals(ext)|| "png".equals(ext))
{
ImageIO.write(image, ext, fout);
}
ImageIO.write(image, "jpg", fout);
fout.flush();
fout.close();
return dataPath;
}
catch(Exception e)
{
System.out.print(e.getMessage().toString());
}
return "";
}
通过url获取图片并保存至本地
最新推荐文章于 2024-07-14 14:31:02 发布