iOS壓縮 gif 圖片

最近發(fā)現(xiàn)相冊可以直接存儲疆偿、瀏覽 gif,感覺蘋果開始注意 gif彼妻,所以總結一下自己的使用方法嫌佑。一般 gif 在內存比較大豆茫,在 cell 上展示會比較卡,所以做下壓縮還是很有必要的屋摇。查找很多資料也沒法下可以直接操作的 api揩魂,所有的壓縮原理似乎都是對 gif 的每幀圖片分別壓縮,然后再合成 gif炮温,所以我也是按照這個思路實現(xiàn)了一下火脉。下面直接上代碼:

+ (NSData *)scallGIFWithData:(NSData *)data scallSize:(CGSize)scallSize {
  if (!data) {
    return nil;
  }
  CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
  size_t count = CGImageSourceGetCount(source);
  
  // 設置 gif 文件屬性 (0:無限次循環(huán))
  NSDictionary *fileProperties = [self filePropertiesWithLoopCount:0];
  
  NSString *tempFile = [NSTemporaryDirectory() stringByAppendingString:@"scallTemp.gif"];
  NSFileManager *manager = [NSFileManager defaultManager];
  if ([manager fileExistsAtPath:tempFile]) {
    [manager removeItemAtPath:tempFile error:nil];
  }
  NSURL *fileUrl = [NSURL fileURLWithPath:tempFile];
  CGImageDestinationRef destination = CGImageDestinationCreateWithURL((__bridge CFURLRef)fileUrl, kUTTypeGIF , count, NULL);
  
  NSTimeInterval duration = 0.0f;
  for (size_t i = 0; i < count; i++) {
    CGImageRef imageRef = CGImageSourceCreateImageAtIndex(source, i, NULL);
    UIImage *image = [UIImage imageWithCGImage:imageRef];
    UIImage *scallImage = [self scallImageWidthScallSize:scallSize];
    
    NSTimeInterval delayTime = [self frameDurationAtIndex:i source:source];
    duration += delayTime;
    // 設置 gif 每針畫面屬性
    NSDictionary *frameProperties = [self framePropertiesWithDelayTime:delayTime];
    CGImageDestinationAddImage(destination, scallImage.CGImage, (CFDictionaryRef)frameProperties);
    CGImageRelease(imageRef);
  }
  CGImageDestinationSetProperties(destination, (CFDictionaryRef)fileProperties);
  // Finalize the GIF
  if (!CGImageDestinationFinalize(destination)) {
    NSLog(@"Failed to finalize GIF destination");
    if (destination != nil) {
      CFRelease(destination);
    }
    return nil;
  }
  CFRelease(destination);
  CFRelease(source);
  return [NSData dataWithContentsOfFile:tempFile];
}

按照 size 壓縮每幀圖片

- (UIImage *)scallImageWidthScallSize:(CGSize)scallSize{
  CGFloat width = self.size.width;
  CGFloat height = self.size.height;
  
  CGFloat scaleFactor = 0.0;
  CGFloat scaledWidth = scallSize.width;
  CGFloat scaledHeight = scallSize.height;
  CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
  
  if (!CGSizeEqualToSize(self.size, scallSize))
  {
    CGFloat widthFactor = scaledWidth / width;
    CGFloat heightFactor = scaledHeight / height;
    
    scaleFactor = MAX(widthFactor, heightFactor);
    
    scaledWidth= width * scaleFactor;
    scaledHeight = height * scaleFactor;
    
    // center the image
    if (widthFactor > heightFactor)
    {
      thumbnailPoint.y = (scallSize.height - scaledHeight) * 0.5;
    }
    else if (widthFactor < heightFactor)
    {
      thumbnailPoint.x = (scallSize.width - scaledWidth) * 0.5;
    }
  }
  CGRect rect;
  rect.origin = thumbnailPoint;
  rect.size = CGSizeMake(scaledWidth, scaledHeight);
  UIGraphicsBeginImageContext(rect.size);
  [self drawInRect:rect];
  UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return  image;
}

讀取幀率

+ (float)frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source {
  float frameDuration = 0.1f;
  CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil);
  NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties;
  NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary];
  
  NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime];
  if (delayTimeUnclampedProp) {
    frameDuration = [delayTimeUnclampedProp floatValue];
  }
  else {
    
    NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime];
    if (delayTimeProp) {
      frameDuration = [delayTimeProp floatValue];
    }
  }

  if (frameDuration < 0.011f) {
    frameDuration = 0.100f;
  }
  CFRelease(cfFrameProperties);
  frameDuration += 0.1;
  return frameDuration;
}

合成新的 gif, 設置播放屬性

