Friday, February 27, 2009

im4javaで画像を角丸四角に切り取る

im4javaで画像を角丸四角に切り取るには、以下のコードを実行します。


// im4java-0.96.0-bin.tar.bz2を解凍してim4java-0.96.0.jarはclasspathに通す
public class Im4java3
{
public static void main(String args[])
throws Exception
{
try
{
IMOperation op = new IMOperation();
op.verbose();
op.addImage("sf.jpg");

IdentifyCmd identify = new IdentifyCmd();
ArrayListOutputConsumer output =
new ArrayListOutputConsumer();
identify.setOutputConsumer(output);
identify.run(op);
ArrayList lines = output.getOutput();

int width = 0;
int height = 0;
for(String line:lines){
if( line.startsWith(" Geometry: ") ){
if( line.indexOf("+") != -1 ){
String sz[] = line.substring(
" Geometry: ".length(),
line.indexOf("+")
).split("x");
width = new Integer(sz[0]);
height = new Integer(sz[1]);
}
}
}

// 画像サイズと同じ大きさの角丸四角で切り取り
IMOperation op2 = new IMOperation();
op2.size(new Integer(width), new Integer(height));
op2.addImage("xc:none");
op2.alpha("activate").channel("rgba");
op2.fill("white");
op2.draw("roundrectangle 0,0," + (width-1) +
"," + (height-1) + ",30,30");
op2.addImage("sf.jpg");
op2.compose("src_in").composite();
op2.addImage("sample920a.png");

// ConvertCmd convert = new ConvertCmd();
ImageCommand convert = new WindowsConvertCmd();
convert.run(op2);


}
catch(CommandException cex)
{
System.out.println(cex.getErrorText());
cex.printStackTrace();
}
}

// im4java 0.96
static class WindowsConvertCmd extends ImageCommand
{
public WindowsConvertCmd()
{
setCommand("cmd");
setCommand("/c");
setCommand("convert");
/* another way
setCommand("C:\\Program Files\\ImageMagick-6.4.9-Q16\\convert");
*/
}
}

}


元画像(sf.jpg)


出力画像(sample920a.png)


関連情報
im4javaのまとめ
im4javaで画像のサイズを取得する

No comments: