app实现上传图片

通过点击ImageView,调用系统相册或者相机选择照片。
调用UIImagePickerController,需要有UIImagePickerControllerDelegate,UINavigationControllerDelegate两个协议,sourceType中UIImagePickerControllerSourceTypePhotoLibrary是相册,UIImagePickerControllerSourceTypeCamera是相机(真机才可以测试)。

1.打开相册

        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
        controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
        controller.mediaTypes = mediaTypes;
        controller.delegate = self;
        [self presentViewController:controller
                           animated:YES
                         completion:^(void){
//                             DDLogInfo(@"Picker View Controller is presented");
                         }];
2.选择图片,可以在这使用第三方的RSKImageCropper,用来自定义选取圆形或方形的图片

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    __weak VerificationViewController *weakSelf = self;
    [picker dismissViewControllerAnimated:YES
                               completion:^() {
                                   UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
                                   //取得选择的图片
                                   weakSelf.userPortrait = portraitImg;
                                   //上传图片
                                   [weakSelf updateUserPortait];
                               }];
}
/**这个方法记得写,用来点击取消时返回*/
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES
                               completion:^{
                               }];
}
3.图片上传,大部分会采用base64加密,参数封装

NSData *data                = UIImageJPEGRepresentation(self.userPortrait, 0.5);
    NSString *bodystring        = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    NSData  *imagedata          = [bodystring dataUsingEncoding:NSUTF8StringEncoding];
    NSString  *imageData        = [[NSString alloc] initWithData:imagedata
                                                        encoding:NSUTF8StringEncoding];




你可能感兴趣的:(移动开发)