Java : how to convert text to image

(minor changes on initial codes :D. Noted the function ImageIO.write() )

 

package EXP;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;


/**
 * @author Matthew Jones, 2009
 */
public class Main {


    public static void main(String[] args) throws IOException {
        try {


            // collect correct inputs or DIE.
            String email = "dingxy@gmail.com";
           
            Color fg = Color.white ;
            Color bg = Color.black ;
           
            //Color fg = new Color(Integer.parseInt(args[1], 16));
            //Color bg = new Color(Integer.parseInt(args[2], 16));
            String filename = "c://snow.png";


            // call render image method.
            RenderedImage rendImage = writeImage(email, fg, bg);


            File file = new File(filename);


            ImageIO.write(rendImage, "png", file);


        } catch (Exception e) {
            // Sloppy Error handling below
            System.out.println("Usage: textToImage.jar email fg-colour-hex bg-colour-hex filename");
            System.out.println("Example: textToImage.jar eg@eg.com FFFFFF 0000FF C://dir//image.png");
            System.out.print(e.getMessage());
        }
    }


    private static RenderedImage writeImage(String text, Color fgc, Color bgc) {

        // calculate image size requirements.
        int width = (text.length() * 7) + 5;

        // standard height requirement of 16 px.
        int height = 16*2;
        BufferedImage buffRenderImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D flatGraphic = buffRenderImage.createGraphics();

        // Draw background
        flatGraphic.setColor(bgc);
        flatGraphic.fillRect(0, 0, width, height);


        //Draw text
        flatGraphic.setColor(fgc);
        Font font = new Font("Courier", Font.BOLD, 12);
        flatGraphic.setFont(font);
        flatGraphic.drawString(text, 1, 10);
        flatGraphic.drawString("Sencond line", 1, 25);

        // don't use drawn graphic anymore.
        flatGraphic.dispose();

        return buffRenderImage;
    }
}
=============my own try on this====================

package EXP;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import javax.imageio.ImageIO;



public class ConvertStr2IMG {
    String email ="dingxy@globalsources.com";
    private int width=240;  // width of image.
    private int height=60;  // height of image.
    private Font font=new Font("arial",Font.PLAIN,12);
    private Color bgColor=Color.white;  //background color of image.
    private Color fontColor=Color.black;
    boolean verStretch=true;
    boolean horStretch=true;
   
    public  BufferedImage getImage() {
         
         if(email==null||email.equals(""))
            return null;
     
          int imgWidth=width;
          int imgHeight=height;
          int emailPosY=0;

          BufferedImage img = new BufferedImage(width,height*3/2, BufferedImage.TYPE_INT_RGB);
          FontMetrics fontMetrics=img.getGraphics().getFontMetrics(font);
         
             if(horStretch)
               imgWidth=fontMetrics.stringWidth(email); //set the width of the image as the pixel width of the email string.
                //System.out.println("font width : "+ fontMetrics.stringWidth(email));
            if(verStretch){
               //et the height of the image as the  font height of the email string.
               imgHeight=fontMetrics.getMaxAscent()+fontMetrics.getMaxDescent();
              
               System.out.println("font height : "+ imgHeight);
               System.out.println("font asc : "+ fontMetrics.getMaxAscent());
               System.out.println("font desc : "+ fontMetrics.getMaxDescent());
              
               emailPosY=fontMetrics.getMaxAscent();  //set the y-axis of the email string is drawn on the image.
            }else{
                //set the y-axis position of the email string so that the string is drawn in the middle of the image in vertical direction.   
                emailPosY=(imgHeight-(fontMetrics.getMaxAscent()+fontMetrics.getMaxDescent()))/2+fontMetrics.getMaxAscent();
            }
         
            BufferedImage retVal = new BufferedImage(imgWidth,imgHeight*3/2, BufferedImage.TYPE_INT_RGB);

            Graphics graphics=retVal.getGraphics();
           
            graphics.setColor(bgColor);  //set background color of the image.
            graphics.fillRect(0,0,imgWidth,imgHeight*3/2);

            graphics.setColor(fontColor); // set font color of the email string.

            graphics.setFont(font);
            graphics.drawString(email,0,emailPosY);
           
            //draw a line
            //graphics.drawLine(0, emailPosY+5, imgWidth, emailPosY+5);
           
            //draw a thick line
            graphics.setColor(Color.red);
            //g.fillOval(10,10, 5, 5);
            ((Graphics2D) graphics).setStroke(new BasicStroke(2));
            graphics.drawLine(0, emailPosY+5, imgWidth, emailPosY+5);
           
            //draw seconde text
            //graphics.drawString("second line",0,emailPosY+imgHeight);

            return retVal;
        }
       
    /**
     * Function to save the image object to a file with the defined file
     * name and path .
     * @param fileName : the file name that image object will be stored in.
     * @param filePath : the file path that image file will be located at .
     * @return true: save image file success ; false: save image file failed .
     */   
        public boolean saveImageToFile(String fileName , String filePath) {

            boolean bImage = false ;
            BufferedImage bufImg=this.getImage();
            if(bufImg==null){
                System.out.println("bufImg is null");
            }
            String filePathName = "";
            if (filePath.endsWith("//")|| filePath.endsWith("//"))
            {
                filePathName = filePath+fileName;
            }
            else{
                filePathName = filePath+ File.separator +fileName;
            }
            try{
               
                FileOutputStream fileOut= new FileOutputStream(filePathName);
                BufferedOutputStream bufOut=new BufferedOutputStream(fileOut);
                System.out.println("filePathName is "+filePathName);
                bImage = ImageIO.write(bufImg, "png", fileOut);
               
            }catch(Exception e){
                e.printStackTrace();
            }
                return bImage ;
        }

    /**
     * Function to save the image object to a file with the defined
     * file name and path .
     * @param fileName : the file name that image object will be stored in.
     * @param filePath : the file path that image file will be located at .
     * @param bufImage : the image object for being stored in the file.
     * @return true: save image file success ; false: save image file failed .
     */   
        public boolean saveImageToFile(String fileName , String filePath , BufferedImage bufImg) {
            boolean bImage = false ;
            if(bufImg==null){
                System.out.println("bufImg is null");
            }
            String filePathName = filePath+ File.separator +fileName;
            try{
               
                FileOutputStream fileOut= new FileOutputStream(filePathName);
                BufferedOutputStream bufOut=new BufferedOutputStream(fileOut);
                System.out.println("filePathName is "+filePathName);
                bImage = ImageIO.write(bufImg, "png", fileOut);
               
            }catch(Exception e){
                e.printStackTrace();
            }
                return bImage ;
        }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ConvertStr2IMG emailConvert = new ConvertStr2IMG();
        boolean bTest = emailConvert.saveImageToFile("test.png", "c://", emailConvert.getImage());

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值