1. 程式人生 > 其它 >網路圖片等比例壓縮 + Token驗證(請求頭)下載按照日期分檔案

網路圖片等比例壓縮 + Token驗證(請求頭)下載按照日期分檔案

技術標籤:操作檔案java深度學習經驗分享

網路圖片下載

圖片Token驗證(請求頭)下載按照日期分檔案

某些業務場景要得到網路url中圖片,但是要登陸後獲得token才能請求到圖片

Util

/**
     * 圖片下載
     * @param urlList 網路圖片路徑
     * @param path 圖片儲存路徑
     * @param uri 圖片要建立資料夾路徑
     * @param token 目標登入成功後得到的請求頭引數
     */
public static void downloadPicture(String urlList,String path,String uri,String token) { try { if (!new File(uri).exists()) { File f = new File(uri); if(!f.exists()){ f.mkdirs(); } } log.info("<<<<<<<<<<<<<<圖片開始下載>>>>>>>>>>>>>>"
); URL url = new URL(urlList); // 開啟連線 HttpURLConnection con = (HttpURLConnection) url.openConnection(); //GET請求 con.setRequestMethod("GET"); //請求載入時間 con.setConnectTimeout(5*1000); //一種新增token方式 con.
setRequestProperty("accessToken",token); //兩種新增token方式 con.addRequestProperty("accessToken",token); con = (HttpURLConnection) url.openConnection(); // 輸入流 InputStream is = con.getInputStream(); // 1K的資料緩衝 byte[] bs = new byte[1024]; // 讀取到的資料長度 int len; // 輸出的檔案流 OutputStream os = new FileOutputStream(path); // 開始讀取 Integer fileSize = 0; while ((len = is.read(bs)) != -1) { os.write(bs, 0, len); fileSize += len; } log.info("<<<<<<<<<<<<<<圖片下載完成>>>>>>>>>>>>>>"); // 完畢,關閉所有連結 os.close(); } catch (Exception e) { // log.info("<<<<<<<<<<<<<<圖片下載失敗>>>>>>>>>>>>>>"); e.printStackTrace(); } }

測試

    /**
     * 圖片動態路徑落庫
     * @param alarmInfo
     * @param path
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
    	SimpleDateFormat fmt= new SimpleDateFormat("/yyyy/MM/dd/");
    	//日期圖片地址
		String path = fmt.format(date)(new Date());
    	//你請求得到的token
       	String token = "123456";
        //網路圖片路徑--圖片儲存路徑--要建立路徑--token
        ImageUtil.downloadPicture(
                "https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png",
                "D:/image/LD/"+path + "11111" + ".jpg",
                path,
                token);
    }

執行結果+會遇到的問題

在這裡插入圖片描述
斜槓 (/) (\) win和linux不一樣 不要出現 (/\)(\/)這種情況

圖片等比例壓縮

Util


import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;

/**
 * 圖片壓縮處理
 * @author 
 */
@Slf4j
@NoArgsConstructor
public class ImgCompress {
    private static Image img;
    private static int width;
    private static int height;
    private static String path; //壓縮後圖片位置
    private static int proportion;

    public static ImgCompress newImgCompress(){
        return new ImgCompress();
    }

    /**
     * 圖片壓縮演算法
     * @param inputPath
     * @param outputPath
     * @param pro
     */
    public static void initCompression(String inputPath, String outputPath, int pro){
        boolean flag=true;
        proportion=pro;
        URL url;
        try {
            url = new URL(inputPath);
            img = ImageIO.read(url);      // 構造Image物件
        } catch (Exception e) {
            e.printStackTrace();
        }
        width = img.getWidth(null);    // 得到源圖寬
        height = img.getHeight(null);  // 得到源圖長
        //如果圖片過小則不進行壓縮。
        if(width<200){
            flag=false;
        }else if(height<200){
            flag=false;
        }
        if(flag){
            path = outputPath;
            try {
                resizeFix(width/proportion, height/proportion);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 按照寬度還是高度進行壓縮
     * @param w int 最大寬度
     * @param h int 最大高度
     */
    public static void resizeFix(int w, int h) throws IOException {
        if (width / height > w / h) {
            resizeByWidth(w);
        } else {
            resizeByHeight(h);
        }
    }

    /**
     * 以寬度為基準,等比例放縮圖片
     * @param w int 新寬度
     */
    public static void resizeByWidth(int w) throws IOException {
        int h = (int) (height * w / width);
        resize(w, h);
    }

    /**
     * 以高度為基準,等比例縮放圖片
     * @param h int 新高度
     */
    public static void resizeByHeight(int h) throws IOException {
        int w = (int) (width * h / height);
        resize(w, h);
    }

    /**
     * 強制壓縮/放大圖片到固定的大小
     * @param w int 新寬度
     * @param h int 新高度
     */
    public static 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(path);
        FileOutputStream out = new FileOutputStream(destFile); // 輸出到檔案流
        // 可以正常實現bmp、png、gif轉jpg
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        encoder.encode(image); // JPEG編碼
        out.close();
    }
}

封裝一下路徑

    /**
     *
     * @param urlList 網路地址
     * @param path 圖片儲存路徑
     * @param uri 建立路徑
     * @throws IOException
     */
    public static void compressionImage(String urlList, String path, String uri, String token) throws IOException {
        if (!new File(uri).exists()) {
            File f = new File(uri);
            if(!f.exists()){
                f.mkdirs();
            }
        }
        log.info("<<<<<<<<<<<<<<圖片開始下載>>>>>>>>>>>>>>");
        URL url = new URL(urlList);
        ImgCompress.initCompression(url.toString(),path,4);
    }

測試

    /**
     * 圖片動態路徑落庫
     * @param alarmInfo
     * @param path
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
    	SimpleDateFormat fmt= new SimpleDateFormat("/yyyy/MM/dd/");
    	//日期圖片地址
		String path = fmt.format(date)(new Date());
    	//你請求得到的token
       	String token = "123456";
        //網路圖片路徑--圖片儲存路徑--要建立路徑--token
        ImageUtil.compressionImage(
                "https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png",
                "D:/image/LD/"+path + "11111" + ".jpg",
                path,
                token);
    }

結果

未壓縮之前
在這裡插入圖片描述
壓縮後
在這裡插入圖片描述
效果還是可以的