头像压缩 通过base64数据上传
1.通过相机/相册获取图片
用到的代理
@interface ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
//打开相机相册方法如下:
- (void)getImageFromIpc
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.sourceType = UIImagePickerControllerSourceTypeCamera; //打开相机
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //打开相册
picker.delegate = self;
//设置选择后的图片可被编辑
picker.allowsEditing = YES;
[self presentViewController:picker animated:YES completion:nil];
}
代理方法如下:
#pragma mark -- <UIImagePickerControllerDelegate>--
// 获取图片后的操作
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
// 销毁控制器
[picker dismissViewControllerAnimated:YES completion:nil];
// 设置图片
UIImage *image = info[UIImagePickerControllerOriginalImage];
//设置上下文画板的尺寸 (大于或小于均会让图片显示不全或者超过)
UIGraphicsBeginImageContext(CGSizeMake(64, 64));
CGRect thumbnailRect = CGRectZero;
//设置图片在上下文画板上的尺寸(64*64像素)
thumbnailRect.size.width = 64;
thumbnailRect.size.height = 64;
[image drawInRect:thumbnailRect];
UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.imageView.image = newImage;
//后端要求, 图片像素64*64 大小小于4K
NSData *data = UIImageJPEGRepresentation(newImage, 0.6f);
NSLog(@"%@",data);
NSLog(@"%lu",data.length);
NSString *kind = [ViewController typeForImageData:data];
NSLog(@"%@",kind);
NSString *dataBase64Str = [Base64Util base64EncodedStringFrom:data];
NSLog(@"%@",dataBase64Str);
NSData *dataBase64 = [dataBase64Str dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%lu",(unsigned long)dataBase64.length);
}
如何压缩图片 64*64像素
//设置上下文画板的尺寸 (大于或小于均会让图片显示不全或者超过)
UIGraphicsBeginImageContext(CGSizeMake(64, 64));
CGRect thumbnailRect = CGRectZero;
//设置图片在上下文画板上的尺寸(64*64像素)
thumbnailRect.size.width = 64;
thumbnailRect.size.height = 64;
[image drawInRect:thumbnailRect];
UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();