OC調(diào)用相機并且給拍好的照片添加水印

OC調(diào)用相機并且給拍好的照片添加水印

今天我們學(xué)習(xí)一下iOS調(diào)用原生相機并且給照片添加水印要怎么做。

首先我們新建一個項目,在開始寫代碼之前我們要添加權(quán)限。找到項目的Info.plist文件,添加相機和相冊的使用權(quán)限。右鍵>Add Row 添加 "Privacy - Photo Library Usage Description" 和 "Privacy - Camera Usage Description"的key。value填寫自定義提示文字。(當(dāng)用戶第一次要使用相機和相冊的時候會彈出提示框)


1-1

Privacy - Photo Library Usage Description
Privacy - Camera Usage Description

話不多說直接貼代碼。

先導(dǎo)入頭文件

#import <Photos/Photos.h>
@interface ViewController ()<UIImagePickerControllerDelegate>
@property (strong,nonatomic)  UIImagePickerController * pickerImage;

UIImagePickerController的初始化

self.pickerImage =[[UIImagePickerController alloc] init];
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;//設(shè)置類型為相機
        self.pickerImage.delegate = self;//設(shè)置代理
        self.pickerImage.allowsEditing = YES;//設(shè)置照片可編輯
        self.pickerImage.sourceType = sourceType;
        //設(shè)置是否顯示相機控制按鈕 默認為YES
        self.pickerImage.showsCameraControls = YES;

        //創(chuàng)建疊加層(例如添加的相框,這里通過這種方式可以在拍照的時候把水印直接顯示在相機上) 
        UIView *overLayView=[[UIView alloc]initWithFrame:CGRectMake(0, 60, s_width, s_height - 200)];
        UILabel * telLbl = [[UILabel alloc]initWithFrame:CGRectMake(40, s_height - 300 - 200, 300, 30)];
        telLbl.textColor = UIColor.whiteColor;
        telLbl.text = [NSString stringWithFormat:@"手機號:%@",self.shouji.text];
        [overLayView addSubview:telLbl];
        UILabel * jingduLbl = [[UILabel alloc]initWithFrame:CGRectMake(40, s_height - 268 - 200, 300, 30)];
        jingduLbl.text =  [NSString stringWithFormat:@"經(jīng)度:%@",jingdu] ;
        jingduLbl.textColor = UIColor.whiteColor;
        [overLayView addSubview:jingduLbl];
        UILabel * weiduLbl = [[UILabel alloc]initWithFrame:CGRectMake(40, s_height - 236 - 200, 300, 30)];
        weiduLbl.text = [NSString stringWithFormat:@"緯度:%@",weidu];
        weiduLbl.textColor = UIColor.whiteColor;
        [overLayView addSubview:weiduLbl];
        UILabel * dizhiLbl = [[UILabel alloc]initWithFrame:CGRectMake(40, s_height - 202 - 200, 400, 30)];
        dizhiLbl.text = [NSString stringWithFormat:@"地址:%@",dizhi];
        dizhiLbl.textColor = UIColor.whiteColor;
        [overLayView addSubview:dizhiLbl];
        UILabel * shijianLbl = [[UILabel alloc]initWithFrame:CGRectMake(40, s_height - 170 - 200, 300, 30)];
        shijianLbl.text = [NSString stringWithFormat:@"時間:%@",currentDateStr];
        shijianLbl.textColor = UIColor.whiteColor;
        [overLayView addSubview:shijianLbl];
        UILabel * beizhuLbl = [[UILabel alloc]initWithFrame:CGRectMake(40, s_height - 138 - 200, 300, 30)];
        beizhuLbl.text = [NSString stringWithFormat:@"備注:%@",self.beizhu.text];;
        beizhuLbl.textColor = UIColor.whiteColor;
        [overLayView addSubview:beizhuLbl];

        //選擇前置攝像頭或后置攝像頭
        self.pickerImage.cameraDevice=UIImagePickerControllerCameraDeviceRear;
        //調(diào)用系統(tǒng)攝像頭
        [self presentViewController:self.pickerImage animated:YES completion:^{
        }];
        }

拍照以后通過代理方法獲取當(dāng)前得到的圖片

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    // 獲取用戶拍攝的是照片還是視頻
   UIImage *theImage =nil;
        // 判斷,圖片是否允許修改
   if ([picker allowsEditing])
   {
       // 獲取用戶編輯之后的圖像
       theImage = [info objectForKey:UIImagePickerControllerEditedImage];
   }
   else
   {
       // 獲取原始的照片
       theImage = [info objectForKey:UIImagePickerControllerOriginalImage];
   }
    [self composeImg:theImage];
}

水印簡單來說就是兩張圖片何在一起,我們現(xiàn)在現(xiàn)在來通過UIView畫一張圖片,把它當(dāng)做簡單的水印,當(dāng)然大家自己有水印素材可以直接跳過這一步,用兩個UIImage對象去合成一張圖片

- (void)initLogoImage
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //設(shè)定時間格式,這里可以設(shè)置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //用[NSDate date]可以獲取系統(tǒng)當(dāng)前時間
    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    //創(chuàng)建疊加層(例如添加的相框)
    UIView *overLayView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, s_width, s_height - 200)];
    UILabel * telLbl = [[UILabel alloc]initWithFrame:CGRectMake(40, s_height - 300 - 200, 300, 30)];
    telLbl.textColor = UIColor.whiteColor;
    telLbl.text = [NSString stringWithFormat:@"手機:%@",self.shouji.text];
    [overLayView addSubview:telLbl];
    UILabel * jingduLbl = [[UILabel alloc]initWithFrame:CGRectMake(40, s_height - 268 - 200, 300, 30)];
    jingduLbl.text =  [NSString stringWithFormat:@"經(jīng)度:%@",jingdu] ;
    jingduLbl.textColor = UIColor.whiteColor;
    [overLayView addSubview:jingduLbl];
    UILabel * weiduLbl = [[UILabel alloc]initWithFrame:CGRectMake(40, s_height - 236 - 200, 300, 30)];
    weiduLbl.text = [NSString stringWithFormat:@"緯度:%@",weidu];
    weiduLbl.textColor = UIColor.whiteColor;
    [overLayView addSubview:weiduLbl];
    UILabel * dizhiLbl = [[UILabel alloc]initWithFrame:CGRectMake(40, s_height - 202 - 200, 400, 30)];
    dizhiLbl.text = [NSString stringWithFormat:@"地址:%@",dizhi];
    dizhiLbl.textColor = UIColor.whiteColor;
    [overLayView addSubview:dizhiLbl];
    UILabel * shijianLbl = [[UILabel alloc]initWithFrame:CGRectMake(40, s_height - 170 - 200, 300, 30)];
    shijianLbl.text = [NSString stringWithFormat:@"時間:%@",currentDateStr];
    shijianLbl.textColor = UIColor.whiteColor;
    [overLayView addSubview:shijianLbl];
    UILabel * beizhuLbl = [[UILabel alloc]initWithFrame:CGRectMake(40, s_height - 138 - 200, 300, 30)];
    beizhuLbl.text = [NSString stringWithFormat:@"備注:%@",self.beizhu.text];
    beizhuLbl.textColor = UIColor.whiteColor;
    [overLayView addSubview:beizhuLbl];
    overLayView.backgroundColor = [UIColor clearColor];
    _logoImage = [self convertViewToImage:overLayView];
}

// 傳入UIView生成UIImage對象使用該方法不會模糊,根據(jù)屏幕密度計算
- (UIImage *)convertViewToImage:(UIView *)view {
    UIImage *imageRet = [[UIImage alloc]init];
    //UIGraphicsBeginImageContextWithOptions(區(qū)域大小, 是否是非透明的, 屏幕密度); 這里透明度指的是背景是否透明
    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    imageRet = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return imageRet;
}

ConvertViewToImage的方法拿到的圖片我們把它作為水印和拍好的照片畫到一起

// 我這里方法傳進來的是主圖片 _logoImage是作為水印圖片
- (void)composeImg:(UIImage *)image{
    CGFloat w = 1000;
    CGFloat h = 1000;
    //以主圖片的大小作為底圖
    //以主圖片為畫布創(chuàng)建上下文
    UIGraphicsBeginImageContext(CGSizeMake(s_width, s_height));
    //先把1.png 畫到上下文中
    [image drawInRect:CGRectMake(0, 0, s_width, s_height)];
    //再把小圖放在上下文中  位子坐標自己慢慢調(diào)整
    [_logoImage drawInRect:CGRectMake(20, 20, w, h)];
    //從當(dāng)前上下文中獲得最終圖片
    UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();//關(guān)閉上下文
    // 預(yù)覽我們合成的照片
    [self showResultPhoto:resultImg];
}
    // 預(yù)覽我們得到的圖片 
- (void)showResultPhoto:(UIImage *)image{
    photoImage = [UIImageView new];
    photoImage.image = image;
    [self.view addSubview:photoImage];
    photoImage.frame = self.view.frame;
    saveBtn = [UIButton allloc]initWithFrame:CGRectMake(x, y, width, height)];// 保存圖片的按鈕
    [saveBtn setTitle:@"使用相片" forState:UIControlStateNormal];
    self.phtotImage = image;
    [saveBtn addTarget:self action:@selector(saveSWPhoto) forControlEvents:UIControlEventTouchUpInside];
    [saveBtn setBackgroundColor:UIColor.grayColor];
    [self.view addSubview:saveBtn];
}
// 保存所得到的圖片
- (void)saveSWPhoto{
    ShowHUBInController;
    [[PHPhotoLibrary sharedPhotoLibrary]performChanges:^{
        [PHAssetChangeRequest creationRequestForAssetFromImage:self.phtotImage];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                HideHUBInController;;
                ShowHUBInWindowAutoHid(@"保存失敗");
            });

            NSLog(@"%@",@"保存失敗");
            NSLog(@"%@",error);
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                HideHUBInController;
                ShowHUBInWindowAutoHid(@"保存成功");
            });
            NSLog(@"%@",@"保存成功");
        }
    }];
}

這里我們來看看軟件的截圖和拍出的照片的樣子吧


打開相機

預(yù)覽照片

保存到相冊的照片

感覺還是不錯的,嘿嘿。有什么不好的地方麻煩大家?guī)兔χ赋?,我們共同學(xué)習(xí)。
如果能幫到大家,就給我點個贊吧。謝謝大家。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容