業(yè)務(wù)場景:
在自己做二維碼生成弱恒,生成以后需要傳遞圖片到后端射亏,結(jié)果發(fā)現(xiàn)APP一直在閃退虫腋,斷點調(diào)試的時候莽红,發(fā)現(xiàn)問題出現(xiàn)在了UIImage轉(zhuǎn)NSData這一步妥畏,也就是以下這兩個方法:
UIImagePNGRepresentation
UIImageJPEGRepresentation
(兩個方法的差異我就不贅述了,可以自己百度下)
實際在執(zhí)行這個方式時安吁,返回了一個nil對象醉蚁,導(dǎo)致了上傳的時候,appendPartWithFileData數(shù)據(jù)為空而崩潰了鬼店;其實以前一直是這樣操作的网棍,一直沒想到為什么會為nil
經(jīng)過參考官方文檔,發(fā)現(xiàn)了問題:
在蘋果官方的文檔里面寫著這么一句
“ return image as JPEG. May return nil if image has no CGImageRef or invalid bitmap format. compression is 0(most)..1(least)”
也就是當(dāng)沒有CGImageRef的時候妇智,會造成這個方法返回為空滥玷;然后我又回溯了一下自己生成二維碼的方法:
CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
[qrFilter setValue:stringData forKey:@"inputMessage"];
[qrFilter setValue:@"M" forKey:@"inputCorrectionLevel"];
CIImage *qrImage = qrFilter.outputImage;
//放大并繪制二維碼 (上面生成的二維碼很小,需要放大)
CGImageRef cgImage = [[CIContext contextWithOptions:nil] createCGImage:qrImage fromRect:qrImage.extent];
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetInterpolationQuality(context, kCGInterpolationNone);
//翻轉(zhuǎn)一下圖片 不然生成的QRCode就是上下顛倒的
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, CGContextGetClipBoundingBox(context), cgImage);
UIImage *codeImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRelease(cgImage);
//繪制顏色
CIFilter *colorFilter = [CIFilter filterWithName:@"CIFalseColor"
keysAndValues:
@"inputImage",[CIImage imageWithCGImage:codeImage.CGImage],
@"inputColor0",[CIColor colorWithCGColor:frontColor == nil ? [UIColor clearColor].CGColor: frontColor.CGColor],
@"inputColor1",[CIColor colorWithCGColor: backColor == nil ? [UIColor blackColor].CGColor : backColor.CGColor],
nil];
UIImage * colorCodeImage = [UIImage imageWithCIImage:colorFilter.outputImage];
其實自己用到的巍棱,就是CIImage惑畴,當(dāng)執(zhí)行方法生成的圖片,去打印 colorCodeImage的CGImage
NSLog(@"%@", colorCodeImage.CGImage)
執(zhí)行結(jié)果是nil
以此航徙,找到了問題的所在如贷,如果這樣的話,那就重新生成一下圖片就行了
直接貼上代碼,需要的研究一下
- (UIImage *)scaleImage:(UIImage *)image{
//確定壓縮后的size
CGFloat scaleWidth = image.size.width;
CGFloat scaleHeight = image.size.height;
CGSize scaleSize = CGSizeMake(scaleWidth, scaleHeight);
//開啟圖形上下文
UIGraphicsBeginImageContext(scaleSize);
//繪制圖片
[image drawInRect:CGRectMake(0, 0, scaleWidth, scaleHeight)];
//從圖形上下文獲取圖片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
//關(guān)閉圖形上下文
UIGraphicsEndImageContext();
return newImage;
}
當(dāng)拿到現(xiàn)在的newImage的時候杠袱,發(fā)現(xiàn)正常能夠執(zhí)行相應(yīng)的轉(zhuǎn)換NSData的方法了泻红;