读取网页图片

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;


public class ConnTest {
	private static Logger logger = Logger.getLogger(ConnTest.class);
	public static void main(String[] args) {
		Map<String, Object> map = null;
		ConnTest connTest = new ConnTest();
		String picUrl = "http://img.alicdn.com/bao/uploaded/i4/1039969019/TB2Oso2cDMlyKJjSZFFXXalVFXa_!!1039969019.jpg_430x430q90.jpg";
		 try {
			map = connTest.getUrlPicLR_try2(picUrl);
		 } catch (Exception e) {	//第一次“获取网络连接图片的长宽及图片名”失败后,尝试第二次
			 e.printStackTrace();
			logger.info("第一次“获取网络连接图片的长宽及图片名”失败,下面开始尝试第二次:");
			try {
				Thread.sleep(2*1000);
				logger.info("================》当前线程睡2秒");
				map = connTest.getUrlPicLR_try2(picUrl);
			} catch (Exception e1) {
				logger.info("很遗憾!第二次“获取网络连接图片的长宽及图片名”也失败,将不再尝试");
			}
		 }
		 System.out.println(map.get("picName"));	//如果两次“获取网络连接图片的长宽及图片名”均失败,则返回null
		 System.out.println(map.get("width"));
		 System.out.println(map.get("height"));
	}
	public Map<String, Object> getUrlPicLR_try2(String picUrl) throws Exception{
		 Map<String, Object> map = new HashMap<>();
		 URL url = null;  
	     InputStream is = null;  
	     BufferedImage img = null;
	     File picture = new File(picUrl);
	     String picName = picture.getName();
		 map.put("picName", picName);
	     try {  
	    	 url = new URL(picUrl); 
	    	 // 打开连接
	    	 URLConnection con = url.openConnection();
	    	 System.err.println("打开连接成功");
	    	 con.setConnectTimeout(10000);//链接时间
	    	 con.setReadTimeout(10000);
	    	 // 输入流
	    	 is = con.getInputStream();
	         //is = url.openStream();  
	         img = ImageIO.read(is);
	              
	         if(img!=null){  
	        	 int width =  img.getWidth();
	        	 map.put("width", width);
	        	 int height = img.getHeight();
	        	 map.put("height", height);
	         }else{  
	        	 System.out.println("图片不存在!");  
	         }  
	     } catch (Exception e) {
	    	 e.printStackTrace();
	    	 map = null;
	     }  finally {  
	         try {
	        	 is.close();
	        	 if(map == null) {
	        		 throw new Exception("关流成功,流读取失败");
	        	 }
	         } catch (Exception e) {  
	        	 throw new Exception("关流失败");
	         }
	     }  
		 return map;
	 }
}

上述是将图片从网页上读取图片,下面是切割图片

public String picCut(String url){
		SimpleDateFormat YYYY = new SimpleDateFormat("yyyy");
		SimpleDateFormat MM = new SimpleDateFormat("MM");
		SimpleDateFormat dd = new SimpleDateFormat("dd");
		Long nowTime = System.currentTimeMillis();
		String year = YYYY.format(nowTime);
		String month = MM.format(nowTime);
		String day = dd.format(nowTime);
		String now = year+"\\"+month+"\\"+day;
		 
		 File picture = new File(url);  
	     BufferedImage sourceImg;
	     String arrurl = "";
	     try {
				sourceImg = ImageIO.read(new FileInputStream(picture));
				int width =  sourceImg.getWidth();
				int height = sourceImg.getHeight();
				
		        FileInputStream is = null;  
		        ImageInputStream iis = null;  
		        try {  
		            // 读取图片文件  
		            is = new FileInputStream(url);  
		  
		            Iterator<ImageReader> it = ImageIO  
		                    .getImageReadersByFormatName(url.substring(url.length()-3));  
		  
		            ImageReader reader = it.next();  
		  
		            // 获取图片流  
		            iis = ImageIO.createImageInputStream(is);  
		  
		           
		            reader.setInput(iis, true);  
		  
		            
		            ImageReadParam param = reader.getDefaultReadParam();  
		  
		          
		            Rectangle rect = new Rectangle(0, 0, width, (int) ((int)height*0.8));  
		  
		              
		            param.setSourceRegion(rect);  
		  
		            
		            BufferedImage bi = reader.read(0, param);  
		  
		            // 保存新图片 
		            if(!(new File("D:\\en_US1\\pic\\"+now)).exists()){
		            	(new File("D:\\en_US1\\pic\\"+now)).mkdirs();
		                System.out.println("创建目录为:"+(new File("D:\\en_US1\\pic\\"+now)));
		                Thread.sleep(500);
		            }
		            ImageIO.write(bi, url.substring(url.length()-3), new File(url.replace("C:", "D:")));
		            
		        } finally {  
		            if (is != null)
		                is.close();  
		            if (iis != null)
		            	iis.flush();
		                iis.close();  
		        }  
		} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.out.print("====================图片读取失败");
		} 
	    System.out.println("===========================图片剪切完成");
	    return url.replace("C:", "D:");
	 }

从网页上下载图片

//根据图片URL将图片下载到本地
	 public String downPic(String picUrl){
		 
		SimpleDateFormat YYYY = new SimpleDateFormat("yyyy");
		SimpleDateFormat MM = new SimpleDateFormat("MM");
		SimpleDateFormat dd = new SimpleDateFormat("dd");
		Long nowTime = System.currentTimeMillis();
		String year = YYYY.format(nowTime);
		String month = MM.format(nowTime);
		String day = dd.format(nowTime);
		String now = year+"\\"+month+"\\"+day;
		 
		 String bUrl = null;
		 try {
			 URL url = new URL(picUrl); 
			 // 打开连接
			 URLConnection con = url.openConnection();
			 con.setConnectTimeout(10000);//链接时间
			 con.setReadTimeout(10000);
			 
			 // 输入流
			 InputStream is = con.getInputStream();
			 
	         DataInputStream dataInputStream = new DataInputStream(is);  
	         String imageName = this.getUrlPicLR(picUrl).get("picName").toString();
	         if(!(new File("C:\\en_US1\\pic\\"+now)).exists()){
	        	 (new File("C:\\en_US1\\pic\\"+now)).mkdirs();
	                System.out.println("创建目录为:"+(new File("C:\\en_US1\\pic\\"+now)));
	                Thread.sleep(500);
	            }
	         FileOutputStream fileOutputStream = new FileOutputStream(new File("C:\\en_US1\\pic\\"+now+"\\"+imageName));  
	         
	         byte[] buffer = new byte[1024];  
	         int length;  

	         while ((length = dataInputStream.read(buffer)) > 0) {  
	             fileOutputStream.write(buffer, 0, length);  
	         }  
	         
	         dataInputStream.close(); 
	         fileOutputStream.flush();
	         fileOutputStream.close();
	         bUrl = ("C:\\en_US1\\pic\\"+now+"\\"+imageName);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error("===================图片下载失败");
		}
		 
		 System.out.print(picUrl+"===============下载成功");
		 
		 return bUrl;
	 }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值