MacOS:以编程方式向图像添加一些文本?

Mar*_*son 0 macos image

我正在将一些代码从linux转换为mac.

如何使用文本以编程方式覆盖图像,类似于ImageMagick转换命令?由于各种原因,我不能依赖于安装ImageMagick.

convert -draw 'text 50,800 "hello world"' f1.png f2.png
Run Code Online (Sandbox Code Playgroud)

ind*_*gie 5

您可以使用NSImageNSString绘图API创建已编辑的图像,然后使用它NSBitmapImageRep来获取图像的PNG数据.例:

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];
Run Code Online (Sandbox Code Playgroud)