我正在尝试使用 PyObjC 用一些文本覆盖图像,同时努力回答我的问题,"Annotate images using tools built into OS X" 。通过引用CocoaMagic ,RMagick 的 RubyObjC 替代品,我想出了这个:
#!/usr/bin/env python
from AppKit import *
source_image = "/Library/Desktop Pictures/Nature/Aurora.jpg"
final_image = "/Library/Desktop Pictures/.loginwindow.jpg"
font_name = "Arial"
font_size = 76
message = "My Message Here"
app = NSApplication.sharedApplication() # remove some warnings
# read in an image
image = NSImage.alloc().initWithContentsOfFile_(source_image)
image.lockFocus()
# prepare some text attributes
text_attributes = NSMutableDictionary.alloc().init()
font = NSFont.fontWithName_size_(font_name, font_size)
text_attributes.setObject_forKey_(font, NSFontAttributeName)
text_attributes.setObject_forKey_(NSColor.blackColor, NSForegroundColorAttributeName)
# output our message
message_string = NSString.stringWithString_(message)
size = message_string.sizeWithAttributes_(text_attributes)
point = NSMakePoint(400, 400)
message_string.drawAtPoint_withAttributes_(point, text_attributes)
# write the file
image.unlockFocus()
bits = NSBitmapImageRep.alloc().initWithData_(image.TIFFRepresentation)
data = bits.representationUsingType_properties_(NSJPGFileType, nil)
data.writeToFile_atomically_(final_image, false)
当我运行它时,我得到这个:
Traceback (most recent call last):
File "/Users/clinton/Work/Problems/TellAtAGlance/ObviouslyTouched.py", line 24, in <module>
message_string.drawAtPoint_withAttributes_(point, text_attributes)
ValueError: NSInvalidArgumentException - Class OC_PythonObject: no such selector: set
查看文档中的drawAtPoint:withAttributes:,它说:“您应该仅在 NSView 具有焦点时调用此方法。” NSImage 不是 NSView 的子类,但我希望这能够工作,并且非常相似的东西似乎可以在 Ruby 示例中工作。
我需要更改什么才能使其正常工作?
<小时/>我重写了代码,将其逐行忠实地转换为 Objective-C 基础工具。它可以工作,没有问题。 [如果有理由的话,我很乐意在这里发帖。]
问题就变成了,如何:
[message_string drawAtPoint:point withAttributes:text_attributes];
不同于
message_string.drawAtPoint_withAttributes_(point, text_attributes)
?有没有办法知道哪个“OC_PythonObject”引发了 NSInvalidArgumentException?
最佳答案
下面是上面代码中的问题:
text_attributes.setObject_forKey_(NSColor.blackColor, NSForegroundColorAttributeName)
->
text_attributes.setObject_forKey_(NSColor.blackColor(), NSForegroundColorAttributeName)
bits = NSBitmapImageRep.alloc().initWithData_(image.TIFFRepresentation)
data = bits.representationUsingType_properties_(NSJPGFileType, nil)
->
bits = NSBitmapImageRep.imageRepWithData_(image.TIFFRepresentation())
data = bits.representationUsingType_properties_(NSJPEGFileType, None)
确实有小错别字。
请注意,代码的中间部分可以替换为这个更具可读性的变体:
# prepare some text attributes
text_attributes = {
NSFontAttributeName : NSFont.fontWithName_size_(font_name, font_size),
NSForegroundColorAttributeName : NSColor.blackColor()
}
# output our message
NSString.drawAtPoint_withAttributes_(message, (400, 400), text_attributes)
我是通过查看 NodeBox 的源代码了解到这一点的,十二行psyphography.py和 cocoa.py ,特别是 save 和 _getImageData 方法。
关于cocoa - 在 PyObjC 中的 NSImage 上绘制文本时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1229830/