Friday, August 10, 2012

groovyで鉛筆画風の星を描画する

groovyで鉛筆画風の星を描画するには、以下のコードを実行します。
@Grab(group='com.jhlabs', module='filters', version='2.0.235')
@Grab(group='org.codehaus.griffon', module='jsilhouette-geom', version='0.4')
import java.awt.*
import java.awt.image.*
import java.io.*
import javax.imageio.*
import com.jhlabs.composite.*
import com.jhlabs.image.*
import org.codehaus.griffon.jsilhouette.geom.*

// 鉛筆画風の星を描画する
def img = new BufferedImage(
    200, 200, BufferedImage.TYPE_INT_ARGB
)
def img2 = new BufferedImage(
    200, 200, BufferedImage.TYPE_INT_ARGB
)
def gr2 = img2.createGraphics()
gr2.setColor(new Color((int)0xeedd00))
gr2.fillRect(0, 0, img2.getWidth(), img2.getHeight())
gr2.dispose()

def gr = img.createGraphics()
gr.setRenderingHint(
  RenderingHints.KEY_ANTIALIASING,
  RenderingHints.VALUE_ANTIALIAS_ON
)
def radius1 = 100
def radius2 = 50
def angle = 0

def star = new Star(img.getWidth()/2, img.getHeight()/2,
  radius1, radius2, 5, angle
)
gr.setColor(new Color((int)0xffffff))
gr.fill(star)
gr.dispose()
// 拡散
def df = new DiffuseFilter()
df.setScale(4)
img = df.filter(img, null)

def wr = img2.getRaster()
def buf = new int[4]

for(int ly=1;ly<wr.getHeight();ly+=2){
  for(int lx=0;lx<wr.getWidth();lx++){
    wr.getPixel(lx, ly, buf)
    buf[0] = Math.min(255, (int)(buf[0] * 1.7f))
    buf[1] = Math.min(255, (int)(buf[1] * 1.7f))
    buf[2] = Math.min(255, (int)(buf[2] * 1.7f))
    wr.setPixel(lx, ly, buf)
  }
}
// 線画
def sf = new SmearFilter()
sf.setShape(SmearFilter.LINES)
sf.setDensity(0.7f)
sf.setDistance(7)
sf.setScatter(0.8f)
sf.setAngle((float)Math.PI/3)
img = sf.filter(img, null)
img2 = sf.filter(img2, null)
// 角度を変更して
sf.setDensity(0.2f)
sf.setAngle((float)Math.PI/4)
img = sf.filter(img, null)
img2 = sf.filter(img2, null)

// 切り取り 
gr2 = img.createGraphics()
gr2.setComposite(AlphaComposite.SrcIn)
gr2.drawImage(img2,0,0,null)
gr2.dispose()

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


出力画像


動作環境
groovy 1.8.6, JDK7 update4

No comments: