iOS 头像保存本地设置圆角并压缩上传服务器

哥来上海了,不过最近忙成狗了,新项目早九晚十,生活除了工作就是工作,不说废话了,也没人关心哥哥

以前就有很多关于头像设置的需求,今天就做一次详细的介绍,效果如下图


圆角图片

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,098评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,213评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,960评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,519评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,512评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,533评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,914评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,574评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,804评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,563评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,644评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,350评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,933评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,908评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,146评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,847评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,361评论 2 342

推荐阅读更多精彩内容