在iPhone上使用文件名保存图像的UIImage

13

我该如何将一张图片(类似使用UIImageWriteToSavedPhotosAlbum()方法)以我选择的文件名保存到private/var文件夹中?

3个回答

17

Kenny,你回答正确了!为了说明问题,我认为代码更有帮助。

//I do this in the didFinishPickingImage:(UIImage *)img method

NSData* imageData = UIImageJPEGRepresentation(img, 1.0);


//save to the default 100Apple(Camera Roll) folder.   

[imageData writeToFile:@"/private/var/mobile/Media/DCIM/100APPLE/customImageFilename.jpg" atomically:NO]; 

2
一个将样本保存到文档文件夹的示例 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *filePath2 = [NSString stringWithFormat:@"%@/%@.jpg", documentsDirectory, fileName];NSData* imageData = UIImageJPEGRepresentation(drawImage.image, 1.0); [imageData writeToFile:filePath2 atomically:NO]; - Robert Childan
[imageData writeToFile:@"/private/var/mobile/Media/DCIM/100APPLE/customImageFilename.jpg" atomically:NO]; 这个/private/var/mobile文件夹是什么? 在iOS中,这是一个标准的写出文件的位置吗? - user798719
3
问题是,如果苹果公司允许一个包含这段代码的应用程序……http://stackoverflow.com/questions/2884003/will-the-app-get-rejected-if-you-write-image-to-private-var-mobile-media-dcim-1?lq=1 - Chris
这还允许吗?好像不是我有写入权限的文件路径。 - James Bedford

10

UIImageWriteToSavedPhotosAlbum()仅用于保存在照片相机胶卷中。如果要保存到自定义文件夹,则需要使用UIImageJPEGRepresentation()UIImagePNGRepresentation()将UIImage转换为NSData,然后将此NSData保存到任何您喜欢的地方。


0

您可以使用以下代码,而无需使用ALAssetsLibrary...

NSString *fileName;

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissViewControllerAnimated:YES completion:^{

if( [picker sourceType] == UIImagePickerControllerSourceTypeCamera )
            {
                UIImageWriteToSavedPhotosAlbum(image,nil, nil, nil);
                [self performSelector:@selector(GetImageName) withObject:nil afterDelay:0.5];
            }
            else
            {
                NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];
                PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:@[refURL] options:nil];
                fileName = [[result firstObject] filename];
            }
}];

-(void)GetImageName
{
 NSString *str =@"";
 PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
 fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
 PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];

if (fetchResult != nil && fetchResult.count > 0) {

    str = [[fetchResult lastObject] filename];
}

fileName = str;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接