美文网首页
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);

}

}];

}

```

相关文章

  • Vue上传图片压缩的问题

    上传图片太大,需要前台进行图片压缩上传图片大于100* 1024 的用canvas 来压缩来解决然后IOS拍照上传...

  • vue 图片压缩

    vue 图片压缩 上传图片大于100* 1024 的用canvas 来压缩来解决 然后IOS拍照上传会有图片旋转的...

  • vue 图片压缩

    vue 图片压缩 上传图片大于100* 1024 的用canvas来压缩来解决 然后IOS拍照上传会有图片旋转的问...

  • iOS图片上传及压缩

    iOS开发中关于图片上传,一般有两种方法:1.自己手动写(如:NSURLMutableRequest等系统类),实...

  • iOS 上传图片及压缩图片

    ####获取图片 的方法代码 ``` -(void)avatarTap:(id)sender{ UIAlertCo...

  • 2015-10-16图片压缩,MD5校验去重

    ios客户端上传图片的时候,如果图片过大,通常会压缩后上传, UIImageJPEGRepresentation(...

  • iPic for Mac(图床神器) v1.7.0中文免费版

    上传图片相关设置 上传前压缩图片 可以在 iPic 的 偏好设置 中开启「上传前压缩图片」选项,目前支持压缩的图片...

  • iOS 网络上传图片

    上传图片 构造参数(NSArray *)files 上传图片—压缩 压缩到小于(...

  • iOS 图片压缩方法

    iOS 图片压缩方法 更多图片处理方法见图片组件 BBWebImage iOS 图片压缩方法 两种图片压缩方法 两...

  • iOS 图片压缩上传

    前段时间处理了下图片上传压缩的问题,在这里记录下。iPhone拍摄的照片2-3M可压缩至30-60KB左右,清晰度...

网友评论

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

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