UIImage一些扩展(获取视频第一帧、色值转图片、base64
下面的都是类方法
pragma mark ---- 获取图片第一帧
-
(UIImage*) JJthumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
NSParameterAssert(asset);
AVAssetImageGenerator *assetImageGenerator =[[AVAssetImageGenerator alloc] initWithAsset:asset];
assetImageGenerator.appliesPreferredTrackTransform = YES;
assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;CGImageRef thumbnailImageRef = NULL;
CFTimeInterval thumbnailImageTime = time;
NSError thumbnailImageGenerationError = nil;
thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)actualTime:NULL error:&thumbnailImageGenerationError];
if(!thumbnailImageRef)
NSLog(@"thumbnailImageGenerationError %@",thumbnailImageGenerationError);
UIImagethumbnailImage = thumbnailImageRef ? [[UIImage alloc]initWithCGImage: thumbnailImageRef] : nil;
return thumbnailImage;
}
pragma mark ---- 色值转图片
-
(UIImage *)imageWithColor:(UIColor *)color withCenter:(UIImage *)centerImage size:(CGSize)size
{
UIView *background = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, size.width, size.height)];
[background setBackgroundColor:color];UIImageView *imageView = [[UIImageView alloc] initWithImage:centerImage];
[background addSubview:imageView];
imageView.center = background.center;// Render image
UIGraphicsBeginImageContextWithOptions(background.bounds.size, background.opaque, 0.0);
[background.layer renderInContext:UIGraphicsGetCurrentContext()];UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
pragma mark ---- base64字符串转图片
- (UIImage *)Base64StrToUIImage:(NSString *)encodedImageStr{
if (encodedImageStr.length==0) {
return nil;
}
NSData *decodedImageData = [[NSData alloc] initWithBase64EncodedString:encodedImageStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
UIImage *decodedImage = [UIImage imageWithData:decodedImageData];
return decodedImage;
}
pragma mark ---- 加载gif图
-
(UIImage *)loadGif_animatedGIFWithData:(NSData *)data {
if (!data) {
return nil;
}CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
size_t count = CGImageSourceGetCount(source);
UIImage *animatedImage;
if (count <= 1) {
animatedImage = [[UIImage alloc] initWithData:data];
}
else {
NSMutableArray *images = [NSMutableArray array];NSTimeInterval duration = 0.0f; for (size_t i = 0; i < count; i++) { CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL); duration += [self sd_frameDurationAtIndex:i source:source]; [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]]; CGImageRelease(image); } if (!duration) { duration = (1.0f / 10.0f) * count; } animatedImage = [UIImage animatedImageWithImages:images duration:duration];
}
CFRelease(source);
return animatedImage;
}