Friday, October 12, 2012

groovyで写真を夕暮れ風に加工する

groovyで写真を夕暮れ風に加工するには、以下のコードを実行します。
@Grab(group='com.jhlabs', module='filters', version='2.0.235')
import java.awt.*
import java.awt.image.*
import java.io.*
import javax.imageio.*
import com.jhlabs.composite.*
import com.jhlabs.image.*

// 写真を夕暮れ風に加工する
def img = ImageIO.read(new File("sf2.jpg"))
def imga = new BufferedImage(
    img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB
)
def gr = imga.createGraphics()
gr.drawImage(img,0,0,null)
gr.dispose()

// 閾値で2色画像を作成
def threshold = 127
def white = (int)0x50F24405
def black = (int)0x503E606F

def wr = imga.getRaster()
def buf = new int[4]
for(int ly=0;ly<wr.getHeight();ly++){
  for(int lx=0;lx<wr.getWidth();lx++){
    wr.getPixel(lx, ly, buf)

    if( PixelUtils.brightness((buf[0]<<16)+(buf[1]<<8)+buf[2]) > threshold  ){
      buf[0] = (white >> 16) & 0xff
      buf[1] = (white >> 8) & 0xff
      buf[2] = white & 0xff
      buf[3] = (white >> 24) & 0xff
    } else {
      buf[0] = (black >> 16) & 0xff
      buf[1] = (black >> 8) & 0xff
      buf[2] = black & 0xff
      buf[3] = (black >> 24) & 0xff
    }

    wr.setPixel(lx, ly, buf)
  }
}
// ぼかす
def gf = new GaussianFilter()
gf.setRadius(3f)
imga = gf.filter(imga, null)
// 重ね合わせ
def gr2 = img.createGraphics()
gr2.drawImage(imga,0,0,null)
gr2.dispose()

ImageIO.write(img, "png", new File("sunset.png"))


元画像

出力画像


動作環境
groovy 1.8.6, JDK7 update4

No comments:

Post a Comment