iOS 上傳圖片及壓縮圖片

####獲取圖片 的方法代碼

```

-(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);

}

}];

}

```

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末烦周,一起剝皮案震驚了整個濱河市尽爆,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌读慎,老刑警劉巖漱贱,帶你破解...
    沈念sama閱讀 216,997評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異贪壳,居然都是意外死亡饱亿,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來彪笼,“玉大人钻注,你說我怎么就攤上這事∨涿ǎ” “怎么了幅恋?”我有些...
    開封第一講書人閱讀 163,359評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長泵肄。 經(jīng)常有香客問我捆交,道長,這世上最難降的妖魔是什么腐巢? 我笑而不...
    開封第一講書人閱讀 58,309評論 1 292
  • 正文 為了忘掉前任品追,我火速辦了婚禮,結(jié)果婚禮上冯丙,老公的妹妹穿的比我還像新娘肉瓦。我一直安慰自己,他們只是感情好胃惜,可當(dāng)我...
    茶點故事閱讀 67,346評論 6 390
  • 文/花漫 我一把揭開白布泞莉。 她就那樣靜靜地躺著,像睡著了一般船殉。 火紅的嫁衣襯著肌膚如雪鲫趁。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,258評論 1 300
  • 那天利虫,我揣著相機與錄音挨厚,去河邊找鬼。 笑死列吼,一個胖子當(dāng)著我的面吹牛幽崩,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播寞钥,決...
    沈念sama閱讀 40,122評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼慌申,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了理郑?” 一聲冷哼從身側(cè)響起蹄溉,我...
    開封第一講書人閱讀 38,970評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎您炉,沒想到半個月后柒爵,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,403評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡赚爵,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,596評論 3 334
  • 正文 我和宋清朗相戀三年棉胀,在試婚紗的時候發(fā)現(xiàn)自己被綠了法瑟。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,769評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出悄但,到底是詐尸還是另有隱情,我是刑警寧澤酥夭,帶...
    沈念sama閱讀 35,464評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站脊奋,受9級特大地震影響熬北,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜诚隙,卻給世界環(huán)境...
    茶點故事閱讀 41,075評論 3 327
  • 文/蒙蒙 一讶隐、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧最楷,春花似錦整份、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,705評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽火俄。三九已至犯建,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間瓜客,已是汗流浹背适瓦。 一陣腳步聲響...
    開封第一講書人閱讀 32,848評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留谱仪,地道東北人玻熙。 一個月前我還...
    沈念sama閱讀 47,831評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像疯攒,于是被迫代替她去往敵國和親嗦随。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,678評論 2 354

推薦閱讀更多精彩內(nèi)容