開發(fā)筆記(圖片相冊相機(jī))

目錄

1.獲取圖片的自身大小
2.iOS系統(tǒng)8.x上面icon圖片花屏問題處理
3.圖片URL中含有中文無法顯示
4.iPhone上讀取圖片數(shù)據(jù)的簡單方法
5.跳轉(zhuǎn)相冊的時候想修改相冊上方導(dǎo)航欄的文字、顏色等
6.圖片壓縮并轉(zhuǎn)base64功能
7.圖片壓縮方法(知本家)
8.圖片選擇器:PictureSelector
9.iOS中圖片拉伸的幾種方式
10.相機(jī) - 相冊訪問
11.相機(jī)和相冊介紹
12.Xcode里面xx.xcassets圖標(biāo)1x、2x、3x什么時候調(diào)用

1.獲取圖片的自身大小

2.iOS系統(tǒng)8.x上面icon圖片花屏問題處理

這種情況下,把圖片資源直接放在bundle下,不要放在image assets下。
http://www.itdecent.cn/p/ca0bbb403143

3.圖片URL中含有中文無法顯示

在開發(fā)的過程中經(jīng)常會遇到記載圖片的問題,一般由后臺給我們提供圖片的鏈接地址,我們使用第三方庫進(jìn)行記載,而在個別圖片是帶有漢字的,導(dǎo)致圖片記載失敗導(dǎo)致一些問題。針對這個問題是由于,我們在使用帶有漢字的url請求時,漢字部分轉(zhuǎn)碼會出現(xiàn)錯誤。解決辦法是將url進(jìn)行UTF-8編碼轉(zhuǎn)換之后再請求,這樣就能順利加載出圖片了。圖片接口如:http: //7xq0ch.com1.z0.glb.clouddn.com//company/1521171384722/灰car5?e=1523763412&token=TwDqISTq2s5np1-

4.iPhone上讀取圖片數(shù)據(jù)的簡單方法

iPhone上讀取圖片數(shù)據(jù)的簡單方法有兩種:UIImageJPEGRepresentation和UIImagePNGRepresentation

1.JPEG需要兩個參數(shù):圖片的引用和壓縮系數(shù),PNG只需要圖片引用作為參數(shù)(這里JPEG表示UIImageJPEGRepresentation;PNG表示UIImagePNGRepresentation)
2.PNG比JPEG返回的圖片數(shù)據(jù)量大很多,耗時長,有時候會卡頓
3.JPEG可以通過更改壓縮系數(shù)縮小圖片數(shù)據(jù)量(如果對照片的清晰度沒有非常高的要求);而且從視角角度看,其圖片的質(zhì)量并沒有明顯的降低

  • 總結(jié):在讀取圖片數(shù)據(jù)內(nèi)容時,建議優(yōu)先使用UIImageJPEGRepresentation,并可根據(jù)自己的實際使用場景設(shè)置壓縮系數(shù),進(jìn)一步降低圖片數(shù)據(jù)量大小

相關(guān)鏈接:https://blog.csdn.net/he317165264/article/details/50401959

UIImage *getImage = [UIImage imageWithContentsOfFile:file];
NSData *data;
if (UIImagePNGRepresentation(getImage) == nil){
   data = UIImageJPEGRepresentation(getImage, 1);
} else {
   data = UIImagePNGRepresentation(getImage);
}
  • 例子:李庫管微信發(fā)送賬單的時候,使用UIImageJPEGRepresentation導(dǎo)致用[WXApi sendReq:req]方法時,iPhoneX無法授權(quán)微信(手機(jī)上已經(jīng)安裝了微信,但識別是沒有安裝);解決方法是改成使用UIImagePNGRepresentation方法,所以在這個微信調(diào)起的地方還是用PNG的圖片設(shè)置方法比較好
UIImagePNGRepresentation

5.跳轉(zhuǎn)相冊的時候想修改相冊上方導(dǎo)航欄的文字、顏色等

導(dǎo)航欄相關(guān)的文字、顏色等修改

6.圖片壓縮并轉(zhuǎn)base64功能

