Sunday, March 15, 2009

im4javaで画像を円形に切り取る

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


import java.util.*;
import org.im4java.core.*;
import org.im4java.process.*;

// im4java-0.96.0-bin.tar.bz2を解凍してim4java-0.96.0.jarはclasspathに通す
public class Im4java6
{
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<String> 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("ellipse " + (width/2) +
"," + (height/2) + "," + (width/2-1) +
"," + (height/2-1) + ",0,360");
op2.addImage("sf.jpg");
op2.compose("src_in").composite();
op2.addImage("sample923a.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)


出力画像(sample923a.png)


関連情報
im4javaのまとめ

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

im4javaのホームページ
im4java

No comments: