iOS 实现头像选取(照相或者图片库)、大小等比缩放、生成圆形头像

时间:2023-01-23 14:46:04

iOS 实现头像选取(照相或者图片库)、大小等比缩放、生成圆形头像

//

//  ViewController.h

//  TestImageController

//

//  Created by huweibin on 15-5-17.

//  Copyright (c) 2015 taogu. All rights reserved.

//


#import <UIKit/UIKit.h>

#import <MobileCoreServices/MobileCoreServices.h>

#import <QuartzCore/QuartzCore.h>

@interface ViewController :UIViewController<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>


@end




//

//  ViewController.m

//  TestImageController

//

//

//  Created by huweibin on 15-5-17.

//  Copyright (c) 2015 taogu. All rights reserved.

//


#import "ViewController.h"


@interface ViewController ()

@property(nonatomic,strong) UIImageView *img;

@property(nonatomic,strong) NSData *fileData;

@end


@implementation ViewController


- (void)viewDidLoad

{

    [superviewDidLoad];


    //设置图片框

    self.img = [[UIImageViewalloc] initWithFrame:CGRectMake(100,100, 93, 93)];

    UIBarButtonItem *left = [[UIBarButtonItemalloc] initWithTitle:@"picture"style:UIBarButtonItemStyleBorderedtarget:selfaction:@selector(takePictureClick:)];

    self.navigationItem.rightBarButtonItem = left;


    [self.viewaddSubview:self.img];


    //图片路径

    NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

   NSString *documentsDirectory = [paths objectAtIndex:0];

   NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];

   NSLog(@"imageFile->>%@",imageFilePath);

   UIImage *selfPhoto = [UIImageimageWithContentsOfFile:imageFilePath];//

   self.img.image = selfPhoto;

    [self.img.layersetCornerRadius:CGRectGetHeight([self.imgbounds]) / 2];

    self.img.layer.masksToBounds = YES;

}


//从相册获取图片

-(void)takePictureClick:(UIButton *)sender

{

    UIActionSheet* actionSheet = [[UIActionSheetalloc]

                                 initWithTitle:@"请选择文件来源"

                                 delegate:self

                                 cancelButtonTitle:@"取消"

                                 destructiveButtonTitle:nil

                                 otherButtonTitles:@"照相机",@"摄像机",@"本地相簿",@"本地视频",nil];

    [actionSheetshowInView:self.view];

    

}

#pragma mark -

#pragma UIActionSheet Delegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex

{

    NSLog(@"buttonIndex = [%ld]",(long)buttonIndex);

   switch (buttonIndex) {

       case 0://照相机

        {

            UIImagePickerController *imagePicker = [[UIImagePickerControlleralloc] init];

            imagePicker.delegate =self;

            imagePicker.allowsEditing =YES;

            imagePicker.sourceType =UIImagePickerControllerSourceTypeCamera;

//            [self presentModalViewController:imagePicker animated:YES];

            [selfpresentViewController:imagePicker animated:YEScompletion:nil];

        }

           break;

       case 1://摄像机

        {

            UIImagePickerController *imagePicker = [[UIImagePickerControlleralloc] init];

            imagePicker.delegate =self;

            imagePicker.allowsEditing =YES;

            imagePicker.sourceType =UIImagePickerControllerSourceTypeCamera;

            imagePicker.videoQuality =UIImagePickerControllerQualityTypeLow;

//            [self presentModalViewController:imagePicker animated:YES];

            [selfpresentViewController:imagePicker animated:YEScompletion:nil];

        }

           break;

       case 2://本地相簿

        {

            UIImagePickerController *imagePicker = [[UIImagePickerControlleralloc] init];

            imagePicker.delegate =self;

            imagePicker.allowsEditing =YES;

            imagePicker.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;

//            [self presentModalViewController:imagePicker animated:YES];

            [selfpresentViewController:imagePicker animated:YEScompletion:nil];

        }

           break;

       case 3://本地视频

        {

            UIImagePickerController *imagePicker = [[UIImagePickerControlleralloc] init];

            imagePicker.delegate =self;

            imagePicker.allowsEditing =YES;

            imagePicker.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;

//            [self presentModalViewController:imagePicker animated:YES];

            [selfpresentViewController:imagePicker animated:YEScompletion:nil];

        }

           break;

       default:

           break;

    }

}


#pragma mark -

#pragma UIImagePickerController Delegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{

    if ([[infoobjectForKey:UIImagePickerControllerMediaType]isEqualToString:(__bridgeNSString *)kUTTypeImage]) {

        UIImage *img = [infoobjectForKey:UIImagePickerControllerEditedImage];

        [selfperformSelector:@selector(saveImage:) withObject:img afterDelay:0.5];

    }

    elseif ([[info objectForKey:UIImagePickerControllerMediaType]isEqualToString:(__bridgeNSString *)kUTTypeMovie]) {

        NSString *videoPath = [[infoobjectForKey:UIImagePickerControllerMediaURL]path];

       self.fileData = [NSDatadataWithContentsOfFile:videoPath];

    }

//    [picker dismissModalViewControllerAnimated:YES];

    [picker dismissViewControllerAnimated:YEScompletion:nil];

}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker

{

//    [picker dismissModalViewControllerAnimated:YES];

        [picker dismissViewControllerAnimated:YEScompletion:nil];

}


- (void)saveImage:(UIImage *)image {

    //    NSLog(@"保存头像!");

    //    [userPhotoButton setImage:image forState:UIControlStateNormal];

   BOOL success;

    NSFileManager *fileManager = [NSFileManagerdefaultManager];

   NSError *error;

    

    NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

   NSString *documentsDirectory = [paths objectAtIndex:0];

   NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];

   NSLog(@"imageFile->>%@",imageFilePath);

    success = [fileManagerfileExistsAtPath:imageFilePath];

   if(success) {

        success = [fileManagerremoveItemAtPath:imageFilePath error:&error];

    }

//    UIImage *smallImage=[self scaleFromImage:image toSize:CGSizeMake(80.0f, 80.0f)];//将图片尺寸改为80*80

   UIImage *smallImage = [selfthumbnailWithImageWithoutScale:image size:CGSizeMake(93,93)];

    [UIImageJPEGRepresentation(smallImage,1.0f) writeToFile:imageFilePath atomically:YES];//写入文件

   UIImage *selfPhoto = [UIImageimageWithContentsOfFile:imageFilePath];//读取图片文件

   self.img.image = selfPhoto;

}


// 改变图像的尺寸,方便上传服务器

- (UIImage *) scaleFromImage: (UIImage *) image toSize: (CGSize) size

{

    UIGraphicsBeginImageContext(size);

    [imagedrawInRect:CGRectMake(0,0, size.width, size.height)];

    UIImage *newImage =UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

   return newImage;

}




//2.保持原来的长宽比,生成一个缩略图

- (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize

{

   UIImage *newimage;

   if (nil == image) {

        newimage =nil;

    }

   else{

       CGSize oldsize = image.size;

       CGRect rect;

       if (asize.width/asize.height > oldsize.width/oldsize.height) {

            rect.size.width = asize.height*oldsize.width/oldsize.height;

            rect.size.height = asize.height;

            rect.origin.x = (asize.width - rect.size.width)/2;

            rect.origin.y =0;

        }

       else{

            rect.size.width = asize.width;

            rect.size.height = asize.width*oldsize.height/oldsize.width;

            rect.origin.x =0;

            rect.origin.y = (asize.height - rect.size.height)/2;

        }

        UIGraphicsBeginImageContext(asize);

        CGContextRef context =UIGraphicsGetCurrentContext();

        CGContextSetFillColorWithColor(context, [[UIColorclearColor] CGColor]);

       UIRectFill(CGRectMake(0,0, asize.width, asize.height));//clear background

        [imagedrawInRect:rect];

        newimage = UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();

    }

   return newimage;

}

@end