問題場景:填寫認(rèn)證信息的時候需要從手機(jī)選擇照片上傳到服務(wù)器,像素較高,上傳時間會很長,用戶體驗較差,所以通過壓縮上傳提高速度。

相關(guān)鏈接:
圖片壓縮:http://www.itdecent.cn/p/0b1d10cf8f61
圖片壓縮第三方庫:ZipArchive(https://github.com/ZipArchive/ZipArchive
圖片轉(zhuǎn)base64:
http://www.itdecent.cn/p/77d1370c0bab
http://www.itdecent.cn/p/91979b5def90

1.解決方法1:常規(guī)壓縮

// 圖片壓縮方法
- (NSData *)zipNSDataWithImage:(UIImage *)sourceImage{ //進(jìn)行圖像尺寸的壓縮
    
    CGSize imageSize = sourceImage.size;//取出要壓縮的image尺寸
    CGFloat width = imageSize.width; //圖片寬度
    CGFloat height = imageSize.height; //圖片高度 //1.寬高大于1280(寬高比不按照2來算,按照1來算)
    
    if (width>1280 || height>1280) {
        
        if (width>height) {
            
            CGFloat scale = height/width;
            width = 1280;
            height = width*scale;
        } else {
            
            CGFloat scale = width/height;
            height = 1280;
            width = height*scale;
        } //2.寬大于1280高小于1280
    } else if (width>1280 || height<1280) {
        
        CGFloat scale = height/width;
        width = 1280;
        height = width*scale; //3.寬小于1280高大于1280
        
    } else if (width<1280 || height>1280) {
        
        CGFloat scale = width/height;
        height = 1280;
        width = height*scale; //4.寬高都小于1280
    } 
    
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    [sourceImage drawInRect:CGRectMake(0,0,width,height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext(); //進(jìn)行圖像的畫面質(zhì)量壓縮
    NSData *data = UIImageJPEGRepresentation(newImage, 1.0);
    
    if (data.length>100*1024) {
        
        if (data.length>1024*1024) {//1M以及以上
            
            data = UIImageJPEGRepresentation(newImage, 0.7);
        } else if (data.length>512*1024) {//0.5M-1M
            
            data = UIImageJPEGRepresentation(newImage, 0.8);
        } else if (data.length>200*1024) { //0.25M-0.5M
            
            data = UIImageJPEGRepresentation(newImage, 0.9);
        }
    }
    return data;
}
要用的地方回調(diào)

2.解決方法2:第三方庫ZipArchive壓縮

大致代碼

7.圖片壓縮方法(知本家)

  • 封裝的方法
/// 圖片壓縮
/// @param originalImage 原圖片
/// @param imgWidth 裁剪的寬 默認(rèn)屏幕寬
/// @param imgHeight 裁剪的高 默認(rèn)屏幕高
/// @param qualityNum 圖片質(zhì)量設(shè)置 默認(rèn) 1
+ (UIImage *)compressImage:(UIImage *)originalImage andImageWidth:(CGFloat)imgWidth AndImageHeight:(CGFloat)imgHeight andImageQuality:(CGFloat)qualityNum {
    
    CGFloat scaleWidth;
    CGFloat scaleHeight;
    CGFloat widthInPoint;
    CGSize newSize;
    NSData *imageData = UIImageJPEGRepresentation(originalImage, 1.0);
    
    if (imageData.length>2*1024*1024) {
        
          if (imgWidth==0) {
              scaleWidth = [UIScreen mainScreen].bounds.size.width * 2;
              widthInPoint = scaleWidth / [[UIScreen mainScreen] scale];
          } else {
              scaleWidth = imgWidth * 2;
              widthInPoint = scaleWidth / [[UIScreen mainScreen] scale];
          }
          
          if (imgHeight==0) {
              scaleHeight = widthInPoint * originalImage.size.height / originalImage.size.width;
          } else {
              scaleHeight = imgHeight * 2;
              scaleHeight = scaleHeight / [[UIScreen mainScreen] scale];
          }
        
          newSize = CGSizeMake(widthInPoint,scaleHeight);
          UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:newSize];
          UIImage * tempImage = [renderer imageWithActions:^(UIGraphicsImageRendererContext * _Nonnull rendererContext) {
              [originalImage drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
          }];
          tempImage = [UIImage imageWithData:UIImageJPEGRepresentation(tempImage, qualityNum)];
          return tempImage;
    } else {
        return originalImage;
    }
}
  • 舉例實際應(yīng)用
//點擊相機(jī)方法
- (void)takingPictures {
    [self.imagePicker photographWithController:self selectedAssets:@[] finishPickering:^(NSArray<UIImage *> * _Nonnull photos, NSArray * _Nonnull assets) {
        
        UIImage *image = [UIImage imageWithData:UIImageJPEGRepresentation([photos[0] fixOrientation], 0.5)];
        NSData *fileData = UIImageJPEGRepresentation(image, 1.0);
        
        if (fileData.length >  20 * 1024 * 1024) {
            [MBProgressHUD showError:kLocLanguage(@"txt_JHAddInfoViewController_waringGigMessage") toView:kWindow];
        } else {
            image = [UIImage compressImage:image andImageWidth:0 AndImageHeight:0 andImageQuality:0.5];
            NSVillagePictureFileList *model = [NSVillagePictureFileList new];
            model.chooseImage = image;
            [self.dataArr addObj:model];
            [self.collectionView reloadData];
            [self setAddBtnFram];
        }
    }];
}

8.圖片選擇器:PictureSelector

http://www.itdecent.cn/p/cf091f9becfd?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

9.iOS中圖片拉伸的幾種方式

1.UIImageView整體拉伸

UIImageView-contentMode:

typedef NS_ENUM(NSInteger, UIViewContentMode) {    
UIViewContentModeScaleToFill,         // 默認(rèn) 拉伸(會變形)    
UIViewContentModeScaleAspectFit,      // 等比例拉伸    
UIViewContentModeScaleAspectFill,     // 等比例填充    
UIViewContentModeRedraw,              // redraw on bounds change (這個不清楚)     
UIViewContentModeCenter,              // 下面的就是不拉伸按位置顯示了    
UIViewContentModeTop,    
UIViewContentModeBottom,    
UIViewContentModeLeft,    
UIViewContentModeRight,    
UIViewContentModeTopLeft,    
UIViewContentModeTopRight,    
UIViewContentModeBottomLeft,    
UIViewContentModeBottomRight,
};

2.UIImage局部拉伸

// 按4邊間距顯示不拉伸的區(qū)域
- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets NS_AVAILABLE_IOS(5_0); 
// 按2點拉伸
- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight;
- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode;
// 拉伸模式
typedef NS_ENUM(NSInteger, UIImageResizingMode) {    
UIImageResizingModeTile,//進(jìn)行區(qū)域復(fù)制模式拉伸    
UIImageResizingModeStretch,//進(jìn)行漸變復(fù)制模式拉伸
};

3.UIImage修改大小

//內(nèi)縮放,一條變等于最長邊,另外一條小于等于最長邊
- (UIImage *)scaleToSize:(CGSize)newSize {    
CGFloat width = self.size.width;    
CGFloat height= self.size.height;    
CGFloat newSizeWidth = newSize.width;    
CGFloat newSizeHeight= newSize.height;    
if (width <= newSizeWidth &&height <= newSizeHeight) 
{        
return self;    
}        
if (width == 0 || height == 0 || newSizeHeight == 0 || newSizeWidth == 0) 
{        
return nil;    
}    
CGSize size;    
if (width / height > newSizeWidth / newSizeHeight) 
{        
size = CGSizeMake(newSizeWidth, newSizeWidth * height / width);    
} 
else 
{        
size = CGSizeMake(newSizeHeight * width / height, newSizeHeight);    
}    
return [self drawImageWithSize:size];
}

- (UIImage *)drawImageWithSize: (CGSize)size {    
CGSize drawSize = CGSizeMake(floor(size.width), floor(size.height));    
UIGraphicsBeginImageContext(drawSize);        
[self drawInRect:CGRectMake(0, 0, drawSize.width, drawSize.height)];   
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
UIGraphicsEndImageContext();    
return newImage;
}

4.images.xcassets

在Xcode中選中圖片,然后點擊右下角的Show Slicing
slicing 面板和一個按鈕"Start Slicing
點擊按鈕之后,會顯示下面的三個選項,左邊的按鈕用于horizontal edge insets,右邊的按鈕用于vertical edge insets,中間的則是兩個都有。在我們的例子中要保留圓角,所以我們按中間的按鈕,告訴系統(tǒng)我們想要按鈕的中間在水平和垂直方向拉伸。在按下按鈕之后,就能看到一些可以拖動的細(xì)條,這可以設(shè)置從哪里開始拉伸圖片
系統(tǒng)會保留深紫色的區(qū)域,淺紫色的區(qū)域會被拉伸
更厲害的是,Xcode自動找到了圓角,所以我們不需要設(shè)置從哪里開始拉伸圖片。最后別忘了在Attribtues pane中設(shè)置圖片是可拉伸的

如果我是你的話,我就會嘗試并習(xí)慣這個功能。有了這個無價之寶,你就不用再在resizableImageWithCapInsets方法中填寫那些神奇的數(shù)字了,也能幫助你分離view邏輯和app邏輯。轉(zhuǎn)載自原文

10.相機(jī) - 相冊訪問

1.問題描述

1.訪問相機(jī)和相冊的時候,如果用戶拒絕訪問,則進(jìn)入顯示系統(tǒng)的頁面,想改里面的導(dǎo)航攔右邊的取消按鈕的顏色
2.初次下載app時相機(jī)和相冊的訪問權(quán)限的設(shè)置操作(注意分為:根據(jù)狀態(tài)來判斷 || 根據(jù)允許和不允許的操作回調(diào)來判斷)

2.解決問題

  • 改變顏色
[[UINavigationBar appearance] setBarTintColor: [UToColor whiteColor]];
[[UINavigationBar appearance] setTintColor:[UToColor blackColor]];
[[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UToColor blackColor],NSFontAttributeName:[UToFont defaultAdaptationFontWithSize:16.0]}];
  • 權(quán)限設(shè)置問題
    1.根據(jù)按鈕的回調(diào)方法來判斷:(即用戶還沒有點擊過允許和不允許,現(xiàn)在進(jìn)行點擊來獲取相應(yīng)展示)
// 相機(jī)
[_selectHeadImgView camerBtnClick:^(UIButton *sender){// 相機(jī)
        
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
          [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {//相機(jī)權(quán)限
                
             if (granted) {
                    
                    UIImagePickerController *imagePickerVC = [[UIImagePickerController alloc] init];
                    imagePickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
                    imagePickerVC.modalPresentationStyle = UIModalPresentationCurrentContext;
                    [[UINavigationBar appearance] setBarTintColor: [UToColor whiteColor]];
                    [[UINavigationBar appearance] setTintColor:[UToColor blackColor]];
                    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UToColor blackColor],NSFontAttributeName:[UToFont defaultAdaptationFontWithSize:16.0]}];
                    imagePickerVC.allowsEditing = YES;
                    imagePickerVC.delegate = self;
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        [self presentViewController:imagePickerVC animated:YES completion:NULL];
                    });
                } else {
                    
                    UToAlert *aler =[UToAlert AlertTitle:@"無法使用相機(jī)" content:@"請在iPhone的“設(shè)置-隱私-相機(jī)”中允許訪問相機(jī)。" cancelButton:@"" okButton:@"確定" complete:nil];
                    [aler showAlertWithController:self];
                }
            }];
        }
    }];
 
// 相冊
    [_selectHeadImgView photoBtnClick:^(UIButton *sender){// 照片
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                
                if (status == PHAuthorizationStatusAuthorized) {
                    
                } else {
                    
                }
                UIImagePickerController * imagePickerVC = [[UIImagePickerController alloc]init];
                imagePickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                [[UINavigationBar appearance] setBarTintColor: [UToColor whiteColor]];
                [[UINavigationBar appearance] setTintColor:[UToColor blackColor]];
                [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UToColor blackColor],NSFontAttributeName:[UToFont defaultAdaptationFontWithSize:16.0]}];
                imagePickerVC.allowsEditing = YES;
                imagePickerVC.modalPresentationStyle = UIModalPresentationCurrentContext;
                imagePickerVC.delegate = self;
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [self presentViewController:imagePickerVC animated:YES completion:NULL];
                });
            }];
        }
    }];

2.根據(jù)狀態(tài)來判斷:(即用戶已經(jīng)做過允許與不允許的操作之后,再根據(jù)這個用戶的反饋狀態(tài)來判斷展示)

11.相機(jī)和相冊介紹

控制器了解篇章中的 UIImagePickController部分:http://www.itdecent.cn/p/6ce0a8cdc02a

開啟相機(jī)或相冊的代碼如下所示:

