java 粘貼圖片

來源:互聯網
上載者:User

標籤:java-swing

java swing 程式中如何擷取剪下板中的圖片呢?
下面是我做的一個java swing 圖形介面:

右鍵,出現菜單,點擊菜單中的”paste image”就會擷取剪下板中的圖片

/***     * 把系統剪下板中的圖片黏貼到swing的Label控制項中     */    public void pasteClipboardImageAction(){        BufferedImage bufferedimage=ComponentUtil.getClipboardImage(this.frame);        if(ValueWidget.isNullOrEmpty(bufferedimage)){            GUIUtil23.alert("系統剪下板中無圖片,請先複製圖片");            return;        }        image=bufferedimage;        ByteArrayOutputStream baos = new ByteArrayOutputStream();        try {//把粘貼過來的圖片轉為為二進位(位元組數組)            ImageIO.write(bufferedimage, read_qrcode_from_pic_format/*jpg*/, baos);            QRbytes= baos.toByteArray();            ComponentUtil.appendResult(resultArea, "粘貼的二維碼大小:\t"+QRbytes.length, true);        } catch (IOException e) {            e.printStackTrace();        }        qrResultLabel.setIcon(new ImageIcon(image));    }

核心方法:解析剪下板中的內容

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);        }        return image;    }

作者: 黃威
部落格地址:
CSDN部落客頁
itEye部落客頁

java 粘貼圖片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.