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;
}
原文地址:https://www.cnblogs.com/Ayinger/p/11078110.html