+ (NSDictionary *)filePropertiesWithLoopCount:(int)loopCount {
  return @{(NSString *)kCGImagePropertyGIFDictionary:
             @{(NSString *)kCGImagePropertyGIFLoopCount: @(loopCount)}
           };
}

+ (NSDictionary *)framePropertiesWithDelayTime:(NSTimeInterval)delayTime {
  
  return @{(NSString *)kCGImagePropertyGIFDictionary:
             @{(NSString *)kCGImagePropertyGIFDelayTime: @(delayTime)},
           (NSString *)kCGImagePropertyColorModel:(NSString *)kCGImagePropertyColorModelRGB
           };
}

demo

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末柒啤,一起剝皮案震驚了整個濱河市倦挂,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌担巩,老刑警劉巖方援,帶你破解...
    沈念sama閱讀 216,692評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異涛癌,居然都是意外死亡犯戏,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,482評論 3 392
  • 文/潘曉璐 我一進店門拳话,熙熙樓的掌柜王于貴愁眉苦臉地迎上來先匪,“玉大人,你說我怎么就攤上這事弃衍⊙椒牵” “怎么了?”我有些...
    開封第一講書人閱讀 162,995評論 0 353
  • 文/不壞的土叔 我叫張陵笨鸡,是天一觀的道長姜钳。 經(jīng)常有香客問我,道長形耗,這世上最難降的妖魔是什么哥桥? 我笑而不...
    開封第一講書人閱讀 58,223評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮激涤,結果婚禮上拟糕,老公的妹妹穿的比我還像新娘。我一直安慰自己倦踢,他們只是感情好送滞,可當我...
    茶點故事閱讀 67,245評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著辱挥,像睡著了一般犁嗅。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上晤碘,一...
    開封第一講書人閱讀 51,208評論 1 299
  • 那天褂微,我揣著相機與錄音功蜓,去河邊找鬼。 笑死宠蚂,一個胖子當著我的面吹牛式撼,可吹牛的內容都是我干的。 我是一名探鬼主播求厕,決...
    沈念sama閱讀 40,091評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼著隆,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了呀癣?” 一聲冷哼從身側響起美浦,我...
    開封第一講書人閱讀 38,929評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎十艾,沒想到半個月后抵代,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體腾节,經(jīng)...
    沈念sama閱讀 45,346評論 1 311
  • 正文 獨居荒郊野嶺守林人離奇死亡忘嫉,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,570評論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了案腺。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片庆冕。...
    茶點故事閱讀 39,739評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖劈榨,靈堂內的尸體忽然破棺而出访递,到底是詐尸還是另有隱情,我是刑警寧澤同辣,帶...
    沈念sama閱讀 35,437評論 5 344
  • 正文 年R本政府宣布拷姿,位于F島的核電站,受9級特大地震影響旱函,放射性物質發(fā)生泄漏响巢。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,037評論 3 326
  • 文/蒙蒙 一棒妨、第九天 我趴在偏房一處隱蔽的房頂上張望踪古。 院中可真熱鬧,春花似錦券腔、人聲如沸伏穆。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,677評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽枕扫。三九已至,卻和暖如春辱魁,著一層夾襖步出監(jiān)牢的瞬間烟瞧,已是汗流浹背偷厦。 一陣腳步聲響...
    開封第一講書人閱讀 32,833評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留燕刻,地道東北人只泼。 一個月前我還...
    沈念sama閱讀 47,760評論 2 369
  • 正文 我出身青樓,卻偏偏與公主長得像卵洗,于是被迫代替她去往敵國和親请唱。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,647評論 2 354

推薦閱讀更多精彩內容

  • 1过蹂、通過CocoaPods安裝項目名稱項目信息 AFNetworking網(wǎng)絡請求組件 FMDB本地數(shù)據(jù)庫組件 SD...
    陽明先生_X自主閱讀 15,979評論 3 119
  • 媽媽十绑,早上好哇。 趁著臨近母親節(jié)之際酷勺,有些話我想寫著送給你”境龋現(xiàn)在你也找到了自己的工作啦,比起以前在家里帶著我們脆诉,是...
    careful_beb2閱讀 154評論 0 0
  • 2018年11.23 星期五 晴6° 文/辣條臉 親愛的辣條: 嘿甚亭,早上好,想跟你說的是击胜,我又迷迷糊...
    辣條臉XX閱讀 336評論 4 2
  • 雨鞋是個怎樣的存在? 雨鞋是個無敵的存在亏狰。 曾經(jīng)我也有一雙屬于自己的雨鞋,可是偶摔,卻早已將它遺忘在記憶的某個角落暇唾。此...
    沐梓茜閱讀 327評論 0 0