java swing 把控件映射为BufferedImage
如何把java swing的可视控件 转化为BufferedImage 呢?
直接上代码:
/*** * convert JTextArea to image * @param ta * @param destFile * @param format */ public static BufferedImage genericImage(JComponent 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(); if(!ValueWidget.isNullOrEmpty(destFile)){ try { ImageIO.write(img, format/*"jpg"*/, destFile); } catch (IOException ex) { ex.printStackTrace(); } } return img; }
如何把BufferedImage 复制到剪切板:
/*** * 复制图片到剪切板 * @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); }
调用:
BufferedImage img =ImageHWUtil.genericImage(ta, null, "jpg"/*picFormat*/); if(ValueWidget.isNullOrEmpty(img)){ return; } ComponentUtil.setClipboardImage(ta.getParent(),img); ToastMessage toastMessage = new ToastMessage("复制图片到剪切板",3000); toastMessage.setVisible(true);
下面是详细工具类:
package com.swing.component; import java.awt.Color; import java.awt.Container; import java.awt.Frame; import java.awt.Image; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JProgressBar; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import com.common.dict.Constant2; import com.common.util.SystemHWUtil; import com.common.util.TypeUtil; import com.common.util.WindowUtil; import com.io.hw.file.util.FileUtils; import com.string.widget.util.ValueWidget; import com.swing.menu.MenuUtil2; import com.swing.messagebox.GUIUtil23; import com.time.util.TimeHWUtil; public final class ComponentUtil { /*** * 为了防止JTextField 重复增加 DocumentListener */ public static Listtfs = new ArrayList (); /*** * 获取指定页面 复选框被选中的个数 * * @param checkBoxes * @param startIndex * :currentPage * size_per_page * @param count * @return */ public static int getSelSum(List checkBoxes, int startIndex, int count) { if (checkBoxes == null || checkBoxes.size() == 0) { return 0; } else { JCheckBox[] chkArr = getCurrentPageChkbox(checkBoxes, startIndex, count); if (chkArr == null) { return 0; } int tmp = 0; for (int i = 0; i < chkArr.length; i++) { JCheckBox array_element = chkArr[i]; tmp += TypeUtil.bool2int(array_element.isSelected()); } return tmp; } } /*** * * @param checkBoxes * @param startIndex * :0,5,10,15 ;if =-1,indicate no paging * @param count * :size of per page */ public static void setSelect(List checkBoxes, int startIndex, int count) { JCheckBox[] chkArr = getCurrentPageChkbox(checkBoxes, startIndex, count); if (ValueWidget.isNullOrEmpty(chkArr)) { return; } for (int i = 0; i < chkArr.length; i++) { JCheckBox chk = chkArr[i]; chk.setSelected(true); // System.out.println(2); } } /*** * * @param checkBoxes * @param startIndex * :0,5,10,15 ;if =-1,indicate no paging and omit count * @param count * :omit when startIndex=-1 * @return */ public static JCheckBox[] getCurrentPageChkbox(List checkBoxes, int startIndex, int count) { if (checkBoxes == null || checkBoxes.size() == 0) { return null; } else { int endIndex = startIndex + count; int sum_chk = checkBoxes.size(); if (/*startIndex == -1*/startIndex <0) { startIndex = 0; } else { if (sum_chk < endIndex) { endIndex = sum_chk; } } JCheckBox[] chkArr = new JCheckBox[endIndex - startIndex]; int index3 = 0; for (int i = startIndex; i < endIndex&i 7){ // length=length-17; // } try { doc.insertString(length, result, set); length = length + result.length(); if (isAddDivide) { doc.insertString(length, SystemHWUtil.DIVIDING_LINE + SystemHWUtil.CRLF, null); } } catch (BadLocationException e) { e.printStackTrace(); GUIUtil23.warningDialog(e.getMessage()); } } /*** * 在实际使用过程中,应该放在线程中 * * @param in * @param sourceSize * : 输入流的长度,即要读取的字节个数 * @param targfile */ public static void progress(JProgressBar copyProgressBar, InputStream in, long sourceSize, File targfile) { FileOutputStream target = null; try { int bytesArrLeng = 0; if (sourceSize < SystemHWUtil.BUFF_SIZE_1024) {// bytesArrLeng = (int) sourceSize; } else { long shangOne = sourceSize / SystemHWUtil.NUMBER_100; if (shangOne == 0) {// sourceSize<100 shangOne = shangOne + 1; } if (shangOne <= SystemHWUtil.BUFF_SIZE_1024) { bytesArrLeng = (int) shangOne; } else { long shangTwo = shangOne / SystemHWUtil.BUFF_SIZE_1024; if (shangOne % SystemHWUtil.BUFF_SIZE_1024 != 0) { shangTwo = shangTwo + 1L; } bytesArrLeng = (int) (shangOne / shangTwo); } } System.out.println("字节数组的长度是:" + bytesArrLeng); target = new FileOutputStream(targfile); byte[] buffer = new byte[bytesArrLeng]; int byteNum; long hasReadByte = 0L;// 已经读取的字节个数 float result; int progressSize = 0; while ((byteNum = in.read(buffer)) != SystemHWUtil.NEGATIVE_ONE) { target.write(buffer, 0, byteNum); hasReadByte = hasReadByte + byteNum; result = (float) ((double) hasReadByte / sourceSize); progressSize = Math.round(result * SystemHWUtil.NUMBER_100); updateProgress(copyProgressBar, progressSize); } if (progressSize < SystemHWUtil.NUMBER_100) { progressSize = SystemHWUtil.NUMBER_100; updateProgress(copyProgressBar, progressSize); } copyProgressBar.setForeground(Color.blue); } catch (Exception e) { e.printStackTrace(); GUIUtil23.errorDialog(e); // copyFileBtn.setEnabled(true); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); GUIUtil23.errorDialog(e); } in = null; } if (target != null) { try { target.close(); } catch (IOException e) { e.printStackTrace(); GUIUtil23.errorDialog(e); } target = null; } } } /*** * 更新进度条上得进度数字 * * @param copyProgressBar * @param progressSize */ private static void updateProgress(JProgressBar copyProgressBar, int progressSize) { copyProgressBar.setString(progressSize + "%"); copyProgressBar.setValue(progressSize); } /*** * 复制图片到剪切板 * @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); } public static BufferedImage getClipboardImage(Frame frame) { // java.lang.ClassCastException: sun.awt.datatransfer.TransferableProxy cannot be cast to sun.awt.datatransfer.ClipboardTransferable Transferable trans=frame.getToolkit().getSystemClipboard().getContents(null); BufferedImage image=null; // if(trans instanceof ClipboardTransferable){ // ClipboardTransferable clipboardTrans =(ClipboardTransferable)trans; try { if (null != trans && trans.isDataFlavorSupported(DataFlavor.imageFlavor)) { Object obj22=trans.getTransferData(DataFlavor.imageFlavor); if(!ValueWidget.isNullOrEmpty(obj22)){ if(obj22 instanceof BufferedImage){ image=(BufferedImage)obj22; } } } } catch (UnsupportedFlavorException e1) { e1.printStackTrace(); GUIUtil23.errorDialog(e1); } catch (IOException e1) { e1.printStackTrace(); GUIUtil23.errorDialog(e1); } // } /*try { Map map=(Map)ReflectHWUtils.getObjectValue(clipboardTrans, "flavorsToData"); Object val=null; for(Object obj:map.keySet()){ val=map.get(obj); break; } byte[] data=(byte[])ReflectHWUtils.getObjectValue(val, "data"); return data;//(BufferedImage)trans.getTransferData(trans.getTransferDataFlavors()[0]); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); }*/ return image; } /*** * * @param comb * @param urls */ public static void fillComboBox(JComboBox comb,String urls[]){ if(comb==null||ValueWidget.isNullOrEmpty(urls)){ return; } for(int i=0;i comb,String picUrls){ if(!ValueWidget.isNullOrEmpty(picUrls)){//为空判断 String urls[]=picUrls.split(Constant2.SHAREDPICDIVISION); ComponentUtil.fillComboBox(comb, SystemHWUtil.unique(urls)); } } public static JComboBox comboBoxSelectedHandle(JComboBox comboBox,final JTextField ipTextField){ if(ValueWidget.isNullOrEmpty(comboBox)){ comboBox = new JComboBox (); } comboBox.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { JComboBox target=(JComboBox )e.getSource(); String selectedPort=(String)target.getSelectedItem(); if(!ValueWidget.isNullOrEmpty(selectedPort)){ ipTextField.setText(selectedPort); } // System.out.println(e.getSource()); } }); comboBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { JComboBox target=(JComboBox )e.getSource(); String selectedPort=(String)target.getSelectedItem(); if(!ValueWidget.isNullOrEmpty(selectedPort)){ ipTextField.setText(selectedPort); } } }); return comboBox; } /*** * * @param tc */ public static void trim(JTextComponent tc){ String text=tc.getText(); if(text!=null && text.length()>0){ tc.setText(text.trim()); } } }