将图片缩放到适合窗口大小_Java

本文介绍了一种图片等比缩放算法,该算法能够确保图片在缩放过程中保持原始的比例,并适应不同的显示控件尺寸。通过计算图片的宽度和高度与控件的宽度和高度之间的比例关系,实现图片的智能缩放。

使用Map传出两个最大值和最小值

参数中 int conWidth,int conHeight 分别是存放图片窗口的长和宽
源码:
    /**
     * scaleImg(); 图像缩放方法,将图片缩放到适合控件的大小
     * ImageIcon image为显示的图片
     * int conWidth,int conHeight 分别是存放图片窗口的的长和宽
     */
    public static Map<String, Integer> scaleImage(ImageIcon image, double conWidth, double conHeight) {

        Map<String, Integer> imgWidthAndHeight = new HashMap<String, Integer>();

        //默认的边框间距
        final double SMALL_SCALE = 0.95;

        double imgWidth = image.getIconWidth();
        double imgHeight = image.getIconHeight();
        //原图的宽长比
        double imgRatio = imgWidth/imgHeight;
        //最终输出宽和长
        double reImgWidth = 0;
        double reImgHeight = 0;


        //若原图的宽小于控件宽
        if(imgWidth < conWidth){
            if(imgHeight < conHeight){
                reImgWidth = conWidth*SMALL_SCALE;
                reImgHeight = reImgWidth/imgRatio;
            }
            else {
                reImgHeight = conHeight*SMALL_SCALE;
                reImgWidth = reImgHeight*imgRatio;
            }
        }
        //若原图的宽大于控件宽
        else {
            if(imgHeight < conHeight){
                reImgWidth = conWidth*SMALL_SCALE;
                reImgHeight = reImgWidth/imgRatio;
            }
            //若原图的长宽同时大于控件的长宽,最复杂的情况
            else {
                //控件的长比宽大
                double conRatio = conWidth/conHeight;

                if (imgRatio < conRatio){
                    reImgHeight = conHeight*SMALL_SCALE;
                    reImgWidth = reImgHeight*imgRatio;
                }
                else {
                    reImgWidth = conWidth*SMALL_SCALE;
                    reImgHeight = reImgWidth/imgRatio;
                }
            }
        }




        imgWidthAndHeight.put("width", (int) reImgWidth);
        imgWidthAndHeight.put("height", (int) reImgHeight);

        return imgWidthAndHeight;
    }

使用方法:

//图片等比缩放函数
            Map<String, Integer> imgWidthAndHeight = ImageProcess.scaleImage(image,IMG_WIDTH,IMG_HEIGHT);
            scaleWidth = imgWidthAndHeight.get("width");
            scaleHeight= imgWidthAndHeight.get("height");


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值