Java取網絡圖片並縮小:
- package action;
-
- import java.awt.image.BufferedImage;
- import java.io.DataInputStream;
- import java.io.FileOutputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
-
- import com.sun.image.codec.jpeg.JPEGCodec;
- import com.sun.image.codec.jpeg.JPEGImageEncoder;
-
- public class Getpic {
- public Getpic() {
- }
-
- public static boolean saveUrlAs(String fileUrl, String savePath)/* fileUrl網絡資源地址 */
- {
-
- try {
- /* 將網絡資源地址傳給,即賦值給url */
- URL url = new URL(fileUrl);
-
- /* 此為聯系獲得網絡資源的固定格式用法,以便後面的in變量獲得url截取網絡資源的輸入流 */
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- DataInputStream in = new DataInputStream(connection.getInputStream());
-
- BufferedImage src = javax.imageio.ImageIO.read(in);
- int width = src.getWidth();
- int height = src.getHeight();
-
- // 邊長縮小為二分之一
- BufferedImage tag = new BufferedImage(width / 2, height / 2, BufferedImage.TYPE_INT_RGB);
- // 繪制縮小後的圖
- tag.getGraphics().drawImage(src, 0, 0, width / 2, height / 2, null);
- FileOutputStream out1 = new FileOutputStream(savePath);
- JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out1);
- encoder.encode(tag);
- out1.close();
-
-
- return true;/* 網絡資源截取並存儲本地成功返回true */
-
- } catch (Exception e) {
- System.out.println(e + fileUrl + savePath);
- return false;
- }
- }
-
- public static void main(String[] args) {
- Getpic pic = new Getpic();/* 創建實例 */
-
- //需要下載的URL
- String photoUrl = "http://hiphotos.baidu.com/yanshennan/pic/item/03a505c8bcbaf6557f3e6f8a.jpg";
-
- // 截取最後/後的字符串
- String fileName = photoUrl.substring(photoUrl.lastIndexOf("/"));
-
- //圖片保存路徑
- String filePath = "E:";
-
- /* 調用函數,並且進行傳參 */
- boolean flag = pic.saveUrlAs(photoUrl, filePath + fileName);
-
- System.out.println("Run ok!\n Get URL file " + flag);
- System.out.println(filePath);
- System.out.println(fileName);
- }
-
- }
相關閱讀: Linux Java取網絡圖片縮小報錯解決 http://www.linuxidc.com/Linux/2012-02/55468.htm