最近在用ALAsset获取相册时候,ALAsset的ALAssetRepresentation只提供了全尺寸图、全屏幕图、metadata等,但是将这些转换成NSData的时候,尺寸都不精确,不是变大了就是变小了。后来一想,不如直接由ALAsset转换成NSData,再由NSData转换成UIImage,后来一试试,真的可以了,而且图片的尺寸还是原来的尺寸。下面把代码贴上
/** * ALAsset 直接转换为UIImage * * @param asset * * @return UIImage */ - (UIImage *)assetToImageForALAsset:(ALAsset *)asset{ UIImage *tempImg = nil; ALAssetRepresentation *image_representation = [asset defaultRepresentation]; Byte *buffer = (Byte*)malloc(image_representation.size); NSUInteger length = [image_representation getBytes:buffer fromOffset: 0.0 length:image_representation.size error:nil]; if (length != 0) { NSData *adata = [[NSData alloc] initWithBytesNoCopy:buffer length:image_representation.size freeWhenDone:YES]; tempImg = [UIImage imageWithData:adata]; } return tempImg; }
//保存成jpg,图片会小一些
BOOL result = [UIImageJPEGRepresentation(image, 1.0) writeToFile:filePath atomically:YES];