美文网首页
iOS 上传图片及压缩图片

iOS 上传图片及压缩图片

作者: jianshu小赵 | 来源:发表于2016-08-04 22:02 被阅读431次

    ####获取图片 的方法代码

    ```

    -(void)avatarTap:(id)sender{

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"设置头像" message:@"" preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {

    NSLog(@"The \"Okay/Cancel\" alert's cancel action occured.");

    }];

    UIAlertAction* fromPhotosAlbumAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault                                                                handler:^(UIAlertAction * action) {                                                                    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];

    imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;

    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;

    imagePicker.allowsEditing = YES;

    imagePicker.delegate = self;

    [self presentViewController:imagePicker animated:YES completion:nil];

    }];

    UIAlertAction* fromPhotoAction = [UIAlertAction actionWithTitle:@"从图库选择" style:UIAlertActionStyleDefault                                                                handler:^(UIAlertAction * action) {                                                                    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];

    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;

    imagePicker.allowsEditing = YES;

    imagePicker.delegate = self;

    [self presentViewController:imagePicker animated:YES completion:nil];

    }];

    UIAlertAction* fromCameraAction = [UIAlertAction actionWithTitle:@"相机拍摄" style:UIAlertActionStyleDefault                                                            handler:^(UIAlertAction * action) {

    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])

    {

    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];

    imagePicker.delegate = self;

    imagePicker.allowsEditing = YES;

    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;

    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;

    [self presentViewController:imagePicker animated:YES completion:nil];

    }

    }];

    [alertController addAction:cancelAction];

    [alertController addAction:fromCameraAction];

    [alertController addAction:fromPhotoAction];

    [alertController addAction:fromPhotosAlbumAction];

    [self presentViewController:alertController animated:YES completion:nil];

    }

    ```

    ###如何进行 压缩

    ```

    UIImage *smallImage=[self scaleFromImage:image toSize:CGSizeMake(240.0f, 240.0f)];//将图片尺寸改为240x240

    [UIImageJPEGRepresentation(smallImage, 1.0f) writeToFile:imageFilePath atomically:YES];//写入jpg文件

    + (UIImage *)imageWithCGImage:(CGImageRef)cgImage scale:(CGFloat)scale orientation:(UIImageOrientation)orientation NS_AVAILABLE_IOS(4_0);

    ```

    该方面使用一个CGImageRef创建UIImage,在创建时还可以指定方法倍数以及旋转方向。当scale设置为1的时候,新创建的图像将和原图像尺寸一摸一样,而orientaion则可以指定新的图像的绘制方向。

    也可以用这个方法进行压缩  你会发现 得到的 大小 会小了很多倍 如果想测试的话可以 装换成 nsdata  打印一下  哦了。

    ```

    + (UIImage *) scaleFromImage: (UIImage *) image toSize: (CGSize) size

    {

    UIGraphicsBeginImageContext(size);

    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;

    }

    ```

    接着我们就贴代码了 上传 加压缩

    ```

    + (void)requestToUploadImage:(UIImage*)image completion:(void(^)(NSString * upfile,int code,NSError*error))complete{

    NSString * url = URL_UPTOIMAGE;

    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];    //请求和接受的格式

    manager.responseSerializer = [AFJSONResponseSerializer serializer];    manager.requestSerializer = [AFJSONRequestSerializer serializer];    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/javascript",@"text/html", nil];

    //请求超时

    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];    manager.requestSerializer.timeoutInterval = 10.0;

    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];        [manager POST:url parameters:nil constructingBodyWithBlock:^(idformData) {

    //NSData * fileData1 = UIImageJPEGRepresentation(image, 0.1);

    //ZLLog(@"%lu",(unsigned long)fileData1.length);

    BOOL success;

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSError *error;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];

    NSLog(@"imageFile->>%@",imageFilePath);

    success = [fileManager fileExistsAtPath:imageFilePath];

    if(success) {

    success = [fileManager removeItemAtPath:imageFilePath error:&error];

    }

    UIImage *smallImage=[self scaleFromImage:image toSize:CGSizeMake(240.0f, 240.0f)];

    [UIImageJPEGRepresentation(smallImage, 1.0f) writeToFile:imageFilePath atomically:YES];

    UIImage *selfPhoto = [UIImage imageWithContentsOfFile:imageFilePath];

    NSData * fileData = UIImageJPEGRepresentation(selfPhoto, 0.1);

    //ZLLog(@"%lu",(unsigned long)fileData.length);

    //使用日期生成图片名称

    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];

    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";

    NSString * fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];

    [formData appendPartWithFileData:fileData name:@"upfile" fileName:fileName mimeType:@"jpg"];

    } success:^(NSURLSessionDataTask *task, id responseObject) {

    NSDictionary * dic = responseObject;

    //ZLLog(@"%@",responseObject);

    NSString * address = dic[@"data"];

    int code = [dic[@"code"] intValue];

    if (complete) {

    complete(address,code,nil);

    }

    } failure:^(NSURLSessionDataTask *task, NSError *error) {

    if (complete) {

    complete(nil,0,error);

    }

    }];

    }

    ```

    相关文章

      网友评论

          本文标题:iOS 上传图片及压缩图片

          本文链接:https://www.haomeiwen.com/subject/jjfhsttx.html