iOS加載超清大圖內(nèi)存暴漲問題解決

加載超清大圖是會引起內(nèi)存爆表的問題,最近一直困擾著我择懂。
SDWebImage在加載大圖時做的不是很好侦厚,加載大圖內(nèi)存爆表。YYWebImage會好一點括眠,但還是不行。
當(dāng)不要求圖片質(zhì)量的情況下倍权,最好是在上傳圖片的時候就壓縮圖片掷豺,如果顯示的時候再壓縮的話也會導(dǎo)致內(nèi)存暴漲,壓縮也是很占內(nèi)存的薄声。
而對于UIImageJPEGRepresentation壓縮方法当船,不能降低顯示內(nèi)存。因為顯示圖片所占的內(nèi)存大小只與圖片的分辨率有關(guān)默辨,與圖片的大小無關(guān)德频。UIImageJPEGRepresentation壓縮方法只能降低圖片大小,分辨率不變廓奕。
壓縮圖片的兩張方式看我寫的這篇http://www.reibang.com/p/8150a8e7c0e4
后來找到了蘋果的一個官方建議加載大圖的demo
https://developer.apple.com/library/ios/samplecode/LargeImageDownsizing/

我改裝之后的代碼抱婉,可以直接用:

#import "LargeImageDispose.h"

#define IPAD1_IPHONE3GS
#ifdef IPAD1_IPHONE3GS
#   define kDestImageSizeMB 60.0f // The resulting image will be (x)MB of uncompressed image data.
#   define kSourceImageTileSizeMB 20.0f // The tile size will be (x)MB of uncompressed image data.
#endif

/* These constants are suggested initial values for iPad2, and iPhone 4 */
//#define IPAD2_IPHONE4
#ifdef IPAD2_IPHONE4
#   define kDestImageSizeMB 120.0f // The resulting image will be (x)MB of uncompressed image data.
#   define kSourceImageTileSizeMB 40.0f // The tile size will be (x)MB of uncompressed image data.
#endif

/* These constants are suggested initial values for iPhone3G, iPod2 and earlier devices */
//#define IPHONE3G_IPOD2_AND_EARLIER
#ifdef IPHONE3G_IPOD2_AND_EARLIER
#   define kDestImageSizeMB 30.0f // The resulting image will be (x)MB of uncompressed image data.
#   define kSourceImageTileSizeMB 10.0f // The tile size will be (x)MB of uncompressed image data.
#endif

#define bytesPerMB 1048576.0f
#define bytesPerPixel 4.0f
#define pixelsPerMB ( bytesPerMB / bytesPerPixel )
#define destTotalPixels kDestImageSizeMB * pixelsPerMB
#define tileTotalPixels kSourceImageTileSizeMB * pixelsPerMB
#define destSeemOverlap 2.0f

@interface LargeImageDispose ()
{
    CGContextRef destContext;
}
@property (strong, nonatomic) UIImage *destImage;


@end

@implementation LargeImageDispose


