Java 隨機生成中文漢字

wangjianme 12年前發布 | 90K 次閱讀 Java Java開發

/**

     * 原理是從漢字區位碼找到漢字。在漢字區位碼中分高位與底位, 且其中簡體又有繁體。位數越前生成的漢字繁體的機率越大。

     * 所以在本例中高位從171取,底位從161取, 去掉大部分的繁體和生僻字。但仍然會有!!

     *

     */

    @Test

    public void create() throws Exception {

       String str = null;

       int hightPos, lowPos; // 定義高低位

       Random random = new Random();

       hightPos = (176 + Math.abs(random.nextInt(39)));//獲取高位值

       lowPos = (161 + Math.abs(random.nextInt(93)));//獲取低位值

       byte[] b = new byte[2];

       b[0] = (new Integer(hightPos).byteValue());

       b[1] = (new Integer(lowPos).byteValue());

       str = new String(b, "GBk");//轉成中文

       System.err.println(str);

    }

 

    /**

     * 旋轉和縮放文字

     * 必須要使用Graphics2d

     */

    public void trans(HttpServletRequest req, HttpServletResponse resp) throws Exception{

       int width=88;

       int height=22;

       BufferedImage img = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);

       Graphics g = img.getGraphics();

       Graphics2D g2d = (Graphics2D) g;

       g2d.setFont(new Font("黑體",Font.BOLD,17));

       Random r = new Random();

       for(int i=0;i<4;i++){

           String str = ""+r.nextInt(10);

           AffineTransform aff = new AffineTransform();

           aff.rotate(Math.random(),i*18,height-5);

           aff.scale(0.6+Math.random(), 0.6+Math.random());

           g2d.setTransform(aff);

           g2d.drawString(str,i*18,height-5);

           System.err.println(">:"+str);

       }

       g2d.dispose();

       ImageIO.write(img, "JPEG",resp.getOutputStream());

    }

 本文由用戶 wangjianme 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!