如何利用java在图片上添加文字

如何利用java在图片上添加文字,第1张

private static final String FILEINPUT="C:/apache-tomcat-6.0.18/webapps/elePhoto/images/许慧欣.jpg"private static final String FILEMARK="C:/apache-tomcat-6.0.18/webapps/elePhoto/images/http_imgload.jpg"private static final String FILEDEST1="C:/apache-tomcat-6.0.18/webapps/elePhoto/images/许慧欣1.jpg"private static final String FILEDEST2="C:/apache-tomcat-6.0.18/webapps/elePhoto/images/许慧欣2.jpg"/*** 给图片添加文字水印* @param filePath 需要添加水印的图片的路径* @param markContent 水印的文字* @param markContentColor 水印文字的颜色* @param qualNum 图片质量* @return 布尔类型*/public boolean createStringMark(String filePath,String markContent,Color markContentColor,float qualNum){ImageIcon imgIcon=new ImageIcon(filePath)Image theImg =imgIcon.getImage()int width=theImg.getWidth(null)int height= theImg.getHeight(null)System.out.println(theImg)BufferedImage bimage = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB)Graphics2D g=bimage.createGraphics()g.setColor(markContentColor)g.setBackground(Color.white)g.drawImage(theImg, 0, 0, null )g.setFont(new Font(null,Font.BOLD,32))//字体、字型、字号g.drawString(markContent,width/10,height/10)//画文字g.dispose()try{FileOutputStream out=new FileOutputStream(FILEDEST1)//先用一个特定的输出文件名JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(out)JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage)param.setQuality(qualNum, true)encoder.encode(bimage, param)out.close()}catch(Exception e)

只提指导,没有源码。

在 Java 中要自定义组件,一般是覆盖掉 protected void paintComponent(Graphics g)方法就可以了,对于你这个类似画笔的程序,首先,整个画布是一个自定义的继承自像 JPanel 一样的东西,不过我们需要覆盖它的 paintComponent 方法,因为:一、我们需要在当鼠标拖放一个东西时我们移动这个选中的图形时记住它的位置;二、设定 label 时需要保存它的 Label。三、知道图形的形状。

,然后在 paintComponent 时依次画出各个图形来。

要绘图:

1、直线,g.drawLine(x,y,x2,y2)// 参数分别是起止点坐标。

2、矩形,g.fillRect(x, y, w, h)// 参数分别是左上角坐标和宽及高。

3、椭圆,g.fillOval(x, y, w, h)// 参数分别是椭圆形的外切矩形的左上角坐标及宽和高,当w 和 h 相等时是个圆。

准备绘图前 g.setColor() 设置前景色;先把整个画布用 g.fillRect() 涂成白色,再分别画各个图形,最后绘制 Label 应该在画图形之后再做。

移动图形,是给 画布组件 addMouseMotionListener 来监听事件的,在拖动时先通过 mouseDragged 事件的 MouseEvent.point 知道它的位置是在哪个图形的内部,之后的移动就修改这个图形的位置。

先用java.awt.Graphics2D.getFont()取得当前正在使用的字体f,java.awt.Graphics2D.getFontRenderContext()取得当前正在使用的渲染上下文frc

然后再用Rectangle2D rect=f.getStringBounds(str,frc)就可以得到你渲染这些文字所占据的矩形,使用rect.getWidth(), rect,getHeight()就可以知道这个矩形的大小了。

反过来通过像素大小决定字符串的长度没有现成的方法。如果你的字体是等宽的可以先用上面的方法求出一个字符的大小然后自己算,不然就只能先试试一个字符,再试试两个字符……直到超过你要的长度就返回的办法了(看起来效率比较低,不过实际使用的时候不是很影响性能)


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11789582.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-18
下一篇 2023-05-18

发表评论

登录后才能评论

评论列表(0条)

保存