1

我正在尝试使用 PyObjC 用一些文本覆盖图像,同时努力回答我的问题"Annotate images using tools built into OS X"。通过引用CocoaMagic,一个 RubyObjC 替代RMagick,我想出了这个:

#!/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 Foundation 工具。它有效,没有问题。[如果有理由的话,我很乐意在这里发帖。]

那么问题就变成了,如何:

[message_string drawAtPoint:point withAttributes:text_attributes];

与......不同

message_string.drawAtPoint_withAttributes_(point, text_attributes)

? 有没有办法判断哪个“OC_PythonObject”引发了 NSInvalidArgumentException?

4

1 回答 1

1

以下是上述代码中的问题:

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.pycocoa.py12 行代码,尤其是 save 和 _getImageData 方法了解到这一点。

于 2009-08-25T04:22:36.627 回答