控制上傳圖片大小

來源:互聯網
上載者:User

標籤:

 圖片上傳問題:上傳到伺服器的圖片建議壓縮一下,因為iphone拍出的照片比較大,如果直接上傳無論是上傳還是下載都比較慢而且費流量,體驗不好.

具體思路如下:

 

先調整解析度,解析度可以自己設定一個值,大於的就縮小到這解析度,小餘的就保持原本解析度。然後在根據最終大小來設定壓縮比,比如傳入maxSize = 100k,最終計算大概這個大小的壓縮比。基本上最終出來的圖片資料根據當前解析度能保持差不多的大小同時不至於太模糊,跟,微博最終效果應該是差不多的,代碼仍然有待最佳化!

//控製圖片大小

- (NSData *)resetSizeOfImageData:(UIImage *)source_image maxSize:(NSInteger)maxSize

{

    //先調整解析度

    CGSize newSize = CGSizeMake(source_image.size.width, source_image.size.height);

    

    CGFloat tempHeight = newSize.height / 1024;

    CGFloat tempWidth = newSize.width / 1024;

    

    if (tempWidth > 1.0 && tempWidth > tempHeight) {

        newSize = CGSizeMake(source_image.size.width / tempWidth, source_image.size.height / tempWidth);

    }

    else if (tempHeight > 1.0 && tempWidth < tempHeight){

        newSize = CGSizeMake(source_image.size.width / tempHeight, source_image.size.height / tempHeight);

    }

    

    UIGraphicsBeginImageContext(newSize);

    [source_image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    

    //調整大小

    NSData *imageData = UIImageJPEGRepresentation(newImage,1.0);

    NSUInteger sizeOrigin = [imageData length];

    NSUInteger sizeOriginKB = sizeOrigin / 1024;

    if (sizeOriginKB > maxSize) {

        NSData *finallImageData = UIImageJPEGRepresentation(newImage,0.50);

        return finallImageData;

    }

    

    return imageData;

}

控制上傳圖片大小

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.