UIimage to NSData returns Null

2019-08-09 22:17发布

I created a QR code image and displayed it in a UIImageView

NSString *QRMessage = @"MESSAGE";

NSData *data = [QRMessage dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:false];
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
[filter setValue:data forKey:@"inputMessage"];
[filter setValue:@"Q" forKey:@"inputCorrectionLevel"];

imageQRCode = filter.outputImage; // imageQRCode is CIImage
ivQR.image = [UIImage imageWithCIImage: imageQRCode]; // ivQR is UIImageView

I'm trying to save the image so the user can somehow send the QR code to another person. I first tried saving it to the "Clipboard" like this...

UIPasteboard *pasteBoard = [UIPasteboard pasteboardWithName:UIPasteboardNameGeneral create:NO];
[pasteBoard setPersistent:true];
[pasteBoard setImage:ivQR.image];

... but it appears nothing is saved in the Clipboard.

So then I tried converting the UIImage to NSData and adding it as an attachment like so:

MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
UIImage *imageToSend = [UIImage imageWithCIImage:imageQRCode];
NSData *data = UIImageJPEGRepresentation(imageToSend,1);
[picker addAttachmentData:data  mimeType:@"image/jpeg" fileName:@"QR.jpg"];

But again nothing seems to be attached.

I did some testing and it appears that the NSData I'm getting back from "UIImageJPEGRepresentation()" gives me "Null" data. The image does in fact get displayed on my phone, so I'm wondering if I'm just converting the data wrong?

Most of my "googling" tells me that the way I'm converting is correct. But most of the examples use a Picture on the user's phone, or a Picture added to the App itself. My Picture is "created"... so does that make a difference?

My goal is to allow the user to Copy to Clipboard, or Add as Attachment of the QR Image. Any assistance is greatly appreciated.

1条回答
等我变得足够好
2楼-- · 2019-08-09 22:26

When converting a CIImage to UIImage, I've found that imageWithCIImage often doesn't work. I generally use CIContext method createCGImage and then create the UIImage from that:

CIImage *ciImage     = ...
CIContext *context   = [CIContext contextWithOptions:nil];
CGImageRef cgImage   = [context createCGImage:ciImage fromRect:rect];
UIImage *image       = [UIImage imageWithCGImage:cgImage];
CGImageRelease(cgImage);

See samples in Core Image Programming Guide.

查看更多
登录 后发表回答