java獲取遠程網絡圖片文件流、壓縮保存到本地


1.獲取遠程網路的圖片

         /**
	 * 根據地址獲得數據的字節流
	 * 
	 * @param strUrl
	 *            網絡連接地址
	 * @return
	 */
	public static byte[] getImageFromNetByUrl(String strUrl) {
		try {
			URL url = new URL(strUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5 * 1000);
			InputStream inStream = conn.getInputStream();// 通過輸入流獲取圖片數據
			byte[] btImg = readInputStream(inStream);// 得到圖片的二進制數據
			return btImg;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
       /**
	 * 根據地址獲得數據的字節流
	 * 
	 * @param strUrl
	 *            本地連接地址
	 * @return
	 */
	public static byte[] getImageFromLocalByUrl(String strUrl) {
		try {
			File imageFile = new File(strUrl);
			InputStream inStream = new FileInputStream(imageFile);
			byte[] btImg = readInputStream(inStream);// 得到圖片的二進制數據
			return btImg;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
       /**
	 * 從輸入流中獲取數據
	 * 
	 * @param inStream
	 *            輸入流
	 * @return
	 * @throws Exception
	 */
	public static byte[] readInputStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[10240];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		inStream.close();
		return outStream.toByteArray();
	}  

2.將網絡讀取的文件流轉成本地文件

                byte[] btImg1 = ImageUtil.getImageFromNetByUrl(fileUrl1);
		if (null != btImg1 && btImg1.length > 0) {
			logger.debug("讀取到:" + btImg1.length + " 字節");
			ImageUtil.writeImageToDisk(btImg1, fileZipUrl1);
		} else {
			logger.debug("沒有從該連接獲得內容");
		}

		byte[] btImg2 = ImageUtil.getImageFromNetByUrl(fileUrl2);
		if (null != btImg2 && btImg2.length > 0) {
			logger.debug("讀取到:" + btImg2.length + " 字節");
			ImageUtil.writeImageToDisk(btImg2, fileZipUrl2);
		} else {
			logger.debug("沒有從該連接獲得內容");
		}
	/**
	 * 將圖片寫入到磁盤
	 * 
	 * @param img
	 *            圖片數據流
	 * @param fileName
	 *            文件保存時的名稱
	 */
	public static void writeImageToDisk(byte[] img, String zipImageUrl) {
		try {
			File file = new File(zipImageUrl);
			FileOutputStream fops = new FileOutputStream(file);
			fops.write(img);
			fops.flush();
			fops.close();
			System.out.println("圖片已經寫入"+zipImageUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

3、壓縮本地圖片

import java.io.*;  
import java.util.Date;  
import java.awt.*;  
import java.awt.image.*;  
import javax.imageio.ImageIO;  
import com.sun.image.codec.jpeg.*;  
/** 
 * 圖片壓縮處理 
 */  
public class ImgCompress {  
    private Image img;  
    private int width;  
    private int height;   
    /** 
     * 構造函數 
     */  
    public ImgCompress(String fileName) throws IOException {  
        File file = new File(fileName);// 讀入文件  
        img = ImageIO.read(file);      // 構造Image對象  
        width = img.getWidth(null);    // 得到源圖寬  
        height = img.getHeight(null);  // 得到源圖長  
    }  
    /** 
     * 按照寬度還是高度進行壓縮 
     * @param w int 最大寬度 
     * @param h int 最大高度 
     */  
    public void resizeFix(int w, int h) throws IOException {  
        if (width / height > w / h) {  
            resizeByWidth(w);  
        } else {  
            resizeByHeight(h);  
        }  
    }  
    /** 
     * 以寬度為基准,等比例放縮圖片 
     * @param w int 新寬度 
     */  
    public void resizeByWidth(int w) throws IOException {  
        int h = (int) (height * w / width);  
        resize(w, h);  
    }  
    /** 
     * 以高度為基准,等比例縮放圖片 
     * @param h int 新高度 
     */  
    public void resizeByHeight(int h) throws IOException {  
        int w = (int) (width * h / height);  
        resize(w, h);  
    }  
    /** 
     * 強制壓縮/放大圖片到固定的大小 
     * @param w int 新寬度 
     * @param h int 新高度 
     */  
    public void resize(int w, int h) throws IOException {  
        // SCALE_SMOOTH 的縮略算法 生成縮略圖片的平滑度的 優先級比速度高 生成的圖片質量比較好 但速度慢  
        BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB );   
        image.getGraphics().drawImage(img, 0, 0, w, h, null); // 繪制縮小后的圖  
        File destFile = new File("C:/Users/Administrator/Desktop/147.jpg");  
        FileOutputStream out = new FileOutputStream(destFile); // 輸出到文件流  
        // 可以正常實現bmp、png、gif轉jpg  
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
        encoder.encode(image); // JPEG編碼  
        out.close();  
    }

    @SuppressWarnings("deprecation")  
    public static void main(String[] args) throws Exception {  
        System.out.println("開始:" + new Date().toLocaleString());  
        ImgCompress imgCom = new  ImgCompress("C:/Users/Administrator/Desktop/1479209533362.jpg");  
        imgCom.resizeFix(285, 380);  
        System.out.println("結束:" + new Date().toLocaleString());  
    } 
} 

 完~

 

  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM