【IOS】讀取、保存圖片的各種方法


一.讀取圖片

1.從資源(resource)讀取
1 UIImage* image=[UIImage imageNamed:@"1.jpg"]; 

 

2.從網絡讀取【最好使用EGOImageView來獲取網絡圖片】
1 NSURL *url=[NSURL URLWithString:@"http://www.sinaimg.cn/qc/photo_auto/chezhan/2012/50/00/15/80046_950.jpg"];  
2 UIImage *imgFromUrl =[[UIImage alloc]initWithData:[NSData dataWithContentsOfURL:url]]; 

 

3.從手機本地讀取
1 //讀取本地圖片非resource  
2 NSString *aPath3=[NSString stringWithFormat:@"%@/Documents/%@.jpg",NSHomeDirectory(),@"test"];  
3 UIImage *imgFromUrl3=[[UIImage alloc]initWithContentsOfFile:aPath3];  
4 UIImageView* imageView3=[[UIImageView alloc]initWithImage:imgFromUrl3];  

 

 
4.從現有的context中獲得圖像
 
 1 //add ImageIO.framework and #import     
 2 CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)url, NULL);  
 3 CGImageRef img= CGImageSourceCreateImageAtIndex(source,0,NULL);  
 4 CGContextRef ctx=UIGraphicsGetCurrentContext();  
 5 CGContextSaveGState(ctx);  
 6 //transformCTM的2種方式  
 7 //CGContextConcatCTM(ctx, CGAffineTransformMakeScale(.2, -0.2));  
 8 //CGContextScaleCTM(ctx,1,-1);  
 9 //注意坐標要反下,用ctx來作為圖片源   
10 CGImageRef capture=CGBitmapContextCreateImage(ctx);  
11 CGContextDrawImage(ctx, CGRectMake(160, 0, 160, 230), [image CGImage]);  
12 CGContextDrawImage(ctx, CGRectMake(160, 230, 160, 230), img);  
13 CGImageRef capture2=CGBitmapContextCreateImage(ctx);  

 

5.用Quartz的CGImageSourceRef來讀取圖片
1 CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)url, NULL);  
2 CGImageRef img= CGImageSourceCreateImageAtIndex(source,0,NULL);  

 

二.保存圖片
1.轉換成NSData來保存圖片(imgFromUrl是UIImage)
1 //保存圖片 2種獲取路徑都可以  
2 //NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
3 //NSString*documentsDirectory=[paths objectAtIndex:0];    
4 //NSString*aPath=[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg",@"test"]];   
5 NSString *aPath=[NSString stringWithFormat:@"%@/Documents/%@.jpg",NSHomeDirectory(),@"test"];  
6 NSData *imgData = UIImageJPEGRepresentation(imgFromUrl,0);      
7 [imgData writeToFile:aPath atomically:YES];

 

用UIImageWriteToSavedPhotosAlbum往照片庫里面存圖片時,經常發生縮略圖能看到但原圖消失的問題

用 UIImageWriteToSavedPhotosAlbum(imageSave, nil, nil, nil), imageSave是UIImage類型,這樣就保存進去了。
而且注意圖片不宜過大,以免程序崩潰
【將圖片保存在手機相冊中】
UIImageWriteToSavedPhotosAlbum(imgView.image,nil,nil,nil);


保存圖片拓展:有時候應用可能被手機禁止訪問相冊,導致圖片保存失敗

應用中有時我們會有保存圖片的需求,如利用UIImagePickerController用IOS設備內置的相機拍照,或是有時我們在應用程序中利用UIKit的 UIGraphicsBeginImageContext,UIGraphicsEndImageContext,UIGraphicsGetImageFromCurrentImageContext方法創建一張圖像需要進行保存。
IOS的UIKit Framework提供了UIImageWriteToSavedPhotosAlbum方法對圖像進行保存,該方法會將image保存至用戶的相冊中,描述如下: 
 1 void UIImageWriteToSavedPhotosAlbum (
 2    UIImage  *image,
 3    id       completionTarget,
 4    SEL      completionSelector,
 5    void     *contextInfo
 6 );
 7 參數說明: 
 8         image 
 9             帶保存的圖片UImage對象 
10         completionTarget 
11             圖像保存至相冊后調用completionTarget指定的selector(可選) 
12         completionSelector 
13                 completionTarget的方法對應的選擇器,相當於回調方法,需滿足以下格式 
14 
15 - (void) image: (UIImage *) image
16 didFinishSavingWithError: (NSError *) error
17                 contextInfo: (void *) contextInfo; 

 

contextInfo指定了在回調中可選擇傳入的數據。 

當我們需要異步獲得圖像保存結果的消息時,我們需要指定completionTarget對象以及其completionSelector對應的選擇器。示例如下:   

 1 - (void)saveImageToPhotos:(UIImage*)savedImage 
 2 {
 3     UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);    
 4 }
 5 // 指定回調方法
 6 - (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
 7 {   
 8     NSString *msg = nil ;    
 9     if(error != NULL){
10         msg = @"保存圖片失敗" ;
11     }else{
12         msg = @"保存圖片成功" ;
13     }
14     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存圖片結果提示"
15                                                         message:msg
16                                                        delegate:self
17                                               cancelButtonTitle:@"確定"
18                                               otherButtonTitles:nil];
19     [alert show];
20 }
21 
22 // 調用示例
23 UIImage *savedImage = [UIImage imageNamed:"savedImage.png"];
24 
25 [self saveImageToPhotos:savedImage];
2.用Quartz的CGImageDestinationRef來輸出圖片,這個方式不常見,所以不做介紹,詳細可以看apple文檔Quartz 2D Programming Guide

三.繪制圖(draw|painting)

1.UIImageView方式加入到UIView層
1 UIImageView* imageView=[[UIImageView alloc]initWithImage:image];  
2 imageView.frame=CGRectMake(0, 0, 320, 480);  
3 [self addSubview:imageView];  
4 [imageView release];  

 

2.[img drawAtPoint]系列方法
1 [image4 drawAtPoint:CGPointMake(100, 0)];    

 

 
3.CGContextDrawImage
1 CGContextDrawImage(ctx, CGRectMake(160, 0, 160, 230), [image CGImage]); 

 


4.CGLayer
這個是apple推薦的一種offscreen的繪制方法,相比bitmapContext更好,因為它似乎會利用iphone硬件(drawing-card)加速
1 CGLayerRef cg=CGLayerCreateWithContext(ctx, CGSizeMake(320, 480), NULL);  
2 //需要將CGLayerContext來作為緩存context,這個是必須的  
3 CGContextRef layerContext=CGLayerGetContext(cg);  
4 CGContextDrawImage(layerContext, CGRectMake(160, 230, 160, 230), img);   
5 CGContextDrawLayerAtPoint(ctx, CGPointMake(0, 0), cg);  

 

5.CALayer的contents
1 UIImage* image=[UIImage imageNamed:@"1.jpg"];  
2 CALayer *ly=[CALayer layer];  
3 ly.frame=CGRectMake(0, 0, 320, 460);  
4 ly.contents=[image CGImage];  
5 [self.layer addSublayer:ly];  

 

四.其它

1.CGImage和UIImage互換
這樣就可以隨時切換UIKit和Quartz之間類型,並且選擇您熟悉的方式來處理圖片.
1 CGImage cgImage=[uiImage CGImage];
2 UIImage* uiImage=[UIImage imageWithCGImage:cgImage];

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM