我有一个名为“保存到相册”的保存按钮。按钮顶部是小UIImageView,用户可以点击下面的按钮将照片的实际尺寸保存到相册。我的问题是当我点击保存按钮时,它显示一个错误:无法将图像保存到相册。
我认为我做得对,但我的经验太有限了。
H档:
#import <UIKit/UIKit.h>
@interface SecondViewController : UIViewController {
IBOutlet UIButton *btnReturn;
IBOutlet UIButton *savePhoto;
IBOutlet UIImage *saveImage;
}
@property (nonatomic, retain) IBOutlet UIButton *btnReturn;
@property (nonatomic, retain) IBOutlet UIButton *savePhoto;
@property (nonatomic, retain) IBOutlet UIImage *saveImage;
-(IBAction) saveToPhotoAlbum;
@end
以下是我的代码:
-(IBAction) saveToPhotoAlbum{
NSString *saveMyPhoto=[NSHomeDirectory() stringByAppendingPathComponent:@"sample.png"];
UIImage *saved=[UIImage imageWithContentsOfFile:saveMyPhoto];
NSData *imageData = [NSData dataWithContentsOfFile:(NSString *)UIImagePNGRepresentation(saved)];
[imageData writeToFile:(NSString *)saved atomically:YES ];
UIImageWriteToSavedPhotosAlbum(saved, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
UIAlertView *alert;
if (error)
alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:@"Unable to save image to Photo Album."
delegate:self cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
else
alert = [[UIAlertView alloc] initWithTitle:@"Success"
message:@"Image saved to Photo Album."
delegate:self cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alert show];
[alert release];
}
答案 0 :(得分:1)
只需创建一个UIImage对象并从文件加载图像。然后只需调用UIIMageWriteToSavedPhotoAlbum函数并将UIImage对象作为第一个参数传递,然后其余部分都可以为NIL。请参阅Apple SDK documentation.
答案 1 :(得分:0)
这些线看起来真的很可疑:
NSString *saveMyPhoto=[NSHomeDirectory() stringByAppendingPathComponent:@"sample.png"];
...
UIImage *saved = [UIImage imageWithContentsOfFile:saveMyPhoto];
...
[imageData writeToFile:(NSString *)saved atomically:YES ];
你有什么期望这样做?你得到一个图像的路径,加载它,然后再次保存它,但你已经将UIImage转换为NSString并希望它会神奇地变成磁盘上的有效路径?
至于你问的问题,你确定你的图像是有效的图像吗?