如何压缩iPhone中的图像?

nid*_*ids 3 iphone objective-c

我从照片库中拍摄图像.我有4-5 mb的大图像,但我想压缩这些图像.因为我需要将这些图像存储在iphone的本地存储器中.因为使用更少的内存或获得更少的内存警告我需要压缩这些图像.

我不知道如何压缩图像和视频.所以我想知道热压缩图像?

    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

    NSData* data = UIImageJPEGRepresentation(image,1.0);
    NSLog(@"found an image");

    NSString *path = [destinationPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpeg", name]];
    [data writeToFile:path atomically:YES]; 
Run Code Online (Sandbox Code Playgroud)

这是保存图像的代码.我不想将整个图像存储得太大.所以,我想将它压缩到更小的尺寸,因为我需要附加多个图像.

谢谢回复.

joe*_*ick 12

您可以为JPEG编码选择较低的质量

NSData* data = UIImageJPEGRepresentation(image, 0.8);
Run Code Online (Sandbox Code Playgroud)

像0.8这样的东西不应该太明显,应该真正改善文件大小.

最重要的是,在使用如下方法进行JPEG表示之前,请先调整图像大小:

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return newImage;
}
Run Code Online (Sandbox Code Playgroud)

来源:调整UIImage大小的最简单方法是什么?


Krr*_*ish 5

UIImageJPEGRepresentation(UIImage的,质量);

1.0表示最高质量,0表示最低质量.

因此,请更改下面一行的质量参数,以减小图像的文件大小

NSData* data = UIImageJPEGRepresentation(image,1.0);
Run Code Online (Sandbox Code Playgroud)