Java取网络图片并缩小


Java取网络图片并缩小:

  1. package action;  
  2.   
  3. import java.awt.image.BufferedImage;  
  4. import java.io.DataInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.net.HttpURLConnection;  
  7. import java.net.URL;  
  8.   
  9. import com.sun.image.codec.jpeg.JPEGCodec;  
  10. import com.sun.image.codec.jpeg.JPEGImageEncoder;  
  11.   
  12. public class Getpic {  
  13.     public Getpic() {  
  14.     }  
  15.   
  16.     public static boolean saveUrlAs(String fileUrl, String savePath)/* fileUrl网络资源地址 */  
  17.     {  
  18.   
  19.         try {  
  20.             /* 将网络资源地址传给,即赋值给url */  
  21.             URL url = new URL(fileUrl);  
  22.               
  23.             /* 此为联系获得网络资源的固定格式用法,以便后面的in变量获得url截取网络资源的输入流 */  
  24.             HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
  25.             DataInputStream in = new DataInputStream(connection.getInputStream());  
  26.               
  27.              BufferedImage src = javax.imageio.ImageIO.read(in);  
  28.              int width = src.getWidth();     
  29.                 int height = src.getHeight();     
  30.             
  31.                 // 边长缩小为二分之一      
  32.                 BufferedImage tag = new BufferedImage(width / 2, height / 2, BufferedImage.TYPE_INT_RGB);     
  33.                 // 绘制缩小后的图      
  34.                 tag.getGraphics().drawImage(src, 00, width / 2, height / 2null);     
  35.                 FileOutputStream out1 = new FileOutputStream(savePath);     
  36.                 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out1);     
  37.                 encoder.encode(tag);     
  38.                 out1.close();     
  39.               
  40.               
  41.             return true;/* 网络资源截取并存储本地成功返回true */  
  42.   
  43.         } catch (Exception e) {  
  44.             System.out.println(e + fileUrl + savePath);  
  45.             return false;  
  46.         }  
  47.     }  
  48.   
  49.     public static void main(String[] args) {  
  50.         Getpic pic = new Getpic();/* 创建实例 */  
  51.           
  52.         //需要下载的URL   
  53.         String photoUrl = "http://hiphotos.baidu.com/yanshennan/pic/item/03a505c8bcbaf6557f3e6f8a.jpg";  
  54.   
  55.         // 截取最后/后的字符串   
  56.         String fileName = photoUrl.substring(photoUrl.lastIndexOf("/"));  
  57.           
  58.         //图片保存路径   
  59.         String filePath = "E:";  
  60.           
  61.         /* 调用函数,并且进行传参 */  
  62.         boolean flag = pic.saveUrlAs(photoUrl, filePath + fileName);  
  63.           
  64.         System.out.println("Run ok!\n Get URL file " + flag);  
  65.         System.out.println(filePath);  
  66.         System.out.println(fileName);  
  67.     }  
  68.   
  69. }  
相关阅读: Linux Java取网络图片缩小报错解决

相关内容