分享最實(shí)用的技術(shù),創(chuàng)造更大的價(jià)值

xcode iOS 獲取后臺圖片base64data數(shù)據(jù)轉(zhuǎn)換UIimage圖片失敗問題解決

base64 數(shù)據(jù) 一般是字符串類型的數(shù)據(jù),格式如:data:image/png;base64,xx...........................這樣的數(shù)據(jù)。


首先,data:image/png;base64, 是固定的前綴數(shù)據(jù),需要?jiǎng)h除。注意,包含 逗號


其次,對字符串進(jìn)行換行符、空字符去除,使其得到一個(gè)標(biāo)準(zhǔn)的可以轉(zhuǎn)換圖片的 base64 字符串?dāng)?shù)據(jù)。


這樣就可以在xcode中,將base64字符串轉(zhuǎn)為nsdata,再轉(zhuǎn)為uiimage了

xcode iOS 獲取后臺圖片base64data數(shù)據(jù)轉(zhuǎn)換UIimage圖片失敗問題解決


            //strImgDataNew 為base64 NSString
            
            //進(jìn)行首尾空字符串的處理
            strImgDataNew = [strImgDataNew stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去除掉首尾的空白字符和換行字符
            
            //進(jìn)行空字符串的處理
            strImgDataNew = [strImgDataNew stringByReplacingOccurrencesOfString:@"\r" withString:@""];
            
            //進(jìn)行換行字符串的處理
            strImgDataNew = [strImgDataNew stringByReplacingOccurrencesOfString:@"\n" withString:@""];
            
            //去掉頭部的前綴//data:image/jpeg;base64, (可根據(jù)實(shí)際數(shù)據(jù)情況而定,如果數(shù)據(jù)有固定的前綴,就執(zhí)行下面的方法,如果沒有就注銷掉或刪除掉)
            // str = [str substringFromIndex:23];   //23 是根據(jù)前綴的具體字符長度而定的。
            
            NSString*encodedImageStr = strImgDataNew;
            
            //進(jìn)行字符串轉(zhuǎn)data數(shù)據(jù) -------NSDataBase64DecodingIgnoreUnknownCharacters
            
            NSData *decodedImgData = [[NSData alloc] initWithBase64EncodedString:encodedImageStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
            
            //把data數(shù)據(jù)轉(zhuǎn)換成圖片內(nèi)容
            UIImage*decodedImage = [UIImage imageWithData:decodedImgData];


聯(lián)系
QQ
電話
咨詢電話:189-8199-7898
TOP