java多线程文本转图片

package net.cnki.armed.test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

public class ImageProducerUtil {

    public static void main(String[] args) throws Exception {
        // 读取Excel文件
        try {
            //List<Row> allData=ExcelUtils.readExcel("C:\\Users\\13661\\Desktop\\标准词和错误词0803.xlsx" , 0, 0,0);
//            for(int i=0;i<allData.size();i++){
//                //获取列数
//                Row row = allData.get(i);
//                int columns = row.getPhysicalNumberOfCells();
//                for(int j=1;j<columns;j++){
//                    String cell = row.getCell(j).toString();
//                    System.out.println(cell);
//                    createImage(cell, new Font("宋体", Font.PLAIN, 100), Paths.get(rootPath, "b" + i +".jpg").toFile());//+ "_"+j
//                }
//            }
            List<String> list = new ArrayList<String>();
            BufferedReader in=new BufferedReader(new FileReader("C:\\Users\\13661\\Desktop\\标注术语5w.txt_内容.txt"));//打开文本文件
            String str; //定义String变量用来保存每一次读到的每一行的数据
//            int i=0;
            while((str=in.readLine())!=null){
//                if(i>4000) {//业务需求
//                    break;
//                }
//                i++;
                list.add(str);
            }
            in.close();
            for(int j=0;j<30;j++){
                FileThread fileThread=new FileThread();
                fileThread.setFileIndex(j);
                fileThread.setFilelist(list);
                fileThread.start();
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

package net.cnki.armed.test;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Paths;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;

import javax.imageio.ImageIO;

/**
 * 多线程生成多个jpg文件
 */
public class FileThread extends Thread{

    private final CountDownLatch countDownLatch = new CountDownLatch(10);
    private int fileIndex;
    private List<String> filelist;
    String rootPath = "C:\\Users\\13661\\Desktop\\pc1\\";
    public int getFileIndex() {
        return fileIndex;
    }

    public void setFileIndex(int fileIndex) {
        this.fileIndex = fileIndex;
    }

    public List<String> getFilelist() {
        return filelist;
    }

    public void setFilelist(List<String> filelist) {
        this.filelist = filelist;
    }

    @Override
    public void run() {
        Random random=new Random();    
        try {
                for (int i = 0; i < filelist.size(); i++) {
                    String str = filelist.get(i);
                    if (i % 10 == fileIndex) {
                        int r = random.nextInt(str.length());
                        if(i<=1000) {
                            str = str.substring(0, r)+randomString()+str.substring(r);
                            //System.out.println(str);//一千条增加一个字 
                            createImage(str, new Font("黑体", Font.PLAIN, 197), Paths.get(rootPath, "a" + (i+1) +".jpg").toFile());
                        }else if(i>1000&&i<=2000) {
                            str = str.substring(0, r)+str.substring(r+1);
                            //System.out.println(str);//一千条减少一个字
                            createImage(str, new Font("黑体", Font.PLAIN, 197), Paths.get(rootPath, "b" + (i+1) +".jpg").toFile());
                        }else if(i>2000&&i<=3000) {
                            str = str.substring(0, r)+randomString()+str.substring(r+1);
                            //System.out.println(str);//一千条随机替换一个字
                            createImage(str, new Font("黑体", Font.PLAIN, 197), Paths.get(rootPath, "c" + (i+1) +".jpg").toFile());
                        }else if(i>3000&&i<=4000) {
                            str = changeString(str,r);
                            System.out.println(str);//一千条随机调换顺序
                            createImage(str, new Font("黑体", Font.PLAIN, 197), Paths.get(rootPath, "d" + (i+1) +".jpg").toFile());
                        }
//                        createImage(str, new Font("黑体", Font.PLAIN, 197), Paths.get(rootPath, "b" + (i+1) +".jpg").toFile());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        countDownLatch.countDown();
    }
    
    
    private static  String randomString() {
        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());
        try {
            str = new String(b, "GBk");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return str;
    }
    public static String changeString(String a,int n){
        StringBuilder beforeStr = new StringBuilder(a.substring(0,n));
        StringBuilder afterStr= new StringBuilder(a.substring(n));
        String result = afterStr.append(beforeStr).toString();
        return result;
    }

    // 根据str,font的样式以及输出文件目录
    public static void createImage(String text, Font font, File outFile)
            throws Exception {
        // 获取font的样式应用在str上的整个矩形
        double rate=1.3;
        int[] arr = getWidthAndHeight(text, font);
        int width =   (int) Math.floor(arr[0]*rate);
        int height = arr[1];
        // 创建图片
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_BGR);//创建图片画布
        Graphics g = image.getGraphics();
        g.setClip(0, 0, width, height);
        g.setColor(Color.WHITE); // 先用白色填充整张图片,也就是背景
        g.fillRect(0, 0, width, height);//画出矩形区域,以便于在矩形区域内写入文字
        g.setColor(Color.black);// 再换成黑色,以便于写入文字
        g.setFont(font);// 设置画笔字体
        int x=(int)(width/2-rate*g.getFontMetrics().stringWidth(text)/2);
        int y=height/2+g.getFontMetrics().getHeight()/3;
 
        MyDrawString(text, x, y, rate, g);
        
        //g.drawString(text, 1, font.getSize());// 画出一行字符串
       // g.drawString(text, 0, 2 * font.getSize());// 画出第二行字符串,注意y轴坐标需要变动
        g.dispose();
        ImageIO.write(image, "png", outFile);// 输出png图片
    }
    
    public static void MyDrawString(String str,int x,int y,double rate,Graphics g){
        String tempStr=new String();
        int orgStringWight=g.getFontMetrics().stringWidth(str);
        int orgStringLength=str.length();
        int tempx=x;
        int tempy=y;
        while(str.length()>0)
        {
            tempStr=str.substring(0, 1);
            str=str.substring(1, str.length());
            g.drawString(tempStr, tempx, tempy);
            tempx=(int)(tempx+(double)orgStringWight/(double)orgStringLength*rate);
        }
    }
    private static int[] getWidthAndHeight(String text, Font font) {
        Rectangle2D r = font.getStringBounds(text, new FontRenderContext(
                AffineTransform.getScaleInstance(1, 1), true, true));
        int unitHeight = (int) Math.floor(r.getHeight());// 
        // 获取整个str用了font样式的宽度这里用四舍五入后+1保证宽度绝对能容纳这个字符串作为图片的宽度
        int width = (int) Math.round(r.getWidth());
        // 把单个字符的高度+3保证高度绝对能容纳字符串作为图片的高度
        int height = unitHeight ;
        //System.out.println("width:" + width + ", height:" + height);
        return new int[]{width, height};
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值