Friday, December 12, 2008

RMagickで画像上に描画した文字列以外の部分をグレースケールにする

RMagickで画像上に描画した文字列以外の部分をグレースケールにするには、以下のコードを実行します。

require 'RMagick'
include Magick

images = ImageList.new("sf.jpg")
img2 = Image.new(images[0].columns, images[0].rows){
self.background_color = "none"
}

dr = Draw.new
# 使用フォント
dr.font = "Tahoma-Bold"
# ポイントサイズ
dr.pointsize = 28
# 描画色
dr.fill = "white"
# gravity
dr.gravity = CenterGravity
dr.annotate(img2, 0, 0, 0, -40, "San Francisco")
# 文字で切り取り
img3 = img2.composite(images[0], 0, 0, SrcInCompositeOp)

# グレースケール画像
images2 = ImageList.new("sf.jpg")
images2.colorspace = ColorspaceType::GRAYColorspace

# グレースケール画像と文字で切り取ったカラー画像を重ね合わせ
img4 = images2.composite(img3, CenterGravity, 0, 0, OverCompositeOp);
img4.write("sample708a.png")

exit

元画像(sf.jpg)


出力画像(sample708a.png)


関連項目
RMagickで日本語文字列を描画する
RMagickで半透明影つきの文字列を描画する

No comments: