如何在iphone中以jpg或png格式保存图像?

时间:2011-05-25 07:08:18

标签: objective-c uiimage

我从UIImageView拍摄图像,这个图像是我以编程方式创建的。现在我想在资源文件夹中以jpg或png格式保存此图像。任何人都知道如何以jpg或png格式保存图像?

提前致谢!

2 个答案:

答案 0 :(得分:14)

这应该有效:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *docs = [paths objectAtIndex:0];
NSString* path =  [docs stringByAppendingFormat:@"/image1.jpg"];

NSData* imageData = [NSData dataWithData:UIImageJPEGRepresentation(imageView.image, .8)];
NSError *writeError = nil;

if(![imageData writeToFile:path options:NSDataWritingAtomic error:&writeError]) {
    NSLog(@"%@: Error saving image: %@", [self class], [writeError localizedDescription]);
}

答案 1 :(得分:2)

小心。这行有一个错误:

UIImageJPEGRepresentation(imageView.image, 80)

如果查看标题,压缩质量应该是介于0(最有损)和1(最低压缩)之间的浮点数

UIKIT_EXTERN NSData *UIImageJPEGRepresentation(UIImage *image, CGFloat compressionQuality);  // return image as JPEG. May return nil if image has no CGImageRef or invalid bitmap format. compression is 0(most)..1(least)