MacOS:以编程方式向图像添加一些文本? [英] MacOS: Programmatically add some text to an image?

查看:74
本文介绍了MacOS:以编程方式向图像添加一些文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm converting some code from linux to mac.

与ImageMagick convert命令类似,如何以编程方式在图像上覆盖文本?由于种种原因,我不能依赖于安装ImageMagick.

How can I programatically overlay an image with text, similar to the ImageMagick convert command? For various reasons I can't depend on having ImageMagick installed.

convert -draw 'text 50,800 "hello world"' f1.png f2.png

推荐答案

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

You can use the NSImage and NSString drawing APIs to create the edited image, and then use NSBitmapImageRep to get PNG data for the image. 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];

这篇关于MacOS:以编程方式向图像添加一些文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