记录iOS大图片压缩
2018-03-27 本文已影响18人
离人萧
以前使用drawInRect改变图片大小,小图片没有问题,大图片在老机型上可能会有内存问题。
前几天看了微信团队的分享,换一种方式,记录一下。
+(UIImage *)scaleALAsset:(ALAsset *)asset withSize:(CGSize)size{
ALAssetRepresentation *representation = [asset defaultRepresentation];
uint8_t *buffer = (Byte*)malloc(representation.size);
NSUInteger length = [representation getBytes:buffer fromOffset: 0.0 length:representation.size error:nil];
if (length) {
NSData *data = [[NSData alloc] initWithBytesNoCopy:buffer length:representation.size freeWhenDone:YES];
return [self scaledImageData:data withSize:size orientation:(UIImageOrientation)representation.orientation];
}
return nil;
}
+(UIImage *)scalePHAsset:(PHAsset *)asset withSize:(CGSize)size{
PHImageRequestOptions *options = [PHImageRequestOptions new];
options.version = PHImageRequestOptionsVersionCurrent;
options.resizeMode = PHImageRequestOptionsResizeModeNone;
options.synchronous = YES;
__block NSData *imageData;
__block UIImageOrientation orientation;
[[PHImageManager defaultManager] requestImageDataForAsset:asset
options: options
resultHandler:^( NSData * _Nullable imageData1,
NSString * _Nullable dataUTI,
UIImageOrientation orientation1,
NSDictionary * _Nullable info) {
imageData = imageData1;
orientation = orientation1;
}];
return [self scaledImageData:imageData withSize:size orientation:orientation];
}
+(UIImage *)scaledImageData:(NSData *)data withSize:(CGSize)size orientation:(UIImageOrientation)orientation{
CGImageSourceRef sourceRef = CGImageSourceCreateWithData((__bridge CFDataRef) data, nil);
CGFloat makePixelSize = MAX(size.width, size.height);
NSDictionary *options = @{
(__bridge id)kCGImageSourceCreateThumbnailFromImageAlways:(__bridge id)kCFBooleanTrue,
(__bridge id)kCGImageSourceThumbnailMaxPixelSize:[NSNumber numberWithFloat:makePixelSize]};
CGImageRef imageFef = CGImageSourceCreateThumbnailAtIndex(sourceRef,
0,
(__bridge CFDictionaryRef)options);
UIImage *resultImage = [UIImage imageWithCGImage:imageFef
scale:UIScreen.mainScreen.scale
orientation:orientation];
CGImageRelease(imageFef);
CFRelease(sourceRef);
return resultImage;
}