`

图片上添加文字

    博客分类:
  • Java
阅读更多
public class ImageAddWord
{
public void addWord(String filePath, String watermark,String outpath, int x, int y,
String fontname, int fontsize, Color color)
{
// 根据图片路径将原图片装进ImageIcon对象中
ImageIcon imgIcon = new ImageIcon(filePath);
// 将原图片转换为Image
Image theImg = imgIcon.getImage();
// 根据图片路径将水印图片装进ImageIcon对象中
//ImageIcon waterIcon = new ImageIcon(watermark);
// 将水印图片转换为Image
//Image waterImg = waterIcon.getImage();
// 获取原图片的宽和高
int width = theImg.getWidth(null);
int height = theImg.getHeight(null);
// 创建BufferedImage对象
BufferedImage bimage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 创建Graphics2D对象
Graphics2D g = bimage.createGraphics();
// g.setColor(Color.red);
// g.setFont(new Font("宋体",Font.BOLD,36));
// 设置字体样式
g.setColor(color);
g.setFont(new Font(fontname, Font.BOLD, fontsize));
g.setBackground(Color.white);
g.drawImage(theImg, 0, 0, null);
//图片比例
float m=(float)((double)width/480.0);
float n=(float)((double)height/360.0);
//System.out.print(k+","+h);

// 设置透明度
g.setComposite(AlphaComposite
.getInstance(AlphaComposite.SRC_OVER, 0.8f));
//g.drawImage(waterImg, 100, 100, null); // 添加水印图片
g.drawString(watermark, x*m,y*n+fontsize); // 添加文字
g.dispose();
// 图片画板创建结束后将图片以文件流写出到指定路径
try
{
FileOutputStream out = new FileOutputStream(outpath);
// 设置文件流格式
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
// 对图片进行编码处理
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
param.setQuality(1.0f, true); // 设置图片质量
encoder.encode(bimage, param);// 将BufferedImage对象中的文件生成图片
//encoder.encode(bimage);
out.close();
} catch (Exception e)
{
e.printStackTrace();
}

}

public static void main(String[] args)
{
ImageAddWord imageAddWord = new ImageAddWord();
String filepath="D://test522.jpg";
String outpath="D://test522.jpg";
imageAddWord
.addWord(
filepath,
"美女b",outpath, 60, 100, "宋体", 12, Color.green);
System.out.print("操作成功完成!");

}

版权声明:本文为博主原创文章,未经博主允许不得转载。

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics