iOS開發中壓縮圖片的質量以及縮小圖片尺寸

樑森森發表於2017-07-14

-(UIImage *)resizeImage:(UIImage *)image

{

    float actualHeight = image.size.height;

    float actualWidth = image.size.width;

    float maxHeight = 300.0;    // 圖片的最大高度

    float maxWidth = 400.0; // 圖片的最大寬度

    float imgRatio = actualWidth/actualHeight;

    float maxRatio = maxWidth/maxHeight;

    float compressionQuality = 0.5;//50 percent compression

    

    if (actualHeight > maxHeight || actualWidth > maxWidth)

    {

        if(imgRatio < maxRatio)

        {

            //adjust width according to maxHeight

            imgRatio = maxHeight / actualHeight;

            actualWidth = imgRatio * actualWidth;

            actualHeight = maxHeight;

        }

        else if(imgRatio > maxRatio)

        {

            //adjust height according to maxWidth

            imgRatio = maxWidth / actualWidth;

            actualHeight = imgRatio * actualHeight;

            actualWidth = maxWidth;

        }

        else

        {

            actualHeight = maxHeight;

            actualWidth = maxWidth;

        }

    }

    

    CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);

    UIGraphicsBeginImageContext(rect.size);

    [image drawInRect:rect];

    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();

    NSData *imageData = UIImageJPEGRepresentation(img, compressionQuality);

    UIGraphicsEndImageContext();

    

    return [UIImage imageWithData:imageData];

    

}


相關文章