-(UIImage *)downsizeLargeImage:(UIImage *)image {
    
    // create an image from the image filename constant. Note this
    // doesn't actually read any pixel information from disk, as that
    // is actually done at draw time.
    UIImage *sourceImage = image;
    if( sourceImage == nil ) NSLog(@"input image not found!");
    // get the width and height of the input image using
    // core graphics image helper functions.
    CGSize sourceResolution;
    sourceResolution.width = CGImageGetWidth(sourceImage.CGImage);
    sourceResolution.height = CGImageGetHeight(sourceImage.CGImage);
    // use the width and height to calculate the total number of pixels
    // in the input image.
    float sourceTotalPixels = sourceResolution.width * sourceResolution.height;
    // calculate the number of MB that would be required to store
    // this image uncompressed in memory.
    float sourceTotalMB = sourceTotalPixels / pixelsPerMB;
    
    NSLog(@"%.2f",sourceTotalMB);

    // determine the scale ratio to apply to the input image
    // that results in an output image of the defined size.
    // see kDestImageSizeMB, and how it relates to destTotalPixels.
    float imageScale = destTotalPixels / sourceTotalPixels;
    NSLog(@"%.2f",destTotalPixels);
    // use the image scale to calcualte the output image width, height
    CGSize destResolution;
    destResolution.width = (int)( sourceResolution.width * imageScale );
    destResolution.height = (int)( sourceResolution.height * imageScale );
    // create an offscreen bitmap context that will hold the output image
    // pixel data, as it becomes available by the downscaling routine.
    // use the RGB colorspace as this is the colorspace iOS GPU is optimized for.
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    int bytesPerRow = bytesPerPixel * destResolution.width;
    // allocate enough pixel data to hold the output image.
    void* destBitmapData = malloc( bytesPerRow * destResolution.height );
    if( destBitmapData == NULL ) NSLog(@"failed to allocate space for the output image!");
    // create the output bitmap context
    
    destContext = CGBitmapContextCreate( destBitmapData, destResolution.width, destResolution.height, 8, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast );
    //    self.destContext = destContext;
    // remember CFTypes assign/check for NULL. NSObjects assign/check for nil.
    if( destContext == NULL ) {
        free( destBitmapData );
        NSLog(@"failed to create the output bitmap context!");
    }
    // release the color space object as its job is done
    CGColorSpaceRelease( colorSpace );
    // flip the output graphics context so that it aligns with the
    // cocoa style orientation of the input document. this is needed
    // because we used cocoa's UIImage -imageNamed to open the input file.
    CGContextTranslateCTM( destContext, 0.0f, destResolution.height );
    CGContextScaleCTM( destContext, 1.0f, -1.0f );
    // now define the size of the rectangle to be used for the
    // incremental blits from the input image to the output image.
    // we use a source tile width equal to the width of the source
    // image due to the way that iOS retrieves image data from disk.
    // iOS must decode an image from disk in full width 'bands', even
    // if current graphics context is clipped to a subrect within that
    // band. Therefore we fully utilize all of the pixel data that results
    // from a decoding opertion by achnoring our tile size to the full
    // width of the input image.
    CGRect sourceTile;
    sourceTile.size.width = sourceResolution.width;
    // the source tile height is dynamic. Since we specified the size
    // of the source tile in MB, see how many rows of pixels high it
    // can be given the input image width.
    sourceTile.size.height = (int)( tileTotalPixels / sourceTile.size.width );
    NSLog(@"source tile size: %f x %f",sourceTile.size.width, sourceTile.size.height);
    sourceTile.origin.x = 0.0f;
    // the output tile is the same proportions as the input tile, but
    // scaled to image scale.
    CGRect destTile;
    destTile.size.width = destResolution.width;
    destTile.size.height = sourceTile.size.height * imageScale;
    destTile.origin.x = 0.0f;
    NSLog(@"dest tile size: %f x %f",destTile.size.width, destTile.size.height);
    // the source seem overlap is proportionate to the destination seem overlap.
    // this is the amount of pixels to overlap each tile as we assemble the ouput image.
    float sourceSeemOverlap = (int)( ( destSeemOverlap / destResolution.height ) * sourceResolution.height );
    NSLog(@"dest seem overlap: %f, source seem overlap: %f",destSeemOverlap, sourceSeemOverlap);
    CGImageRef sourceTileImageRef;
    // calculate the number of read/write opertions required to assemble the
    // output image.
    int iterations = (int)( sourceResolution.height / sourceTile.size.height );
    // if tile height doesn't divide the image height evenly, add another iteration
    // to account for the remaining pixels.
    int remainder = (int)sourceResolution.height % (int)sourceTile.size.height;
    if( remainder ) iterations++;
    // add seem overlaps to the tiles, but save the original tile height for y coordinate calculations.
    float sourceTileHeightMinusOverlap = sourceTile.size.height;
    sourceTile.size.height += sourceSeemOverlap;
    destTile.size.height += destSeemOverlap;
    NSLog(@"beginning downsize. iterations: %d, tile height: %f, remainder height: %d", iterations, sourceTile.size.height,remainder );
    for( int y = 0; y < iterations; ++y ) {
        
        NSLog(@"iteration %d of %d",y+1,iterations);
        sourceTile.origin.y = y * sourceTileHeightMinusOverlap + sourceSeemOverlap;
        destTile.origin.y = ( destResolution.height ) - ( ( y + 1 ) * sourceTileHeightMinusOverlap * imageScale + destSeemOverlap );
        // create a reference to the source image with its context clipped to the argument rect.
        sourceTileImageRef = CGImageCreateWithImageInRect( sourceImage.CGImage, sourceTile );
        // if this is the last tile, it's size may be smaller than the source tile height.
        // adjust the dest tile size to account for that difference.
        if( y == iterations - 1 && remainder ) {
            float dify = destTile.size.height;
            destTile.size.height = CGImageGetHeight( sourceTileImageRef ) * imageScale;
            dify -= destTile.size.height;
            destTile.origin.y += dify;
        }
        // read and write a tile sized portion of pixels from the input image to the output image.
        CGContextDrawImage( destContext, destTile, sourceTileImageRef );
        /* release the source tile portion pixel data. note,
         releasing the sourceTileImageRef doesn't actually release the tile portion pixel
         data that we just drew, but the call afterward does. */
        CGImageRelease( sourceTileImageRef );
        /* while CGImageCreateWithImageInRect lazily loads just the image data defined by the argument rect,
         that data is finally decoded from disk to mem when CGContextDrawImage is called. sourceTileImageRef
         maintains internally a reference to the original image, and that original image both, houses and
         caches that portion of decoded mem. Thus the following call to release the source image. */
        
        // we reallocate the source image after the pool is drained since UIImage -imageNamed
        // returns us an autoreleased object.
        if( y < iterations - 1 ) {
            sourceImage = image;

            [self performSelectorOnMainThread:@selector(createImageFromContext) withObject:nil waitUntilDone:YES];
        }
    }
    NSLog(@"downsize complete.");
    //    [self performSelectorOnMainThread:@selector(initializeScrollView:) withObject:nil waitUntilDone:YES];
    // free the context since its job is done. destImageRef retains the pixel data now.
    CGContextRelease( destContext );
    
    return self.destImage;
}

-(void)createImageFromContext {
    // create a CGImage from the offscreen image context
    CGImageRef destImageRef = CGBitmapContextCreateImage( destContext );
    if( destImageRef == NULL ) NSLog(@"destImageRef is null.");
    // wrap a UIImage around the CGImage
    self.destImage = [UIImage imageWithCGImage:destImageRef scale:1.0f orientation:UIImageOrientationDownMirrored];
    // release ownership of the CGImage, since destImage retains ownership of the object now.
    CGImageRelease( destImageRef );
    if( self.destImage == nil ) NSLog(@"destImage is nil.");
}

@end

這段代碼只是改變了圖片的渲染方式档叔,利用GPU 進行渲染桌粉,有效降低內(nèi)存,不改變圖片的質(zhì)量衙四,親測加載24M圖片so easy铃肯,只占20多內(nèi)存
不能用于加載太小的圖片,只能用于加載大圖(大概1M以上)

最近看了這篇文章http://www.reibang.com/p/1c9de8dea3ea
導(dǎo)致加載大圖內(nèi)存暴漲的原因是對大圖的解壓縮加載传蹈。
在SDWebImage中大圖禁用解壓縮押逼,可以防止內(nèi)存暴漲:

[[SDImageCache sharedImageCache] setShouldDecompressImages:NO];
[[SDWebImageDownloader sharedDownloader] setShouldDecompressImages:NO];

測試只有iPhone7步藕,7p,SE,有用,其他機型不起作用挑格,和系統(tǒng)版本沒有關(guān)系

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末咙冗,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子漂彤,更是在濱河造成了極大的恐慌雾消,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,525評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件挫望,死亡現(xiàn)場離奇詭異立润,居然都是意外死亡,警方通過查閱死者的電腦和手機媳板,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評論 3 395
  • 文/潘曉璐 我一進店門桑腮,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人蛉幸,你說我怎么就攤上這事破讨。” “怎么了奕纫?”我有些...
    開封第一講書人閱讀 164,862評論 0 354
  • 文/不壞的土叔 我叫張陵添忘,是天一觀的道長。 經(jīng)常有香客問我若锁,道長搁骑,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,728評論 1 294
  • 正文 為了忘掉前任又固,我火速辦了婚禮仲器,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘仰冠。我一直安慰自己乏冀,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,743評論 6 392
  • 文/花漫 我一把揭開白布洋只。 她就那樣靜靜地躺著辆沦,像睡著了一般。 火紅的嫁衣襯著肌膚如雪识虚。 梳的紋絲不亂的頭發(fā)上肢扯,一...
    開封第一講書人閱讀 51,590評論 1 305
  • 那天,我揣著相機與錄音担锤,去河邊找鬼蔚晨。 笑死,一個胖子當(dāng)著我的面吹牛肛循,可吹牛的內(nèi)容都是我干的铭腕。 我是一名探鬼主播银择,決...
    沈念sama閱讀 40,330評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼累舷!你這毒婦竟也來了浩考?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,244評論 0 276
  • 序言:老撾萬榮一對情侶失蹤被盈,失蹤者是張志新(化名)和其女友劉穎怀挠,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體害捕,經(jīng)...
    沈念sama閱讀 45,693評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡绿淋,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,885評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了尝盼。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片吞滞。...
    茶點故事閱讀 40,001評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖盾沫,靈堂內(nèi)的尸體忽然破棺而出裁赠,到底是詐尸還是另有隱情,我是刑警寧澤赴精,帶...
    沈念sama閱讀 35,723評論 5 346
  • 正文 年R本政府宣布佩捞,位于F島的核電站,受9級特大地震影響蕾哟,放射性物質(zhì)發(fā)生泄漏一忱。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,343評論 3 330
  • 文/蒙蒙 一谭确、第九天 我趴在偏房一處隱蔽的房頂上張望帘营。 院中可真熱鬧,春花似錦逐哈、人聲如沸芬迄。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽禀梳。三九已至,卻和暖如春肠骆,著一層夾襖步出監(jiān)牢的瞬間算途,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評論 1 270
  • 我被黑心中介騙來泰國打工哗戈, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留郊艘,地道東北人荷科。 一個月前我還...
    沈念sama閱讀 48,191評論 3 370
  • 正文 我出身青樓唯咬,卻偏偏與公主長得像纱注,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子胆胰,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,955評論 2 355

推薦閱讀更多精彩內(nèi)容