网络图片等比例压缩 + Token验证(请求头)下载按照日期分文件

图片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);
    }

结果

未压缩之前
在这里插入图片描述
压缩后
在这里插入图片描述
效果还是可以的

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值