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);
- }
- }
界面如下图: