####獲取圖片 的方法代碼
```
-(void)avatarTap:(id)sender{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"設(shè)置頭像" 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創(chuàng)建UIImage淤袜,在創(chuàng)建時還可以指定方法倍數(shù)以及旋轉(zhuǎn)方向痒谴。當(dāng)scale設(shè)置為1的時候,新創(chuàng)建的圖像將和原圖像尺寸一摸一樣铡羡,而orientaion則可以指定新的圖像的繪制方向积蔚。
也可以用這個方法進行壓縮? 你會發(fā)現(xiàn) 得到的 大小 會小了很多倍 如果想測試的話可以 裝換成 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);
}
}];
}
```