iOS壓縮圖片大小

來源:互聯網
上載者:User

iOS壓縮圖片大小

最近碰到一個比較愚蠢的問題,項目中做的拍照或者從相簿選擇圖片上傳時,沒有經過處理,直接把原圖上傳了,導致在列表中看的時候,明明是小圖片流量卻要爆炸了,想想iphone拍出照片大小可都是以M為單位的。所以趕緊做了下壓縮處理再上傳。為了方便根據不同壓縮需求調用,這裡採用調用可修改參數的方法的做法,更加靈活一點。調用的方法如下:

//圖片伸縮到指定大小- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize forImage:(UIImage *)originImage{    UIImage *sourceImage = originImage;// 原圖    UIImage *newImage = nil;// 新圖// 原圖尺寸    CGSize imageSize = sourceImage.size;    CGFloat width = imageSize.width;    CGFloat height = imageSize.height;    CGFloat targetWidth = targetSize.width;// 目標寬度    CGFloat targetHeight = targetSize.height;// 目標高度// 伸縮參數初始化    CGFloat scaleFactor = 0.0;    CGFloat scaledWidth = targetWidth;    CGFloat scaledHeight = targetHeight;    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);        if (CGSizeEqualToSize(imageSize, targetSize) == NO)    {// 如果原尺寸與目尺規寸不同才執行        CGFloat widthFactor = targetWidth / width;        CGFloat heightFactor = targetHeight / height;                if (widthFactor > heightFactor)            scaleFactor = widthFactor; // 根據寬度伸縮        else            scaleFactor = heightFactor; // 根據高度伸縮        scaledWidth= width * scaleFactor;        scaledHeight = height * scaleFactor;                // 定位元影像片的中心點        if (widthFactor > heightFactor)        {            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;        }        else if (widthFactor < heightFactor)        {            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;        }    }    // 建立基於位元影像的上下文    UIGraphicsBeginImageContext(targetSize);    // 目尺規寸    CGRect thumbnailRect = CGRectZero;    thumbnailRect.origin = thumbnailPoint;    thumbnailRect.size.width= scaledWidth;    thumbnailRect.size.height = scaledHeight;        [sourceImage drawInRect:thumbnailRect];    // 新圖片    newImage = UIGraphicsGetImageFromCurrentImageContext();    if(newImage == nil)        NSLog(@"could not scale image");        // 退出位元影像上下文    UIGraphicsEndImageContext();    return newImage;}
我在注釋裡都寫明了一下。這個方法接受兩個參數,一個是要壓縮到的尺寸,另一個是原圖。調用的過程也很簡單,比如:
// 伸縮圖片if ([self imageByScalingAndCroppingForSize:CGSizeMake(100, 100) forImage:theImage]) {// 伸縮成功    theImage = [self imageByScalingAndCroppingForSize:CGSizeMake(100, 100) forImage:theImage];}
這樣就可以了,我把名為theImage的圖片檔案壓縮到100*100的尺寸,經過測試,原來1M的圖片處理後就只有20多k了,這樣流量的壓力就大大減少啦。

這個方法也可以用來伸縮圖片的尺寸,不過我還是用來壓縮的,在不追求高清晰度的情況下,使用還是很方便靈活的,希望能幫到大家~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.