zoukankan      html  css  js  c++  java
  • Android 根据宽高比确定新宽高

      今天遇到一个问题,要求图片大小不能超过4096 * 4096,如果超过此大小,需要进行压缩处理,为了不让图片失真,所以需要根据图片的宽高比来进行压缩。

    思路

    为使图片不失真,所以要根据宽高比来计算新宽高,求出宽高的最小公约数,然后减小公约数的值,使新公约数乘以宽高比小于最大尺寸。

    实现步骤:

    1. 获取宽高的最小公约数

    2. 计算宽高比

    3. 对比宽高,找出最大值,重新计算公约数

    4. 根据新得到的公约数和宽高比来计算图片的宽高

    /**
     * 计算压缩图片的宽高
     */
    public void getCompressPicSize(){
        int gcd = getGCD(curPicWidth,curPicHeight);
        int ratioW = curPicWidth  / gcd;
        int ratioH = curPicHeight  / gcd;
        int newGCD;
        if(curPicWidth > curPicHeight){
            newGCD =  getOptimumGCD(ratioW);
        }else {
            newGCD = getOptimumGCD(ratioH);
        }
        int compressPicWidth =  newGCD  * ratioW; // 压缩后的宽高
        int compressPicHeight =  newGCD  * ratioH;
        Log.e("输出结果:", "最小公约数"+ gcd +"
     比例为:" + ratioW +":"+ ratioH+"
     新公约数为:" + newGCD +"
     新宽高为:" + compressPicWidth +"-"+ compressPicHeight ); 
    }
    /**
     * 获取最小公约数
     * @param w 宽
     * @param h 高
     * @return
     */
    public int getGCD(int w,int h){
        int result = 0;
        while (h != 0){
            result = w % h;
            w = h;
            h = result;
        }
        return w;
    }
    /**
     * 计算出最佳公约数
     * @param ratio
     * @return
     */
    public int getOptimumGCD(int ratio){
        return  picMaxWH / ratio;
    }
  • 相关阅读:
    Charles 注册码
    pom.xml
    SpringMVC 表格跳转后显示${message}中的内容显示不出来
    使用IDEA 开发Spring,Maven-->并且部署到 tomcat
    Leetcode51 N后
    n queen
    八皇后问题
    Access提示“操作必须使用一个可更新的查询”的解决办法
    Win7系统卸载McAfee杀毒软件
    Win7(x64)升级到Win10
  • 原文地址:https://www.cnblogs.com/Ayinger/p/11078110.html
Copyright © 2011-2022 走看看