構建動態網站,靈活性與美觀經常會成為一個矛盾。網頁設計師從視覺角度考慮,在許多地方采用了圖片,有時甚至在動態輸出的內容上使用了圖片,比如網站的欄目、各類標題等。而這些內容往往 要經常變換,需要WEB頁面的腳本程序根據數據庫中的內容實時輸出。傳統使用圖片的形式顯然無法勝任需要經常變換內容的位置 ,通常是采用折衷的辦法,或降低對視覺效果的要求,讓設計師改用文字設計,或要求維護人員不時根據實際內容重新制作并更換圖片,等等。對此,本文將 提供一種更為靈活的解決方案。
?
如果你是一個WEB開發者,或多或少會遇到這樣一種情況:網頁設計師在設計網頁時,在需要動態輸出內容的地方采用圖片,如:
?
而"熱點聚焦"這個名稱,也許過一兩天就要求改成"焦點訪談"等其它字樣,到時不得不重新制作一張圖片替代。而采用文字加背景,有時不易達到好的效果。采用表格背景圖方式,需要精心調整表格的尺寸,而且其它的改動也會有意無意影響到它,需要小心調試。
本人在多個項目開發中遇到網頁中需要動態圖文結合輸出情況,程序員和美工往往最終都是選擇了回避和妥協,盡管通常影響不大,但畢竟與盡善盡美的追求有所差距。于是終于產生了本文的解決方法。
?
先看看我們要解決的問題
?
我們的問題可以簡單總結為:有一張圖片,如:
?
現在我們要動態地將文字比如"熱點聚焦"輸出到上面,并在網頁上得到類似如下的顯示:
?
?
?HTML如何顯示一張圖片
?
在HMTL中顯示一張圖片很簡單:<img src="bg.jpg" weight="153" height="25">。
另外我們還知道src屬性中的文件類型并沒有做限定,也就是說<img src="image.jsp">的寫法也是合法的,同樣引用Servlet:<img src="/imageServlet">的寫法也是合法的,瀏覽器解析到該語句時,將向目標服務器發送一個HTTP請求。通過了解HTTP協議,可以知道,如果這時imageServlet做出Content-Type為image/jpeg的正確響應(可以通過設置contentType="images/jpeg"來實現),那么也將正確顯示一張圖片。這個原理也是實現將數據庫中的圖像數據顯示到網頁上所用的原理。
進一步利用這個原理,當向imageServlet請求圖像時,imageServlet不是簡單的發送原圖像數據,而是先對原圖像數據進行一定的處理,比如在原圖片上面的指定位置加上文字,甚至對再做一些處理比如陰影、立體等,然后再將處理后的圖像數據流發送出去,那么不就可以得到圖文結合后的圖像了嗎?
根據以上分析,我們得到這樣的實現方法:在<img>的src屬性中調用實現上述功能的Servlet并傳遞相關的參數,如背景圖片路徑、輸出文字、文字輸出的位置、字體、大小等,由該Servlet進行圖文處理,并返回處理后的圖像數據,從而在網頁上顯示出加上文字的圖像。
?
通過Servlet實現圖文結合輸出
?
下面根據上面的原理編寫一個簡單的Servlet實現代碼,該Servlet能夠根據傳遞的參數要求,將文字輸出到圖片上并向瀏覽器返回圖文結合后的圖像數據,并在調用的網頁上顯示出圖文結合后的圖像(注:該servlet僅實現了JPG格式圖像文件的處理,不支持GIF):
package test.servlet; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.awt.*; import java.awt.image.*; import com.sun.image.codec.jpeg.*; /** * * @author SailingLee */ public class TextIntoImage extends HttpServlet { private static final String CONTENT_TYPE = "image/jpeg;charset=GB2312"; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(CONTENT_TYPE); String text = ""; //要嵌的文字 String imageFile = ""; //被嵌的圖片的虛擬路徑 int x = 0; //坐標 int y = 0; String fontColor = ""; //字體顏色 int fontSize = 0; //字體大小 String fontStyle = ""; //字體風格(斜體,粗體等) String fontName = ""; //字體名稱 try { //取得參數(ParamUtil類請參看后面附的ParamUtil類代碼) text = ParamUtil.getParameter(request, "text"); imageFile = ParamUtil.getParameter(request, "imageFile"); x = ParamUtil.getIntParameter(request, "x", 0); y = ParamUtil.getIntParameter(request, "y", 0); fontColor = ParamUtil.getParameter(request, "fontColor"); fontSize = ParamUtil.getIntParameter(request, "fontSize", 16); fontStyle = ParamUtil.getParameter(request, "fontStyle"); fontName = ParamUtil.getParameter(request, "fontName"); //====================debug info======================= System.out.println("text:"+text); System.out.println("imageFile:"+imageFile); } catch (Exception e) { e.printStackTrace(); } ServletOutputStream output = response.getOutputStream(); if (imageFile.toLowerCase().endsWith(".jpeg") || imageFile.toLowerCase().endsWith(".jpg")) { imageFile = getServletContext().getRealPath(imageFile); InputStream imageIn = new FileInputStream(new File(imageFile)); JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(imageIn); BufferedImage image = decoder.decodeAsBufferedImage(); Graphics g = image.getGraphics(); //設置顏色 g.setColor(new Color(Integer.parseInt(fontColor, 16))); //設置字體 Font mFont = new Font(fontName, Font.PLAIN, fontSize);//默認字體 if (fontStyle.equalsIgnoreCase("italic")) { mFont = new Font(fontName, Font.ITALIC, fontSize); } if (fontStyle.equalsIgnoreCase("bold")) { mFont = new Font(fontName, Font.BOLD, fontSize); } if (fontStyle.equalsIgnoreCase("plain")) { mFont = new Font(fontName, Font.PLAIN, fontSize); } g.setFont(mFont); //輸出文字 g.drawString(text, x, y); //輸出數據流 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output); encoder.encode(image); imageIn.close(); } output.close(); } // <editor-fold defaultstate="collapsed" desc="HttpServlet 方法。單擊左側的 + 號以編輯代碼。"> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ public String getServletInfo() { return "Short description"; }// </editor-fold> }
?
上面獲取參數的代碼使用了一個工具類,它是擴展了request.getParameter()功能的一個類:?
package test.servlet; import java.io.UnsupportedEncodingException; import javax.servlet.*; /** * * @author SailingLee */ public class ParamUtil { /** * 獲得request中指定名稱的參數值,若有中文亂碼問題請增加轉碼部分 * @param request ServletRequest對象 * @param paramName 參數名稱 * @return 如果該變量值存在則返回該值,否則返回"" */ public static String getParameter(ServletRequest request, String paramName) { String temp = request.getParameter(paramName); if (temp != null && !temp.equals("")) { try { //若有中文問題,在此添加轉碼代碼,例:temp = new String(temp.getBytes("8859_1"), "GB2312"); temp = new String(temp.getBytes("8859_1"), "GB2312"); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } return temp; } else { return ""; } } /** * 獲得request中的int型參數值 * @param request ServletRequest對象 * @param paramName 參數名稱 * @param defaultNum 默認值,如果沒有返回該值 * @return 如果該參數值存在則返回其轉換為int型的值,否則返回defaultNum */ public static int getIntParameter(ServletRequest request, String paramName, int defaultNum) { String temp = request.getParameter(paramName); if (temp != null && !temp.equals("")) { int num = defaultNum; try { num = Integer.parseInt(temp); } catch (Exception ignored) { } return num; } else { return defaultNum; } } }
?
?
實際應用
?
?
1.在web.xml中聲明該Servlet
?
<servlet> <servlet-name>TextIntoImage</servlet-name> <servlet-class>test.servlet.TextIntoImage</servlet-class> </servlet> <servlet-mapping> <servlet-name>TextIntoImage</servlet-name> <url-pattern>/TextIntoImage</url-pattern> </servlet-mapping>
?
??
2.將test.servlet.TextIntoImage類和test.servlet.ParamUtil類放入WEB-INF/classes/
3.JSP頁面調用,本例中要將bg.jpg文件放入根目錄,示例代碼:
<img border="0" src="/TextIntoImgServlet/TextIntoImage?text=熱點聚焦&imageFile=/images/bg.jpg&x=20&y=20&fontColor=FFFFFF&fontStyle=bold&fontName=宋體&fontSize=16"/>
?
繼續完善
?
到此可以暫告一個段落了。不過還有很多地方有待繼續完善,例如:加入文字效果處理(陰影、立體、浮雕等),文字豎排,增加對GIF文件支持等
?
[轉自:ht tp://www.ibm.com/developerworks/cn/java/l-imgtxt/index.html ]
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
