簡體   English   中英

IOS 如何根據實際圖像比例調整圖像大小並給出自定義大小?

[英]IOS How to resize image according to actual image ratio and give custom size?

通過檢查實際圖像比例來調整UIImagecustom size以減小圖像大小。 我已經試過這個UIImageJPEGRepresentation(Image, 0.8); 但問題是圖像質量正在降低。 任何幫助將非常感激。 謝謝

UIImage傳遞給以下方法,該方法使用自定義高度/寬度調整圖像大小,您還可以提供圖像的壓縮值以減小圖像大小並檢查調整大小前后的圖像大小。

這是示例方法-

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

    NSInteger imageActualSize = UIImageJPEGRepresentation(image,1).length;

    NSLog(@"size of IMAGE before resizing: %@ ", [NSByteCountFormatter stringFromByteCount:imageActualSize countStyle:NSByteCountFormatterCountStyleFile]);

    float actualHeight = image.size.height;
    float actualWidth = image.size.width;
    float maxHeight = 400.0; // your custom  height
    float maxWidth = 350; // your custom  width
    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();

    NSInteger imageReduceSize = imageData.length;

    NSLog(@"size of IMAGE after resizing: %@ ",[NSByteCountFormatter stringFromByteCount:imageReduceSize countStyle:NSByteCountFormatterCountStyleFile]);

    return [UIImage imageWithData:imageData];

}

這會幫助你..:)

+ (UIImage *)resizeImage:(UIImage *)image toSize:(CGSize)newSize {
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

非常簡單的方法來做到這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM