Home > Software design >  Print NSImage from base64 string
Print NSImage from base64 string

Time:08-11

I'd like to print a base64 encoded image (passed in from canvas in a web view). How can I read/print a base64 string? Here's what I have so far:

- (void) printImage:(NSString *)printerName andData:(NSString *)base64img andW:(float)paperW andH:(float)paperH {
    
    NSImage *img = [base64img dataUsingEncoding:NSDataBase64Encoding64CharacterLineLength];
    
    NSPrintInfo *printInfo = [NSPrintInfo sharedPrintInfo];
    [printInfo setTopMargin:0.0];
    [printInfo setBottomMargin:0.0];
    [printInfo setLeftMargin:0.0];
    [printInfo setRightMargin:0.0];
    [printInfo setHorizontalPagination:NSFitPagination];
    [printInfo setVerticalPagination:NSFitPagination];
    
    [printInfo setPaperSize:NSMakeSize(paperW, paperH)];
    [printInfo setPrinter:[NSPrinter printerWithName:printerName]];
    
    NSPrintOperation *op = [img printOperationForPrintInfo: printInfo autoRotate: YES];
    
    [op setShowsPrintPanel:NO];
    [op setShowsProgressPanel:NO];
    [op runOperation];
}

Thanks in advance!

CodePudding user response:

This line has at least three errors:

NSImage *img = [base64img dataUsingEncoding:NSDataBase64Encoding64CharacterLineLength];
  • First, the dataUsingEncoding: message asks the string to encode itself as data, but you want a decode operation, not an encode operation.

  • Second, the dataUsingEncoding: method requires an NSStringEncoding argument, and NSDataBase64Encoding64CharacterLineLength is not an NSStringEncoding. (It is an NSDataBase64EncodingOptions.)

    Unfortunately, because you are using Objective-C instead of Swift, the compiler doesn't reject this code. (Maybe it gives a warning though? I didn't try it.)

  • Third, dataUsingEncoding: returns an NSData, not an NSImage. I'm pretty sure the compiler emits at least a warning for this.

You need to decode the string to an NSData using initWithBase64EncodingString:options:, and then you need to create an NSImage from the NSData using initWithData:.

NSData *data = [[NSData alloc] initWithBase64EncodedString:base64img
    options:NSDataBase64DecodingIgnoreUnknownCharacters];
if (data == nil) {
    return;
}

NSImage *img = [[NSImage alloc] initWithData:data];
if (img == nil) {
    return;
}
  • Related