java swing 把JTextArea导出为图片

java swing中如何把JTextArea 导出成为一张图片(jpg或png)呢?

核心方法:

/***
	     * convert JTextArea to image
	     * @param ta
	     * @param destFile
	     * @param format
	     */
	    public static File genericImage(JTextArea ta,File destFile,String format){//TODO 如何提高分辨率
			BufferedImage img = new BufferedImage(ta.getWidth(), ta.getHeight(), BufferedImage.TYPE_INT_RGB);
	        Graphics2D g2d = img.createGraphics();
	        ta.printAll(g2d);
	        g2d.dispose();
	        try {
	            ImageIO.write(img, format/*"jpg"*/, destFile);
	        } catch (IOException ex) {
	            ex.printStackTrace();
	        }
	        return destFile;
		}

调用:

private void chooseDestFile(JTextArea ta,String picFormat){
		JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        File selectedFile=new File("C:\\Users\\Administrator\\Pictures\\"+TimeHWUtil.formatDate(new Date(), "yyyyMM"));
        //home目录应该动态获取
//        System.out.println(selectedFile.getAbsolutePath());
        if(!ValueWidget.isNullOrEmpty(selectedFile)){
        	chooser.setSelectedFile(selectedFile);
        }
        chooser.setName("二维码."+picFormat);
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
                "picture Files", picFormat, "二维码");
            chooser.setFileFilter(filter);
        chooser.setDialogType(JFileChooser.SAVE_DIALOG);
        chooser.setControlButtonsAreShown(true);
        chooser.setDialogTitle("保存二维码");
        //            chooser.setVisible(true);
        int result = chooser.showSaveDialog(ta);
        System.out.println("New file:" + result);
        if (result == JOptionPane.OK_OPTION)
        {
            selectedFile = chooser.getSelectedFile();
            if(! SystemHWUtil.isHasSuffix(selectedFile)){
            	selectedFile=new File(selectedFile.getAbsolutePath()+ SystemHWUtil.ENGLISH_PERIOD+picFormat);
            }
            ImageHWUtil.genericImage(ta, selectedFile, picFormat);
            System.out.println("select file:" + selectedFile);
        }
	}

  

界面如下图:
java swing 把JTextArea导出为图片_第1张图片
 

可执行的jar包见附件

参考:http://stackoverflow.com/questions/11894064/java-converting-a-string-in-jtextarea-to-an-image

http://stackoverflow.com/questions/23568114/converting-text-to-image-in-java

http://myjeeva.com/convert-image-to-string-and-string-to-image-in-java.html

你可能感兴趣的:(导出图片,文本转化为图片,文本导出图片)