UIImageWriteToSavedPhotosAlbum方法保存图片到相册,相册找不到

今天分享个小知识,项目需求生成二维码,然后把二维码图片保存到相册

很简单,使用系统方法

    UIImageWriteToSavedPhotosAlbum(cgImage, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);

- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSString *message = @"";
    if (!error) {
        message = @"成功保存到相册";
        [self.view makeToast:message duration:DisShowTime position:CSToastPositionBottom];
    }else
    {
        message = [error description];
        [self.view makeToast:@"保存失败" duration:DisShowTime position:CSToastPositionBottom];
    }
    NSLog(@"message is %@",message);
    
    
}

然后就发现保存成功, 相册中确没有找到

顺便把二维码生成也放上面


- (CIImage *)generateQRCode:(NSString *)code width:(CGFloat)width height:(CGFloat)height {
    
    // 生成二维码图片
    CIImage *qrcodeImage;
    NSData *data = [code dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:false];
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [filter setValue:data forKey:@"inputMessage"];
    [filter setValue:@"H" forKey:@"inputCorrectionLevel"];
    qrcodeImage = [filter outputImage];
    
    // 消除模糊
    CGFloat scaleX = width / qrcodeImage.extent.size.width; // extent 返回图片的frame
    CGFloat scaleY = height / qrcodeImage.extent.size.height;
    CIImage *transformedImage = [qrcodeImage imageByApplyingTransform:CGAffineTransformScale(CGAffineTransformIdentity, scaleX, scaleY)];
    
    return transformedImage;
}

下面直接结论了:

经过一番测试,发现方法[UIImage imageWithCIImage:codeImage];生产的UIImage并不算是实际意义上的图片UIImage.CGImage为nil,而相册保存方法UIImageWriteToSavedPhotosAlbum所保存的就是UIImage.CGImage

下面就简单了,先
CCImage ——> CGImage
CGImage ——> UIImage

   // self.img 为 CIImage对象
    CIFilter *filter = [CIFilter filterWithName:@"CISepiaTone"];
    [filter setValue:self.img forKey:kCIInputImageKey];
    
    [filter setValue:@0.5 forKey:kCIInputIntensityKey];
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef imageRef = [context createCGImage:filter.outputImage fromRect:filter.outputImage.extent];
    UIImage *cgImage = [UIImage imageWithCGImage:imageRef];

此时cgImage.CGImage就有值了,在执行保存操作即可

推荐阅读更多精彩内容