如何减lessiPhone objective-c中的图像质量/尺寸?

我有一个应用程序,让用户使用他/她的iPhone拍照,并将其用作应用程序的背景图像。 我使用UIImagePickerController让用户拍照并将背景UIImageView图像设置为返回的UIImage对象。

 IBOutlet UIImageView *backgroundView; -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo { backgroundView.image = image; [self dismissModalViewControllerAnimated:YES]; } 

这一切工作正常。 我怎样才能减lessUIImage的大小为480×320,所以我的应用程序可以提高内存效率? 我不在乎是否失去任何图像质量。

提前致谢。

您可以创build一个graphics上下文,以所需的比例绘制图像,并使用返回的图像。 例如:

 UIGraphicsBeginImageContext(CGSizeMake(480,320)); CGContextRef context = UIGraphicsGetCurrentContext(); [image drawInRect: CGRectMake(0, 0, 480, 320)]; UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); 

我知道这个问题已经解决了,但是如果有人(像我这样)想要保持高宽比的形象,这个代码可能会有所帮助:

 -(UIImage *)resizeImage:(UIImage *)image toSize:(CGSize)size { float width = size.width; float height = size.height; UIGraphicsBeginImageContext(size); CGRect rect = CGRectMake(0, 0, width, height); float widthRatio = image.size.width / width; float heightRatio = image.size.height / height; float divisor = widthRatio > heightRatio ? widthRatio : heightRatio; width = image.size.width / divisor; height = image.size.height / divisor; rect.size.width = width; rect.size.height = height; if(height < width) rect.origin.y = height / 3; [image drawInRect: rect]; UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return smallImage; } 

使用contentOfFile并确保所有的图像都是.png。 苹果是为png优化的。

哦,使用contentOfFile而不是imageName方法。 有几个原因。 即使在调用[release]之后,由ImageName引入的内存仍保留在内存中。

不要问我为什么。 苹果告诉了我。

Roydell Clarke