调整UIImage和imagePickerController的内存压力?

时间:2014-03-25 15:40:45

标签: ios objective-c uiimagepickercontroller image-compression

应用程序崩溃使用 imagePickerController 拍摄照片后 在这里,我试图从imagepickercontroller

旋转图像
- (void)imagePickerController:(UIImagePickerController *)picker1 didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *chosenImage = info[UIImagePickerControllerOriginalImage];
if (chosenImage.imageOrientation!= UIImageOrientationUp) {
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size,self.view.opaque,0.0);
        [chosenImage drawInRect:(CGRect){0, 0,chosenImage.size}];
    chosenImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

}
UIImage *imageToDisplay =chosenImage;
}

它提供了10 MB的图像。如何在Kbs中以非常小的图像压缩它?

2 个答案:

答案 0 :(得分:0)

只需使用这样的东西。

NSURL *url = info[UIImagePickerControllerReferenceURL];

ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset) {
     ALAssetRepresentation *rep = [myasset defaultRepresentation];
     CGImageRef imageRef = [rep fullResolutionImage];
     if (imageRef) {
// here is your image
        chosenImage = [UIImage imageWithCGImage:iref];
     }
};

ALAssetsLibraryAccessFailureBlock failureblock  = ^(NSError *error)
{
        NSLog(@"Error -> %@",[error localizedDescription]);
};

ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
        [assetslibrary assetForURL:url 
                       resultBlock:resultblock
                      failureBlock:failureblock];

或者你可以使用这样的代码

CGSize newSize = CGSizeMake(1000.0f, 1000.0f);
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

这将为您提供1000 * 1000像素的图像。

答案 1 :(得分:0)

我找到了压缩图像的解决方案

//Put this code in didfinish  UIimagepickercontroller
UIImage *chosenImage = info[UIImagePickerControllerOriginalImage];
NSData *imgData= UIImageJPEGRepresentation(chosenImage,0.1);//0.1 is loosy compression
UIImage *compressedImage=[UIImage imageWithData:imgData];
UIImage *resizedImage=[self imageWithImage:compressedImage scaledToSize:CGSizeMake(290, 390)];

下面的代码是调整图片大小

-(UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
//UIGraphicsBeginImageContext(newSize);
// In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account   for Retina resolution).
// Pass 1.0 to force exact pixel size.
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}