swing 对文本域截图
直接上代码:
/*** * convert JTextArea to image * @param ta * @param destFile * @param format */ public static BufferedImage generateImage(JComponent ta,File destFile,String format,Integer specifiedHeight,Integer specifiedWidth){//TODO 如何提高分辨率 int height=ta.getHeight(); int width=ta.getWidth(); if(specifiedHeight!=null&&specifiedHeight!=SystemHWUtil.NEGATIVE_ONE){//如果指定了高度 height=specifiedHeight; } if(specifiedWidth!=null&&specifiedWidth!=SystemHWUtil.NEGATIVE_ONE){//如果指定了高度 width=specifiedWidth; } BufferedImage img = new BufferedImage(width * 4, height * 4, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = img.createGraphics(); g2d.scale(4, 4); ta.printAll(g2d); g2d.dispose(); if(!ValueWidget.isNullOrEmpty(destFile)){ try { ImageIO.write(img, format/*"jpg"*/, destFile); } catch (IOException ex) { ex.printStackTrace(); } } return img; }
提高分辨率:
调用:
/*** * 截图,截屏 * @param ta * @param specifiedHeight * @param specifiedWidth */ public static void generateImageAndCopy(JTextComponent ta, Integer specifiedHeight,Integer specifiedWidth) { BufferedImage img = ImageHWUtil.generateImage(ta, null, "jpg"/*picFormat*/,specifiedHeight,specifiedWidth); if(ValueWidget.isNullOrEmpty(img)){ return; } ComponentUtil.setClipboardImage(ta.getParent(),img); ToastMessage.toast("复制图片到剪切板",3000); } /*** * 复制图片到剪切板 * @param image */ public static void setClipboardImage(Container frame, final Image image) { Transferable trans = new Transferable() { @Override public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { if (isDataFlavorSupported(flavor)) { return image; } throw new UnsupportedFlavorException(flavor); } @Override public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] { DataFlavor.imageFlavor }; } @Override public boolean isDataFlavorSupported(DataFlavor flavor) { return DataFlavor.imageFlavor.equals(flavor); } }; frame.getToolkit().getSystemClipboard().setContents(trans, null); }
Try creating the BufferedImage with twice the size (ie. size.width * 2, size.height * 2), then set ig's scale to 2 and g2draw's scale to 0.5.
参考:http://stackoverflow.com/questions/31393438/java-swing-bufferedimage-poor-quality