我希望在将图像存储为NSData
对象之前压缩图像。
下面是代码,它可以帮助我获取图像的NSData
对象。
NSURL *referenceURL = [info objectForKey:UIImagePickerControllerReferenceURL];
ALAssetsLibrary *library1 = [[ALAssetsLibrary alloc] init];
[library1 assetForURL:referenceURL resultBlock:^(ALAsset *asset)
{
int byteArraySize = asset.defaultRepresentation.size;
NSMutableData* rawData = [[NSMutableData alloc]initWithCapacity:byteArraySize];
void* bufferPointer = [rawData mutableBytes];
NSError* error=nil;
[asset.defaultRepresentation getBytes:bufferPointer fromOffset:0 length:byteArraySize error:&error];
if (error) {
NSLog(@"%@",error);
}
rawData = [NSMutableData dataWithBytes:bufferPointer length:byteArraySize];
}
任何帮助将不胜感激。
答案 0 :(得分:6)
UIImagePickerController会返回压缩图像,但您也可以使用此内置的UIKit函数和PNG的相关函数来控制格式和压缩:
NSData* UIImageJPEGRepresentation(UIImage *image, CGFloat compressionQuality);
如果referenceURL返回一个字符串,您可能需要创建一个NSURL。
NSImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL: referenceURL]];
NSData *compressedImage = UIImageJPEGRepresentation(image, .1); //.1 is low quality
答案 1 :(得分:1)
如果您正在使用UIImagePickerController,则返回的图像将是JPEG,已经压缩(我认为)。如果没有,您可以使用AVAssetWriter将图像写为JPEG或PNG。
答案 2 :(得分:0)
简单易用: -
-(UIImage *)fireYourImageForCompression:(UIImage *)imgComing{
NSData *dataImgBefore = [[NSData alloc] initWithData:UIImageJPEGRepresentation((imgComing), 1.0)];//.1 BEFORE COMPRESSION
int imageSizeBefore = (int)dataImgBefore.length;
NSLog(@"SIZE OF IMAGE: %i ", imageSizeBefore);
NSLog(@"SIZE OF IMAGE in Kb: %i ", imageSizeBefore/1024);
NSData *dataCompressedImage = UIImageJPEGRepresentation(imgComing, .1); //.1 is low quality
int sizeCompressedImage = (int)dataCompressedImage.length;
NSLog(@"SIZE AFTER COMPRESSION OF IMAGE: %i ", sizeCompressedImage);
NSLog(@"SIZE AFTER COMPRESSION OF IMAGE in Kb: %i ", sizeCompressedImage/1024); //AFTER
//now change your image from compressed data
imgComing = [UIImage imageWithData:dataCompressedImage];
return imgComing;}