java压缩网络图片,压缩图片

复制代码
package com.qxnw.healthserver.core.util;

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

public class AliossUtil {
    /**目标图片大小,至于高度,等比例即可,ps:width在2000以上,已看不出区别*/
    public static final int TARGET_WIDTH = 3000;

    public static void main(String[] args) {
        String url = "https://img1.360buyimg.com/image/jfs/t1/38591/20/3737/314695/5cc69c01E1838df09/dd6dce681bd23031.jpg";
       resizeImg(url);
    }

    public static void resizeImg(String url){
        try {
            //通过url获取BufferedImage图像缓冲区
            URL img = new URL(url);
            BufferedImage image = ImageIO.read(img);
            //获取图片的宽、高
            double rate = image.getWidth()*1.0/image.getHeight();
            int targetHeight = (int) (TARGET_WIDTH*1.0/rate);
            //调整图片大小为 400X400尺寸
            BufferedImage newImage = resizeImage(image,TARGET_WIDTH,targetHeight);

            System.out.println("old:w,h= " + image.getWidth()+","+image.getHeight()+"\nnew:w,h="+TARGET_WIDTH+","+targetHeight);

            //将缓冲区图片保存到 F:/test/pic1.jpg (文件不存在会自动创建文件保存,文件存在会覆盖原文件保存)
            ImageIO.write(newImage, "jpg", new File("d:/a.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过BufferedImage图片流调整图片大小
     */
    public static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) throws IOException {
        Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_AREA_AVERAGING);
        BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
        outputImage.getGraphics().drawImage(resultingImage, 0, 0, null);
        return outputImage;
    }
}
复制代码

 

 
posted @   君子笑而不语  阅读(51)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2022-05-17 vue点击复制
2021-05-17 java8 stream多字段排序
2013-05-17 struts2跳转后总是会返回input
点击右上角即可分享
微信分享提示