上传图片到服务器和图片内存处理以及拍照或从相册选取图片的小总结

来源:互联网 发布:java数学黑洞 编辑:程序博客网 时间:2024/05/17 08:52

今天做项目用到的上传图片到服务器,现在来总结一下具体流程。

首先我们看下UIImagePickerControllerSourceTypePhotoLibrary:选取相册中的图像。图像选取控制器以该模式显示时会浏览系统照片库的根目录。

UIImagePickerControllerSourceTypeCamera:打开相机拍照选取图像。(对了,最近新出的IOS10需要对访问相册授权。)

在info.plist文件下添加 :

相机权限

<key>NSCameraUsageDescription</key>

<string>cameraDesciption</string>

相册权限

<key>NSPhotoLibraryUsageDescription</key>

<string>photoLibraryDesciption</string>


~~~~~~~~不然APP会闪退
下面是具体代码:

UIImagePickerController * imagepicker = [[UIImagePickerControlleralloc]init];

    imagepicker.delegate =self;//代理

    if (type ==2) {

            imagepicker.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;

            

        imagepicker.allowsEditing=YES;//允许编辑图片

       

    }else{

        imagepicker.sourceType =UIImagePickerControllerSourceTypeCamera;

        imagepicker.modalTransitionStyle =UIModalTransitionStyleCoverVertical;

        imagepicker.allowsEditing =YES;

    }

     [[UIApplicationsharedApplication].keyWindow.rootViewControllerpresentViewController:imagepickeranimated:YEScompletion:nil];


这个就会跳到系统的选择图片或者拍照界面了,然后选择图片需要实现这个协议方法,下面是具体代码:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info

{

    UIImage *image = info[UIImagePickerControllerOriginalImage];

    [selfsaveImage:image WithName:@"userAvatar.jpg"];

    [self.picButtonsetImage:image forState:UIControlStateNormal] ;//添加从相册选取的图片

    [picker dismissViewControllerAnimated:YEScompletion:nil];

    

}


由于很多服务器不能直接上传图片(通常是通过文件的方式上传),所以我们要把选择的图片保存到本地,就好的方式就是保存到document。最开始我想过为什么我们不直接获取选择的图片的Path然后直接上传呢,后来在网上查了发现IOS并不能直接获取相册文件的路径。下面是保存到document的代码:

- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName

{

    NSData* imageData =UIImageJPEGRepresentation(tempImage,0.2f);

    NSString* documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)objectAtIndex:0];

    NSString* totalPath = [documentPathstringByAppendingPathComponent:imageName];

    

    //保存到 document

    [imageData writeToFile:totalPathatomically:NO];

    self.picPath = totalPath;


}

在保存到document的时候我又出现了个问题,在给文件写保存名字的时候
必须要加上文件后缀名(格式名);不然系统会直接报错。
好了,我们已经得到图片的路径了,下面就是通过文件上传到服务器了。这个看具体服务器的方法了,就不在多说。 但是在上传之前,我们得对图片进行一下处理,因为苹果的照片通常有10多M这个大,所以我们要压缩一下。
0 0
原创粉丝点击