「OSXに組み込まれているツールを使用して画像に注釈を付ける」という質問に答えようとしながら、PyObjCを使用して画像にテキストをオーバーレイしようとしています。RMagickのRubyObjCの代替品であるCocoaMagicを参照することにより、私はこれを思いついた:
#!/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-CFoundationツールに変換しました。問題なく動作します。[理由があれば、ここに投稿させていただきます。]
次に、問題は次のようになります。
[message_string drawAtPoint:point withAttributes:text_attributes];
異なり
message_string.drawAtPoint_withAttributes_(point, text_attributes)
?どの「OC_PythonObject」がNSInvalidArgumentExceptionを発生させているかを確認する方法はありますか?