MacOS: Programmatically add text to an image?

I am converting some code from linux to mac.

How can I programmatically overlay an image with text, like the ImageMagick convert command? For various reasons, I cannot depend on the installation of ImageMagick.

convert -draw 'text 50,800 "hello world"' f1.png f2.png
0
source share
1 answer

You can use the API-interfaces NSImage, and NSStringfor creating the edited image, and then use NSBitmapImageRepto get data for PNG images. Example:

NSString *text = @"hello world";
NSImage *f1 = [[NSImage alloc] initWithContentsOfFile:@"/path/to/f1.png"];
NSImage *f2 = [NSImage imageWithSize:f1.size flipped:YES drawingHandler:^BOOL(NSRect dstRect) {
    [f1 drawInRect:dstRect];

    // Attributes can be customized to change font, text color, etc.
    NSDictionary *attributes = @{NSFontAttributeName: [NSFont systemFontOfSize:17]};
    [text drawAtPoint:NSMakePoint(50, 800) withAttributes:attributes];

    return YES;
}];
NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithCGImage:[f2 CGImageForProposedRect:NULL context:nil hints:nil]];
NSData *data = [rep representationUsingType:NSPNGFileType properties:nil];
[data writeToFile:@"/path/to/f2.png" atomically:YES];
+5
source

All Articles