// 創(chuàng)建一個圖像選擇視圖控制器
UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
// 檢查相機(jī)是否可用
if ([UIImagePickerController 
        isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
    // 相機(jī)可用就使用相機(jī)
    ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
}
else {
    // 相機(jī)不可用就使用相冊
    ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
// 允許編輯照片
ipc.allowsEditing = YES;
// 綁定委托
ipc.delegate = self;
[self presentViewController:ipc animated:YES completion:nil];

UIImagePickerControllerDelegate的兩個回調(diào)方法:

// 選中照片執(zhí)行的回調(diào)方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    // info參數(shù)是一個字典,可以取出原始照片或編輯后的照片
}
// 取消選擇照片的回調(diào)方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {

}

說明:在開啟相機(jī)時可以通過設(shè)置UIImagePickerController對象的mediaTypes屬性來支持?jǐn)z像操作,攝像完成后需要調(diào)用UISaveVideoAtPathToSavedPhotosAlbum函數(shù)將保存在臨時文件夾下的視頻文件保存到相冊中,當(dāng)然在此之前最好用UIVideoAtPathIsCompatibleWithSavedPhotosAlbum函數(shù)判斷能否保存,在此之后可以通過NSFileManager對象的removeItemAtPath:error:方法將臨時文件刪除

Demo代碼如下:

注意在plist文件中添加相應(yīng)屬性(否則會奔潰):NSMicrophoneUsageDescription、NSCameraUsageDescription、NSPhotoLibraryUsageDescription

效果:

補(bǔ)充拓展

12.Xcode里面xx.xcassets圖標(biāo)1x、2x、3x什么時候調(diào)用

Xcode里面xx.xcassets(xx是文件名稱,一般自帶叫Assets,可以進(jìn)行更改)文件中的圖標(biāo)1x、2x、3x是系統(tǒng)自動調(diào)用,一般小手機(jī)調(diào)用1x和2x,大手機(jī)調(diào)用3x,比如:iPhone4以下機(jī)型圖標(biāo)會調(diào)用1x、6調(diào)用2x、6p和x系列調(diào)用3x。

補(bǔ)充:

1.通常盡量將圖片資源放入 Images.xcassets 中,包括 pod 庫的圖片。 Images.xcassets 中的圖片加載后會有緩存,提升加載速度,并且在最終打包時會自動進(jìn)行壓縮(Compress PNG Files),再根據(jù)最終運行設(shè)備進(jìn)行 1x、2x、3x 分發(fā)。

2.對于內(nèi)部 Pod 庫中的資源文件,我們可以在 Pod 庫里面的 Resources 目錄下新建 Asset Catalog 文件,命名為 Images.xcassets,移入所有圖片文件,接著手動修改該 SDK 的 podspec 文件指定使用該 Images.xcassets。

RTImageAssets - Xcode 插件:https://github.com/rickytan/RTImageAssets
RTImageAssets 是 Xcode 插件,用來生成 @3x 的圖片資源對應(yīng)的 @2x 和 @1x 版本,只要拖拽高清圖到 @3x 的位置上,然后按 Ctrl+Shift+A 即可自動生成兩張低清的補(bǔ)全空位,還可以從 @2x 的圖生成 @3x 版本,如果你對圖片質(zhì)量要求不高的話。

.xcassets文件夾中圖標(biāo)1x、2x、3x
1x、2x、3x說明
最后編輯于
?著作權(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ù)。

相關(guān)閱讀更多精彩內(nèi)容

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