貝貝爸爸的程序人生

          關注Seam、BPM
          posts - 23, comments - 10, trackbacks - 0, articles - 32
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          日歷

          <2025年6月>
          25262728293031
          1234567
          891011121314
          15161718192021
          22232425262728
          293012345

          常用鏈接

          搜索

          •  

          最新評論

          關于Graphics2D輸出圖片中文字符亂碼的問題

          Posted on 2011-08-17 15:00 貝貝爸爸 閱讀(9020) 評論(0)  編輯  收藏 所屬分類: BPM
          這幾天調試Activiti引擎的過程中,Activiti引擎會自動生成圖片,可如果遇到中文的節點時,圖片的中文字符將變成亂碼,搜索了下相關的文章,最終為字體原因造成具體看測試代碼:
           1 package org.activiti.examples.processdefinitions;
           2 
           3 import java.awt.Font;
           4 import java.awt.FontMetrics;
           5 import java.awt.Graphics2D;
           6 import java.awt.image.BufferedImage;
           7 import java.io.File;
           8 import java.io.IOException;
           9 
          10 import javax.imageio.ImageIO;
          11 
          12 public class Test {
          13 
          14     /**
          15      * @param args
          16      */
          17     public static void main(String[] args) {
          18         int width = 100;
          19         int height = 100;
          20         String text = "愛我中華";
          21         int x = 0;
          22         int y = 0;
          23         BufferedImage processDiagram = new BufferedImage(100100,
          24                 BufferedImage.TYPE_INT_ARGB);
          25         Graphics2D g = (Graphics2D) processDiagram.createGraphics();
          26         Font font = new Font("宋體", Font.BOLD, 12);
          27         g.setFont(font);
          28         FontMetrics fontMetrics = g.getFontMetrics();
          29         int textX = x + ((width - fontMetrics.stringWidth(text)) / 2);
          30         int textY = y + ((height - fontMetrics.getHeight()) / 2)
          31                 + fontMetrics.getHeight();
          32         g.drawString(text, textX, textY);
          33         File outFile = new File("d:/newfile.png");
          34         try {
          35             ImageIO.write(processDiagram, "png", outFile);
          36         } catch (IOException e) {
          37             // TODO Auto-generated catch block
          38             e.printStackTrace();
          39         }// 寫圖片
          40     }
          41 
          42 }
          43 
          搞定,呵呵。
          如果要部署到linux環境的話,需要將相關的字體文件傳到服務器的jdk下即可。
          我的本地字體文件地址是“C:\WINDOWS\Fonts\simsun.ttc”,
          上傳到服務器地址是:“/usr/jdk/instances/jdk1.5.0/jre/lib/fonts/simsun.ttc”

          剛才試了一下,可以不用指定字體,就能解決亂碼的問題,當然,我覺得應該自動和操作系統的字體相關吧。如果操作系統jdk不支持中文,也應該亂碼。

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 邮箱| 宁国市| 浦东新区| 高密市| 靖宇县| 石城县| 闵行区| 新巴尔虎左旗| 三明市| 墨江| 镇巴县| 大丰市| 晋宁县| 镇安县| 凤阳县| 云南省| 镇巴县| 陆丰市| 秭归县| 武冈市| 保康县| 辽源市| 全椒县| 托克托县| 新巴尔虎左旗| 墨玉县| 桃园市| 年辖:市辖区| 普洱| 上蔡县| 克什克腾旗| 育儿| 贵港市| 江源县| 邵阳县| 福泉市| 米泉市| 宁津县| 手游| 云林县| 成安县|