去年圣诞最流行的就是送金砖了吧,就像下面的那张一样:) 
觉得挺好玩的,今天我就用servlet实现一个最简单的在图片上动态加字的程序。先看看成果吧: 
地址:http://www.myjavaserver.com/servlet/passant.imgproc.AddText?text=要显示的字
只可惜放在老外的免费服务器上,不支持中文。
下面是实现的代码:
package addtext;
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*;
import java.awt.*; import java.awt.image.*; import javax.imageio.*;
public class AddText extends HttpServlet { static final String CONTENT_TYPE = "image/jpeg;charset=GB2312";//以图片格式输出 public void init() throws ServletException { } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(CONTENT_TYPE); String text = ""; String imageFile = "yourpic.jpg"; try { text = request.getParameter("text"); } catch(Exception e) { e.printStackTrace(); } if(text == null || text == "") text = "http://blog.csdn.net/passants"; text = new String(text.getBytes("8859_1"), "GB2312"); //解决中文显示问题 ServletOutputStream output = response.getOutputStream(); BufferedImage image = ImageIO.read(new File(imageFile)); Graphics g = image.getGraphics(); g.setColor(new Color(Integer.parseInt("FF0000", 16))); Font mFont = new Font("宋体", Font.PLAIN, 16); g.setFont(mFont); g.drawString(text, 20, 20); ImageIO.write(image, "JPG", output);//输出jpg格式图片 output.close(); } }
这是个最简单的例子,还可以加入文字特效,如阴影、立体、浮雕等。使用Image IO API还可以对图片的压缩质量进行设定。另外,适当处理一下,可以用URL图片作为inputstream(如果知道某人的相册图片地址,就可以……hoho)。还有就是中文处理问题,要加一句代码(见coding)。
相关文章: Servlet实现动态图文结合输出 URLInputStream Java Image IO APIs java中文问题详解

|