UIImage 占用內存大小

1、查看 AFNetworking 代碼,里面的估算方法是

CGSize imageSize = CGSizeMake(image.size.width * image.scale, image.size.height * image.scale);
    CGFloat bytesPerPixel = 4.0;
    CGFloat bytesPerRow = imageSize.width * bytesPerPixel; // 2560
    CGFloat totalBytes = (UInt64)bytesPerPixel * (UInt64)bytesPerRow;
    NSLog(@"s1:%lu",(unsigned long)totalBytes); // 輸出 10240

2、查看 CGImage 類,發現下面的方法:CGImageGetHeight和CGImageGetBytesPerRow。這樣計算應該更準確

CGFloat cgImageBytesPerRow = CGImageGetBytesPerRow(image.CGImage); // 2560
    CGFloat cgImageHeight = CGImageGetHeight(image.CGImage); // 1137
    NSUInteger size  = cgImageHeight * cgImageBytesPerRow;
    NSLog(@"size:%lu",(unsigned long)size); // 輸出 2910720

使用 Instruments 查看內存使用情況:


instrument.png

和輸出保持一致。

3、搜索 stack overflow ,參考這里

NSUInteger s1 = UIImagePNGRepresentation(thumbImage).length;
NSUInteger s2 = UIImageJPEGRepresentation(thumbImage, 1).length;
NSUInteger s3  = CGImageGetHeight(thumbImage.CGImage) * CGImageGetBytesPerRow(thumbImage.CGImage);
NSLog(@"s1:%u",s1); // s1 is the size of a .png image when saved to a file
NSLog(@"s2:%u",s2); // s2 is the size of a .jpg image when save to a file with best quality
NSLog(@"s3:%u",s3); // correct
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1.概述 對于 Java 的開發者來說,在虛擬機的自動內存管理機制的幫助下,不再需要為每一個 new 操作去寫配對...
    SawyerZh閱讀 3,209評論 3 81
  • 青蛙王子新編是送給女兒的童話。 她一直癡迷于童話故事,尤其中意帥氣的王子。看完了青蛙王子的故事之后,她指著故事書中...
    舒七七閱讀 802評論 0 0
  • 人生三大喜事,我正經歷著第二件——洞房花燭夜。 結婚是一件喜事,也是一件累人的事。談戀愛和結婚是兩回事,談戀愛說分...
    三兩水閱讀 464評論 0 1
  • 經常感覺一切就像一場夢 夢醒了 所有一切重新開始該多好 可是生活依舊繼續 卸下偽裝 或許我什么都不是 時間肆無忌憚...
    桂桃兒閱讀 198評論 0 1
  • 從幼年時起,書就悄悄地進入了我的生活,成為我生命中不缺少的一部分。打開塵封的記憶,時光開始倒流,我又回到了童...
    秋香伊人閱讀 436評論 0 0