iOS相册图片缓存(document)以及图片文件流上传服务器功能

来源:互联网 发布:淘宝鲁班系统 编辑:程序博客网 时间:2024/04/19 20:48

不要忘了遵循协议还有用到的AFNetworking(第三方类库)并且导入

#import "AFHTTPSessionManager.h"头文件

<UIImagePickerControllerDelegateUINavigationControllerDelegate>

首先要创建图片选取对象(sourceType)

 //创建图片选取器对象    UIImagePickerController * pickerViwController = [[UIImagePickerController alloc] init];    /*     图片来源     UIImagePickerControllerSourceTypePhotoLibrary:表示显示所有的照片     UIImagePickerControllerSourceTypeCamera:表示从摄像头选取照片     UIImagePickerControllerSourceTypeSavedPhotosAlbum:表示仅仅从相册中选取照片。     */    pickerViwController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;        //允许用户编辑图片 (YES可以编辑,NO只能选择照片)    pickerViwController.allowsEditing = YES;        //设置代理    pickerViwController.delegate = self;        [self presentViewController:pickerViwController animated:YES completion:nil];


遵循协议之后就可以在从相册选取图片之后回调方法

#pragma mark <2>相册协议中方法,选中某张图片后调用方法- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{       UIImage *image= [info objectForKey:@"UIImagePickerControllerOriginalImage"];    // 如果是相机拍照的,保存在本地    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)    {        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);    }    //让界面的imageview中图片换成得到选中的图片    tapImageView.image = image;     //保存图片到Document目录下        [self saveImage:image  WithName:@"userHeader.png"];  [self dismissViewControllerAnimated:YES completion:nil];}#pragma mark --  压缩图片- (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;}


- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName{   NSData *imageData = UIImagePNGRepresentation(tempImage);        //判断图像是png格式的还是jpg格式的(iOS相册里面可以保存gif格式的,可是gif格式的图片在相册中是以静态图显示的)    if (UIImagePNGRepresentation(tempImage) == nil)    {        imageData = UIImageJPEGRepresentation(tempImage, 1.0);    }    else    {        imageData = UIImagePNGRepresentation(tempImage);    }   NSString* documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];   NSString *tempDocumentPath = [documentPath stringByAppendingPathComponent:imageName];     //保存到 document    [imageData writeToFile: tempDocumentPath atomically:NO];       //上传服务器//    [self uploadToWedServer: tempDocumentPath];    }

#pragma mark //上传服务器- (void)uploadAvatar:(NSString*)tempPath {    //URL(长度不能超过255)模拟器上过长老是bingo    NSURL *filePath=[NSURL URLWithString:totalPath];        // 此为上传路径,当你需要以文件流的方式进行上传的时候,此处只需要把照片转化成NSData类型的data,参数按照之前的上传路径参数制定即可,然后上传          //NSData *data=[NSData dataWithContentsOfFile:filePath];          NSString *uploadString=@"http://localhost/webServer/upload.php";        NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer]multipartFormRequestWithMethod:@"POST" URLString:uploadString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)               {                   [formData appendPartWithFileURL:filePath name:@"file" fileName:@"d3.png" mimeType:@"image/jpeg" error:nil];                    /**                     * 文件流方式上传                     */                    //[formData appendPartWithFileData:data name:@"upFile" fileName:@"headImage.png" mimeType:@"image/png"];     } error:nil];        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];    manager.responseSerializer=[AFHTTPResponseSerializer serializer];        NSProgress *progress = nil;        NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {        if (error) {            NSLog(@"Error: %@", error);        } else {            NSLog(@"OK!,%@ %@", response,[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding] );        }    }];    [uploadTask resume];    }







0 0
原创粉丝点击