簡體   English   中英

如何將圖像保存在從iPhone中的UIGraphicsGetImageFromCurrentImageContext()捕獲的系統中?

[英]how to save the image in system which is captured from UIGraphicsGetImageFromCurrentImageContext() in iPhone?

嗨,我想將當前的UIView捕獲為圖像並將其存儲在本地硬盤中,我如何實現:

范例:

UIGraphicsBeginImageContext(self.superview.frame.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *backgroundImage = UIGraphicsGetImageFromCurrentImageContext();

我想以任何png,jpeg格式將UIImage存儲在本地驅動器中。

我該怎么做。 請幫我。 提前致謝。

將圖像存儲在App的Document文件夾中。

NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);

NSString *dir = [searchPaths lastObject];

NSString *imagePath = [dir stringByAppendingPathComponent:@"/image.png"];

NSData *dataImage=UIImageJPEGRepresentation(image, 0);

[dataImage writeToFile:imagePath atomically:YES];

以下代碼可以幫助您實現。

UIGraphicsBeginImageContext(self.superview.frame.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"New Folder"];
// New Folder is your folder name
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];

NSString *fileName = [stringPath stringByAppendingFormat:@"/image.jpg"];
NSData *data = UIImageJPEGRepresentation(image, 1.0);
[data writeToFile:fileName atomically:YES];

Apple提供了新的方法(方法):

- (UIImage *)snapshot:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSString  *imagePath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/capturedImage.jpg"]];
    [UIImageJPEGRepresentation(image, 0.95) writeToFile:imagePath atomically:YES];

    return image;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM