关于UIImage转NSData (UIImagePNGRepresentation)返回为nil的情况

业务场景:

在自己做二维码生成,生成以后需要传递图片到后端,结果发现APP一直在闪退,断点调试的时候,发现问题出现在了UIImage转NSData这一步,也就是以下这两个方法:

UIImagePNGRepresentation

UIImageJPEGRepresentation

(两个方法的差异我就不赘述了,可以自己百度下)

实际在执行这个方式时,返回了一个nil对象,导致了上传的时候,appendPartWithFileData数据为空而崩溃了;其实以前一直是这样操作的,一直没想到为什么会为nil

经过参考官方文档,发现了问题:
在苹果官方的文档里面写着这么一句
“ return image as JPEG. May return nil if image has no CGImageRef or invalid bitmap format. compression is 0(most)..1(least)”

也就是当没有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);
//翻转一下图片 不然生成的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,当执行方法生成的图片,去打印 colorCodeImage的CGImage

NSLog(@"%@", colorCodeImage.CGImage)

执行结果是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();
    //关闭图形上下文
    UIGraphicsEndImageContext();
    return newImage;
}

当拿到现在的newImage的时候,发现正常能够执行相应的转换NSData的方法了;

你可能感兴趣的:(关于UIImage转NSData (UIImagePNGRepresentation)返回为nil的情况)