zoukankan      html  css  js  c++  java
  • 从摄像头/相册获取图片,压缩图片,上传服务器小结

    iphone中图像通常存储在4个地方【相册、应用程序包、沙盒、Internet】,通过这4个源,我们就可以存取应用图片。

    • 相册

        iphone的相册包含摄像头胶卷+用户计算机同步的部分照片。用户可以通过UIImagePickerController类提供的交互对话框来从相册中选择图像。但是,注意:相册中的图片机器路径无法直接从应用程序访问,只能通过终端用户去选择和使用相册图片

    • 应用程序包

        应用程序包可能会将图像与可执行程序、Info.plist文件和其他资源一同存储。我们可以通过本地文件路径来读取这些基于包的图像并在应用程序中显示它们。

    • 沙盒

        借助沙盒,我们可以把图片存储到Documents、Library、tmp文件夹中。这些文件均可有应用程序读取,且可以通过文件路径创建图像。尽管沙盒外的部分从技术上说是可行的,但是apple表明这些部分不在appstore应用程序允许访问的范围之内。

    • Internet

        应用程序可以通过图片的URL来访问Internet上的资源。

    以上为一些小知识,来自《iphone开发秘籍(第二版)》,可以自己去参考此书。

    下面开始切入正题,从摄像头/相册获取图片,压缩图片,上传图片。

    • 从摄像头/相册获取图片

        刚刚在上面的知识中提到从摄像头/相册获取图片是面向终端用户的,由用户去浏览并选择图片为程序使用。在这里,我们需要过UIImagePickerController类来和用户交互。

        使用UIImagePickerController和用户交互,我们需要实现2个协议<UIImagePickerControllerDelegate,UINavigationControllerDelegate>。

    View Code
    复制代码
    #pragma mark 从用户相册获取活动图片
    - (void)pickImageFromAlbum
    {
        imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        imagePicker.allowsEditing = YES;
        
        [self presentModalViewController:imagePicker animated:YES];
    }
    复制代码

        我们来看看上面的从相册获取图片,我们首先要实例化UIImagePickerController对象,然后设置imagePicker对象为当前对象,设置imagePicker的图片来源为UIImagePickerControllerSourceTypePhotoLibrary,表明当前图片的来源为相册,除此之外还可以设置用户对图片是否可编辑。

    View Code
    复制代码
    #pragma mark 从摄像头获取活动图片
    - (void)pickImageFromCamera
    {
        imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        imagePicker.allowsEditing = YES;
        // 用模式窗体转换到图片选取界面
        [self presentModalViewController:imagePicker animated:YES];
    }
    复制代码

        以上是从摄像头获取图片,和从相册获取图片只是图片来源的设置不一样,摄像头图片的来源为UIImagePickerControllerSourceTypeCamera

        在和用户交互之后,用户选择好图片后,会回调选择结束的方法。

     

    View Code
    复制代码
    - (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
    {
        UIImage *image= [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) 
        {
    //        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
        }
        theImage = [UtilMethod imageWithImageSimple:image scaledToSize:CGSizeMake(120.0, 120.0)];
        UIImage *midImage = [UtilMethod imageWithImageSimple:image scaledToSize:CGSizeMake(210.0, 210.0)];
        UIImage *bigImage = [UtilMethod imageWithImageSimple:image scaledToSize:CGSizeMake(440.0, 440.0)];
        [theImage retain];
        [self saveImage:theImage WithName:@"salesImageSmall.jpg"];
        [self saveImage:midImage WithName:@"salesImageMid.jpg"];
        [self saveImage:bigImage WithName:@"salesImageBig.jpg"];
        
        [self dismissModalViewControllerAnimated:YES];
        [self refreshData];
        [picker release];
    }
    复制代码

     

        在回调结束的方法中,我们对图片进行了大小的处理,为图片的上传做准备。

    • 缩放图片

        缩放图片比较简单,就直接放上代码,让大家参考一下。

    View Code
    复制代码
    //压缩图片
    + (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
    {
        // Create a graphics image context
        UIGraphicsBeginImageContext(newSize);
        
        // Tell the old image to draw in this new context, with the desired
        // new size
        [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
        
        // Get the new image from the context
        UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
        
        // End the context
        UIGraphicsEndImageContext();
        
        // Return the new image.
        return newImage;
    }
    复制代码
    • 存储图像

        在上面我们获取到了图片并对图片进行了压缩,通过之前的小知识了解到,将应用需要的一些图片存入沙盒是个不错的选择,而且应用程序可以直接通过路径去方法沙盒中的图片,在这里我们将图片存入沙盒中的Documents目录下。

    View Code
    复制代码
    #pragma mark 保存图片到document
    - (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName
    {
        NSData* imageData = UIImagePNGRepresentation(tempImage);
        NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString* documentsDirectory = [paths objectAtIndex:0];
        // Now we get the full path to the file
        NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
        // and then we write it out
        [imageData writeToFile:fullPathToFile atomically:NO];
    }
    复制代码
    • 从Documents目录下获取图片

        要从Documents下面获取图片,我们首先需要获取Documents目录的路径。

    View Code
    #pragma mark 从文档目录下获取Documents路径
    - (NSString *)documentFolderPath
    {
        return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    }

        然后,我们便可以通过文件名,去访问获取资源了。

    View Code
    • 上传图片

        项目中我们使用了ASIFormHttpRequest的开源框架,http请求的部分代码如下,http返回以及相关回调方法略去。

    View Code
    复制代码
    - (void)upLoadSalesBigImage:(NSString *)bigImage MidImage:(NSString *)midImage SmallImage:(NSString *)smallImage
    {
        NSURL *url = [NSURL URLWithString:UPLOAD_SERVER_URL];
        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
        [request setPostValue:@"photo" forKey:@"type"];
        [request setFile:bigImage forKey:@"file_pic_big"];
        [request buildPostBody];
        [request setDelegate:self];
        [request setTimeOutSeconds:TIME_OUT_SECONDS];
        [request startAsynchronous]; 
    }
    复制代码

     

    到现在为止,我们已经完成了从摄像头/相册获取图像、存储图像、压缩图像、上传图像。呵呵,很简单吧,由于之前在网上没有找到多少可用的,所以在此记录一下,希望给其他人一些借鉴

     

    在Iphone上有两种读取图片数据的简单方法: UIImageJPEGRepresentation和UIImagePNGRepresentation. 
    UIImageJPEGRepresentation函数需要两个参数:图片的引用和压缩系数.而UIImagePNGRepresentation只需要图片引用作为参数.通过在实际使用过程中,比较发现: UIImagePNGRepresentation(UIImage* image) 要比UIImageJPEGRepresentation(UIImage* image, 1.0) 返回的图片数据量大很多.譬如,同样是读取摄像头拍摄的同样景色的照片, UIImagePNGRepresentation()返回的数据量大小为199K ,而 UIImageJPEGRepresentation(UIImage* image, 1.0)返回的数据量大小只为140KB,比前者少了50多KB.如果对图片的清晰度要求不高,还可以通过设置 UIImageJPEGRepresentation函数的第二个参数,大幅度降低图片数据量.譬如,刚才拍摄的图片, 通过调用UIImageJPEGRepresentation(UIImage* image, 1.0)读取数据时,返回的数据大小为140KB,但更改压缩系数后,通过调用UIImageJPEGRepresentation(UIImage* image, 0.5)读取数据时,返回的数据大小只有11KB多,大大压缩了图片的数据量 ,而且从视角角度看,图片的质量并没有明显的降低.因此,在读取图片数据内容时,建议优先使用UIImageJPEGRepresentation,并可根据自己的实际使用场景,设置压缩系数,进一步降低图片数据量大小.
     
    //打开图片库根目录选择
    UIImagePickerControllerSourceTypePhotoLibrary
    //使用相机选择
    UIImagePickerControllerSourceTypeCamera
    //打开SavedPhoto目录选择
    UIImagePickerControllerSourceTypeSavedPhotosAlbum
     
     
     

     

    用UIImagePickerController调用系统照相机

     

     

    iPhone API 中提供了调用系统照相机的接口,我们只需调用相应的界面,即刻在自己的程序中获取相机图片。下面是一个非常简单的调用系统照相机的例子,相应的界面如下: 最后可以编辑

      iPhone API 中提供了调用系统照相机的接口,我们只需调用相应的界面,即刻在自己的程序中获取相机图片。下面是一个非常简单的调用系统照相机的例子,相应的界面如下:

    最后可以编辑图片和使用相应的图片。

     

    下面是主要代码:

    - (void) addPicEvent 

        //先设定sourceType为相机,然后判断相机是否可用(ipod)没相机,不可用将sourceType设定为相片库 
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera; 

     //用此方法可以判断,设备是否有拍照功能
        if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) { 
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary; 
        }   
        UIImagePickerController *picker = [[UIImagePickerController alloc] init]; 
        picker.delegate = self; 
        picker.allowsEditing = YES; 
        picker.sourceType = sourceType; 
        [self presentModalViewController:picker animated:YES]; 
        [picker release]; 

    - (void)saveImage:(UIImage *)image { 
        NSLog(@"保存"); 

    #pragma mark – 
    #pragma mark Camera View Delegate Methods 
    - (void)imagePickerController:(UIImagePickerController *)picker 
    didFinishPickingMediaWithInfo:(NSDictionary *)info { 
        [picker dismissModalViewControllerAnimated:YES]; 
        UIImage *image = [[info objectForKey:UIImagePickerControllerEditedImage] retain]; 
        [self performSelector:@selector(saveImage:) 
                   withObject:image 
                   afterDelay:0.5]; 

    - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { 
        [picker dismissModalViewControllerAnimated:YES]; 
    }

     

     

     

     

    UIImagePickerController

     

    中期视讯 HD》ipad终于上线了,闲着无事,研究下UIImagePickerController的使用方法。

    引用UIImagePickerController  需用到两个代理<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
    用UIImagePickerController选择、显示图片或视频,主要注意UIImagePickerController几个属性的设置
    一:UI 显示样式,显示的格式确定
    1:sourceType
    @property(nonatomic) UIImagePickerControllerSourceType sourceType
    enum {
    UIImagePickerControllerSourceTypePhotoLibrary,
    UIImagePickerControllerSourceTypeCamera,
    UIImagePickerControllerSourceTypeSavedPhotosAlbum
    };
    typedef NSUInteger UIImagePickerControllerSourceType;
    sourceType用来确定用户界面显示的样式:
    共三种格式(模拟器上的效果图)
    UIImagePickerControllerSourceTypePhotoLibrary,
    UIImagePickerController使用
    UIImagePickerControllerSourceTypeCamera,

    UIImagePickerControllerSourceTypeSavedPhotosAlbum

    UIImagePickerController使用

    为了区分是否支持所需引用的sourceType,一般要用到下面这个函数,以便确定sourceType。

    + (BOOL)isSourceTypeAvailable:(UIImagePickerControllerSourceType)sourceType

    2:   mediaTypes
    @property(nonatomic,copy) NSArray *mediaTypes
    mediaTypes用来确定再picker里显示那些类型的多媒体文件,图片?视频?
    + (NSArray *)availableMediaTypesForSourceType:(UIImagePickerControllerSourceType)sourceType

     

    UIImagePikerController的一些属性和方法:

     

    @property(nonatomic)           UIImagePickerControllerSourceType     sourceType;                  

    @property(nonatomic,copy)      NSArray                              *mediaTypes;                   //是否允许对获得的图片进行编辑,default value is NO.

    @property(nonatomic)           BOOL                                  allowsEditing 

    @property(nonatomic)           BOOL                                  allowsImageEditing 

    //视频最大的时间长度

    @property(nonatomic)           NSTimeInterval                        videoMaximumDuration

    //拍摄照片的清晰度,只有在照相机模式下可用

     

    enum {

        UIImagePickerControllerQualityTypeHigh = 0,       // highest quality 

        UIImagePickerControllerQualityType640x480 = 3,    // VGA quality

        UIImagePickerControllerQualityTypeMedium = 1,     // medium quality, suitable for transmission via Wi-Fi 

        UIImagePickerControllerQualityTypeLow = 2         // lowest quality, suitable for tranmission via cellular network

    };

    typedef NSUInteger UIImagePickerControllerQualityType;

    默认UIImagePickerControllerQualityTypeMedium

     

    @property(nonatomic)           UIImagePickerControllerQualityType    videoQuality

    //是否显示照相机其他控件,默认yes

    @property(nonatomic)           BOOL                                  showsCameraControls

    //类似相框

    @property(nonatomic,retain)    UIView                                *cameraOverlayView 

    @property(nonatomic)           CGAffineTransform                     cameraViewTransform

    //可以设置照相机的模式,照相还是录视频,默认照相模式。

     

    enum {

        UIImagePickerControllerCameraCaptureModePhoto,

        UIImagePickerControllerCameraCaptureModeVideo

    };

    typedef NSUInteger UIImagePickerControllerCameraCaptureMode;

     

    @property(nonatomic) UIImagePickerControllerCameraCaptureMode cameraCaptureMode

    //设置哪个引用摄像头,前置还是后置摄像头

    @property(nonatomic) UIImagePickerControllerCameraDevice      cameraDevice  

    //设置闪光灯模式

    enum {

        UIImagePickerControllerCameraFlashModeOff  = -1,

        UIImagePickerControllerCameraFlashModeAuto = 0,

        UIImagePickerControllerCameraFlashModeOn   = 1

    };

    typedef NSInteger UIImagePickerControllerCameraFlashMode;   

    @property(nonatomic) UIImagePickerControllerCameraFlashMode   cameraFlashMode  

     

     

     

    二:选取动作处理
    UIImagePickerControllerDelegate 
    通过代理来完成用户在选中图片,或者choose视频时的处理方式:
    共有三个可选的代理方法

    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info; 

     

    - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker;

    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo;

     

     

    info中包括选取的照片,视频的主要信息
    NSString *const UIImagePickerControllerMediaType;         选取的类型 public.image  public.movie
    NSString *const UIImagePickerControllerOriginalImage;    修改前的UIImage object.
    NSString *const UIImagePickerControllerEditedImage;      修改后的UIImage object.
    NSString *const UIImagePickerControllerCropRect;           原始图片的尺寸NSValue object containing a CGRect data type
    NSString *const UIImagePickerControllerMediaURL;          视频在文件系统中 的 NSURL地址
    保存视频主要时通过获取其NSURL 然后转换成NSData

     

    保存图片、视频的方法。

     

    // Adds a photo to the saved photos album.  The optional completionSelector should have the form:

    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;

    UIKIT_EXTERN void UIImageWriteToSavedPhotosAlbum(UIImage *image, id completionTarget, SEL completionSelector, void *contextInfo);

     

    // Is a specific video eligible to be saved to the saved photos album? 

    UIKIT_EXTERN BOOL UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(NSString *videoPath) __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_1);

     

    // Adds a video to the saved photos album. The optional completionSelector should have the form:

    //  - (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void //*)contextInfo;

    UIKIT_EXTERN void UISaveVideoAtPathToSavedPhotosAlbum(NSString *videoPath, id completionTarget, SEL completionSelector, void *contextInfo) __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_1);

     

     

     

    实例代码如下:

    实例一:
    - (void) pickImage: (id) sender
    {
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
         ipc.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;
          ipc.mediaTypes =[UIImagePickerController availableMediaTypesForSourceType:ipc.sourceType];   
            } 
    ipc.delegate = self;
    ipc.allowsImageEditing = NO;
    [self presentModalViewController:ipc animated:YES]; 
    }
    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
    {
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:@"public.image"]){
    // UIImage *selectedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        NSLog(@"found an image");
    [UIImageJPEGRepresentation(image, 1.0f) writeToFile:[self findUniqueSavePath] atomically:YES];
        SETIMAGE(image);
    CFShow([[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingString:@"/Documents"]]);
    }
    else if ([mediaType isEqualToString:@"public.movie"]){
    NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
    NSLog(@"found a video");
            NSData *webData = [NSData dataWithContentsOfURL:videoURL];
    //NSData *video = [[NSString alloc] initWithContentsOfURL:videoURL];
    [webData writeToFile:[self findUniqueMoviePath] atomically:YES];
    CFShow([[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingString:@"/Documents"]]);
    // NSLog(videoURL);
    }
    [picker dismissModalViewControllerAnimated:YES];
    }

     

    实例二:主要介绍怎么修改获取图片的方法

    加一个图片处理方法的类:

     

     

    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)selectedImage editingInfo:(NSDictionary *)editingInfo {

     

    CGFloat scale = 100/selectedImage.size.height;

     

    UIImage *newpetimage = [selectedImage scaleToSize:CGSizeMake(selectedImage.size.width*scale, selectedImage.size.height*scale)];

    NSLog(@"imagew = %f,h = %f",newpetimage.size.width,newpetimage.size.height);

     

    }

     

     

     

     

    ios 通过调用系统摄像头拍照,拍视频,然后写入文件

     

    如果您的App里需要获得由系统自带的照相机、摄像机和录音软件所生成的文件。可以借鉴以下代码来调用iPhone摄像头拍照或者摄像的功能,并把获得的数据直接写入到文件。

    如果您的App里需要获得由系统自带的照相机、摄像机和录音软件所生成的文件。可以借鉴以下代码来调用iPhone摄像头拍照或者摄像的功能,并把获得的数据直接写入到文件。

     

    //这一段是,点击一个takePicture按钮的操作.

    01 - (IBAction)takePicture:(id)sender {
    02   
    03 UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    04   
    05 if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
    06 picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    07 NSArray *temp_MediaTypes = [UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
    08 picker.mediaTypes = temp_MediaTypes;
    09 picker.delegate = self;
    10 picker.allowsImageEditing = YES;
    11 }
    12   
    13 [self presentModalViewController:picker animated:YES];
    14 [picker release];
    15   
    16 }

     

    //下面两个函数是遵守 UIImagePickerControllerDelegate这个协议所实现的类.这样就能够完整的实现,获取照片或者视频,然后写入文件的过程.

    01     - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
    02     {
    03       
    04     NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    05       
    06     BOOL success;
    07     NSFileManager *fileManager = [NSFileManager defaultManager];
    08     NSError *error;
    09       
    10     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    11     NSString *documentsDirectory = [paths objectAtIndex:0];
    12       
    13     if ([mediaType isEqualToString:@"public.image"]){
    14       
    15     UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    16 ;    NSLog(@“found an image”);
    17       
    18     NSString *imageFile = [documentsDirectory stringByAppendingPathComponent:@"temp.jpg"];
    19 ;    NSLog(@“%@”, ,imageFile);
    20       
    21     success = [fileManager fileExistsAtPath:imageFile];
    22     if(success) {
    23     success = [fileManager removeItemAtPath:imageFile error:>error];
    24     }
    25       
    26     imageView.image = image;
    27     [UIImageJPEGRepresentation(image, 1.0f) writeToFile:imageFile atomically:YES];
    28       
    29     //SETIMAGE(image);
    30     //CFShow([[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingString:@"/Documents"]]);
    31 ;    }
    32     else if([mediaType isEqualToString:@"public.movie"]){
    33     NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
    34     NSLog(@“%@”, ,videoURL);
    35     NSLog(@“found a video”);
    36     NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
    37       
    38     /****************************************/
    39       
    40     NSString *videoFile = [documentsDirectory stringByAppendingPathComponent:@"temp.mov"];
    41 ;    NSLog(@“%@”, ,videoFile);
    42       
    43     success = [fileManager fileExistsAtPath:videoFile];
    44     if(success) {
    45     success = [fileManager removeItemAtPath:videoFile error:>error];
    46     }
    47     [videoData writeToFile:videoFile atomically:YES];
    48     //CFShow([[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingString:@"/Documents"]]);
    49 ;    //NSLog(videoURL);
    50     }
    51     [picker dismissModalViewControllerAnimated:YES];
    52     }
    53       
    54     - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    55       
    56     [picker dismissModalViewControllerAnimated:YES];
    57       
    58     }
     
     
     

    UIImagePickerController 图像选取器--在iPhone中调用照相机、照片库—IOS开发

    UIImagePickerController 图像选取器是一种导航控制器类,让你可以在应用程序中添加简单的图像选择功能或者照相机界面。用户会看到一个图像选择屏幕,在其中挑选相片,相片的来源则是他自己的相片库、保存下来的相片集或者照相机。当用户选定一个相片后,就会通过 UIImagePickerDelegate 协议中的方法,通知选取器的委托。

    你可以用  UIImagePickerController 类来创建图像选取器,并且可以将其作为一个独立的导航控制器,添加到窗口中。

    一、创建并添加到视图中

    1. UIImagePickerController* picker = [[UIImagePickerController alloc]init];  
    2. [self.view addSubview:picker.view];  

    二、图像来源

    你可以通过 sourceType 属性设定多种图像来源,呈现给用户:

    1. picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;  
    可以使用下列来源:
    1. enum {  
    2. UIImagePickerControllerSourceTypePhotoLibrary,//相片库  
    3.     UIImagePickerControllerSourceTypeCamera,//照相机  
    4.     UIImagePickerControllerSourceTypeSavedPhotosAlbum//保存的相片  
    5. };  
    6. typedef NSUInteger UIImagePickerControllerSourceType;  
    三、图像编辑

     

    要让用户可以随意移动以及缩放图像,可以将 allowsImageEditing 属性设置为 YES,打开图像编辑功能:

    1. picker.allowsEditing=YES;  
    四、图像选取

     

    当用户选择一个图片之后,选择器的委托会通过 didFinishPickingImage 方法接到通知。代理会得到一个包含有该图像的 UIImage 对象,如果编辑功能开启的话,还会得到一个包含了编辑属性的NSDictionary。

    设置选取器的 delegate ,就可以将一个委托赋予选择器:

    1. picker.delegate =self;  
    在你的委托类中实现下面的方法,这样当选取一个图像时,委托类就会得到通知:
    1. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{  
    2.     /*添加处理选中图像代码*/  
    3. }  
    方法的参数包括一个指针,指向报告当前操作的图像选取器控制器,这样你就可以在一个委托中处理多个选取器。参数还包括一个指向 UIImage 对象自身的指针,以及一个字典对象,其中包含有关于图像在屏幕上如何被缩放以及移动的信息。

     

    你可能在用户取消图像选择时也想要得到通知。要达到这一目的,要在代理中实现 imagePickerControllerDidCancel 方法。他会在取消选择时被调用,以指向被取消的图像选取器指针为参数:

    1. - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{  
    2.     /*添加代码,处理选中图像又取消的情况*/  
    3. }  
    最后附上代码例子。 UIImagePickerControllerDemo 
  • 相关阅读:
    引入C/C++动态库
    Linux新手常用命令
    使用Dotfunsctor
    C#上传数据到HTTP,HTTPS 代码示例
    C#多个泛型约束问题
    创建DataTable与DataGridView进行绑定
    递归迭代vector三种方法实现二路归并排序
    区间贪心算法
    递归和非递归实现二叉树的遍历
    C语言实现全排列和回溯法总结
  • 原文地址:https://www.cnblogs.com/zhwl/p/2843788.html
Copyright © 2011-2022 走看看