iOS 头像保存本地设置圆角并压缩上传服务器
2017-05-19 本文已影响56人
fulen
哥来上海了,不过最近忙成狗了,新项目早九晚十,生活除了工作就是工作,不说废话了,也没人关心哥哥
以前就有很多关于头像设置的需求,今天就做一次详细的介绍,效果如下图
圆角图片
1.先建一个HeadPicture类,保存image
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface HeadPicture : NSObject
/**
单利
@return 头像
*/
+(instancetype)sharedHeadsPicture;
/**
* 设置头像
*
* @param image 图片
*/
-(void)setImage:(UIImage *)image forKey:(NSString *)key;
/**
* 读取图片
*
*/
-(UIImage *)imageForKey:(NSString *)key;
@end
#import "HeadPicture.h"
@interface HeadPicture ()
@property (nonatomic, strong) NSMutableDictionary *dictionary;
-(NSString *)imagePathForKey:(NSString *)key;
@end
@implementation HeadPicture
+(instancetype)sharedHeadsPicture{
static HeadPicture *instance = nil;
//确保多线程中只创建一次对象,线程安全的单例
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc] initPrivate];
});
return instance;
}
-(instancetype)initPrivate{
self = [super init];
if (self) {
_dictionary = [[NSMutableDictionary alloc] init];
//注册为低内存通知的观察者
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:@selector(clearCaches:)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
}
return self;
}
-(void)setImage:(UIImage *)image forKey:(NSString *)key{
[self.dictionary setObject:image forKey:key];
//获取保存图片的全路径
NSString *path = [self imagePathForKey:key];
//从图片提取JPEG格式的数据,第二个参数为图片压缩参数
NSData *data = UIImageJPEGRepresentation(image, 0.5);
//以PNG格式提取图片数据
//NSData *data = UIImagePNGRepresentation(image);
NSLog(@"path ===== %@",path);
//将图片数据写入文件
[data writeToFile:path atomically:YES];
}
-(UIImage *)imageForKey:(NSString *)key{
//return [self.dictionary objectForKey:key];
UIImage *image = [self.dictionary objectForKey:key];
if (!image) {
NSString *path = [self imagePathForKey:key];
image = [UIImage imageWithContentsOfFile:path];
if (image) {
[self.dictionary setObject:image forKey:key];
}else{
NSLog(@"Error: unable to find %@", [self imagePathForKey:key]);
}
}
return image;
}
-(NSString *)imagePathForKey:(NSString *)key{
NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [documentDirectories firstObject];
return [documentDirectory stringByAppendingPathComponent:key];
}
-(void)clearCaches:(NSNotification *)n{
NSLog(@"Flushing %ld images out of the cache", (unsigned long)[self.dictionary count]);
[self.dictionary removeAllObjects];
}
@end
2.下面就运用在头像的设置中去了
#import "PersonInformationController.h"
#import "HeadPicture.h"
#define kHeight [UIScreen mainScreen].bounds.size.height
#define kWidth [UIScreen mainScreen].bounds.size.width
@interface PersonInformationController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (strong , nonatomic) UIButton *headButton;
@property (strong, nonatomic) UIImageView *headImageV;
@end
@implementation PersonInformationController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"个人信息";
[self creatUI];
}
- (void)creatUI{
UIView *bgview = [[UIView alloc] initWithFrame:CGRectMake(0, 100*kHeight/736, kWidth, 200*kHeight/736)];
[self.view addSubview:bgview];
bgview.backgroundColor = [UIColor grayColor];
UIView *upview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 130*kHeight/736)];
[bgview addSubview:upview];
upview.backgroundColor = [UIColor cyanColor];
UILabel *headlabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0 , 80, 130*kHeight/736)];
[upview addSubview:headlabel];
headlabel.text = @"头像";
self.headImageV = [[UIImageView alloc] initWithFrame:CGRectMake(kWidth - 130*kHeight/736, 0, 130*kHeight/736, 130*kHeight/736)];
[upview addSubview:self.headImageV];
self.headImageV.backgroundColor = [UIColor grayColor];
[self setCirclePhoto];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pickerImage)];
[self.headImageV addGestureRecognizer:tap];
}
/**
* 设置圆形头像属性
*/
- (void)setCirclePhoto{
[self.headImageV.layer setCornerRadius:CGRectGetHeight([self.headImageV bounds]) / 2];
self.headImageV.layer.masksToBounds = true;
//可以根据需求设置边框宽度、颜色
self.headImageV.layer.borderWidth = 1;
self.headImageV.layer.borderColor = [[UIColor blackColor] CGColor];
//加载首先访问本地沙盒是否存在相关图片
NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"HeadsPicture"];
UIImage *savedImage = [UIImage imageWithContentsOfFile:fullPath];
NSLog(@"savedImage == %@",savedImage);
if (savedImage == NULL) {
savedImage = [UIImage imageNamed:@"image1"];
}
self.headImageV.layer.contents = (id)[savedImage CGImage];
self.headImageV.userInteractionEnabled = YES;
}
- (void)pickerImage{
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.editing = YES;
imagePicker.delegate = self;
/*
如果这里allowsEditing设置为false,则下面的UIImage *image = [info valueForKey:UIImagePickerControllerEditedImage];
应该改为: UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
也就是改为原图像,而不是编辑后的图像。
*/
//允许编辑图片
imagePicker.allowsEditing = YES;
/*
这里以弹出选择框的形式让用户选择是打开照相机还是图库
*/
//初始化提示框;
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择打开方式" message:nil preferredStyle: UIAlertControllerStyleActionSheet];
[alert addAction:[UIAlertAction actionWithTitle:@"照相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:imagePicker animated:YES completion:nil];
}]];
[alert addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:imagePicker animated:YES completion:nil];
}]];
[alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
//取消;
}]];
//弹出提示框;
[self presentViewController:alert animated:true completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
//通过info字典获取选择的照片
UIImage *image = [info valueForKey:UIImagePickerControllerEditedImage];
//以itemKey为键,将照片存入ImageStore对象中
[[HeadPicture sharedHeadsPicture] setImage:image forKey:@"HeadsPicture"];
//将照片放入UIImageView对象
self.headImageV.image = image;
//把一张照片保存到图库中,此时无论是这张照片是照相机拍的还是本身从图库中取出的,都会保存到图库中;
UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
//压缩图片,如果图片要上传到服务器或者网络,则需要执行该步骤(压缩),第二个参数是压缩比例,转化为NSData类型;
NSData *fileData = UIImageJPEGRepresentation(image, 1.0);
// 以下上传服务器
NSMutableDictionary *para = [NSMutableDictionary dictionary];
[para setObject:[JF_DEFAULTS objectForKey:@"userId"] forKey:@"userId"];
// 后台要求将图片转化成base64
NSString *imageString = [fileData base64EncodedStringWithOptions:0];
[para setObject:imageString forKey:@"image"]; // 图片字节流
NSMutableDictionary *dic = [JFBaseRequest mutableDicWithParameters:para]; // 封装的公参字典
CLog(@"上传图片所有参数dic=========%@",dic);
AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];// 请求
manager.responseSerializer = [AFJSONResponseSerializer serializer];
//设置超时时间
[manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
manager.requestSerializer.timeoutInterval = 15.0f;
[manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
// 上传图片
[manager POST:@"http://172.16.16.15:9000/points-gateway/service/member/saveImg" parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
[MBProgressHUD showMessage:@"头像修改成功"];
// [JF_DEFAULTS setObject:nameTextField.text forKey:@"imageUrl"];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
还有一种上传nsdata类型参数,切参数拼接在请求里
NSDictionary *dic = [NSDictionary dictionary];
if ([self.invoiceType isEqualToString:@"2"]) {
dic=@{@"userName":USER_INFO.phone,@"userPwd":USER_INFO.pswMd5,@"recipientName":self.recipientName,@"invoiceType":self.invoiceType,@"pid":_productInfo[@"id"]};
}else{
dic=@{@"userName":USER_INFO.phone,@"userPwd":USER_INFO.pswMd5,@"taxNo":self.taxNo,@"companyName":self.companyName,@"pid":_productInfo[@"id"],@"payType":payWayNum};
}
LYLog(@"%@",dic);
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
// 上传图片
[manager POST:URL_NEWACCONT_PAY parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *imageName = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.jpg",imageName];
// NSData *fileData = [PublicMethod compressImage:self.imageArray[i] toMaxFileSize:300];
for (int i = 0; i< self.fileNameArray.count; i++) {
// 图片压缩在300K以内
NSData *fileData = self.dataArray[i];
[formData appendPartWithFileData:self.dataArray[i] name:self.fileNameArray[i] fileName:fileName mimeType:@"image/jpeg"];
}
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
[self hideHud];
LYLog(@"图片上传成功 code:%@ msg:%@ responseObject:%@",responseObject[@"code"],responseObject[@"msg"],responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
//关闭以模态形式显示的UIImagePickerController
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end