发表时间:2009-11-24
最后修改:2009-11-24
//GoodFont只是一个标记字体特性的bean
//加字体(3D效果)
public static void createJpgByGoodFont(String inputPath,String outputPath,GoodFont[] goodfont){
BufferedImage image;
try {
image = ImageIO.read(new FileInputStream(inputPath));
if(goodfont==null)return;
FileOutputStream jpgOut = new FileOutputStream(outputPath);
Graphics2D g = image.createGraphics();
for(GoodFont gf:goodfont){
int style=gf.getStyle();
int size=gf.getSize();
String name=gf.getName();
int leftX=gf.getLeft();
int topY=gf.getTop();
int width=gf.getWidth();
int high=gf.getHigh();
int textDirect=gf.getTextDirect();
String text=gf.getText();
String align=gf.getAlign();
Color color=gf.getColor();
Color fillColor=gf.getFillColor();
Color drawColor=gf.getDrawColor();
Font font = new Font(name, style, size);
g.setFont(font);
if(fillColor!=null){
g.setColor(fillColor);
g.fill3DRect(leftX, topY, width, high, true);
}
if(drawColor!=null){
g.setColor(drawColor);
for(int i=0;i<gf.getDrawBorder();i++)
g.draw3DRect(leftX, topY, width, high+i, true);
}
//设置背景色,仅当背景无图片时使用
// g.setBackground(Color.YELLOW);
// g.setColor(Color.BLACK);
g.setColor(color);
if(align.equalsIgnoreCase("right")){
leftX=leftX+width-size*text.length();
}
else if(align.equalsIgnoreCase("center")){
leftX=leftX+(width-size*text.length())/2;
}
int j = size;
System.out.println("text="+text+",leftX="+leftX+",topY="+topY+",size="+size+",color="+color+",border="+gf.getDrawBorder());
if(textDirect==1)//横排的文字
g.drawString(text,leftX, topY+j);
else{//竖排的文字
for(int i=0;i<text.length();i++)
{
g.drawString(text.substring(i,i+1),leftX,topY+j);
j+=size;
}
}
}
g.dispose();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(jpgOut);
encoder.encode(image);
jpgOut.flush();
jpgOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (Throwable e) {
e.printStackTrace();
}
}
//加图片
public static void createJpgByLogo(String inputPath,String outputPath,String logoPath,int x,int y){
BufferedImage image;
try {
image = ImageIO.read(new FileInputStream(inputPath));
if(logoPath==null)return;
FileOutputStream jpgOut = new FileOutputStream(outputPath);
Graphics2D g = image.createGraphics();
g.drawImage(ImageIO.read(new FileInputStream(logoPath)), x, y, null);
g.dispose();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(jpgOut);
encoder.encode(image);
jpgOut.flush();
jpgOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (Throwable e) {
e.printStackTrace();
}
}