在現有圖片中加亂數碼(文字)

構想:

在現有的圖片裡,列如樣版票圖,再加入亂數碼,以區別每個票圖的唯一性。

想法:

取得亂數碼,打開樣版票圖,取得畫筆(Graphics2D),把亂數碼設定到TextLayout圖層上,

計算放置TextLayout圖層的x及y坐標,把圖層draw到樣版圖上,輸出到以亂數碼為名稱之圖檔。

以下是範例程式:

程式大樣分成二大部份,一是圖形的加註文字,二是取得亂數編號的方式。

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.font.TextLayout;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;

public class CombineRndImg {
    public void run(String FilePath,String FileName) throws Exception
    {
      String text = getRnd(8);
      BufferedImage im = ImageIO.read(new java.io.File(FilePath+FileName));
          Graphics2D g = im.createGraphics();

          //去除鋸齒等...
          g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, 
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
          g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, 
RenderingHints.VALUE_FRACTIONALMETRICS_ON);
          g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
RenderingHints.VALUE_ANTIALIAS_ON);
          g.setFont(new Font("Dialog", Font.PLAIN, 20));
  
          TextLayout tl = new TextLayout(text, g.getFont(), g.getFontRenderContext());

          Rectangle2D bounds = tl.getBounds();
          //計算文字要放置的位置
          double x = (im.getWidth()-bounds.getWidth()) - bounds.getX()-50;
          double y = (im.getHeight()-bounds.getHeight()) - bounds.getY()-80;
          //從綠色到紅色的漸層
          g.setPaint(new GradientPaint(0, 0, Color.GREEN, 30, 20, Color.RED, true));
      //寫入文字
          tl.draw(g, (float)x, (float)y);
          g.dispose();
      //輸出檔案
          java.io.FileOutputStream newimage = new java.io.FileOutputStream(
new java.io.File(FilePath+text+".jpg")); //輸出到文件流
              //  System.out.println("newimage:"+newimage);
             ImageIO.write(im, "JPEG", newimage);
             if(newimage!=null)
             {
               newimage.close();
               newimage = null ;
             }
    }

    //取得亂數
    public String getRnd(int length)
    {
      java.util.Random rnd = new java.util.Random();
      return getCode(rnd,length);
    }
    //取得亂數碼
    public String getCode(java.util.Random r,int num)
    {
      int rnd = 0;
      String authcode = "";
      for(int i = 0 ; i < num;i++)
      {
        if(getNumChar(r))
        {
          rnd = r.nextInt(9);
          authcode = authcode + rnd;
        }
        else
        {
          rnd = r.nextInt(52);
          if(rnd<26)
          {
            authcode = authcode +((char)(rnd +65));
          }
          else
          {
            authcode = authcode +((char)(rnd -26+ 97));
          }

          }

      }

      return authcode;

    }

    //八成數字二成英文
    //取得數字或字母
    public boolean getNumChar(java.util.Random r)
    {
      if(r.nextInt(100)>20)
        return true;
      else
        return false;
    }

    public static void main(String args[])throws Exception
    {
      CombineRndImg cri = new CombineRndImg();
      cri.run("d:/temp/","movie.jpg");
    }
}

發表迴響