java swing實現簡單圖片顯示(測試產生圖片捷徑)

來源:互聯網
上載者:User
package com.ts.x;import java.awt.Image;import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.net.URL;import java.util.Hashtable;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JLabel;import com.google.zxing.BarcodeFormat;import com.google.zxing.EncodeHintType;import com.google.zxing.MultiFormatWriter;import com.google.zxing.common.BitMatrix;public class SwingTestImg  extends JFrame{private static final long serialVersionUID = 1L;private JLabel label;private Icon icon;private Image image;public static void main(String[] args) {new SwingTestImg();}public SwingTestImg(){try{setTitle("測試圖片簡單顯示");setSize(300,300);setDefaultCloseOperation(DISPOSE_ON_CLOSE);label = new JLabel();add(label);setVisible(true);//A:網路URL圖片//icon = new ImageIcon(new URL("http://tp1.sinaimg.cn/3223061260/180/5659068018/1"));//B:項目目錄下圖片//InputStream is = SwingTestImg.class.getResourceAsStream("twodimensioncode.gif");//ByteArrayOutputStream baos = new ByteArrayOutputStream();//byte [] buff = new byte[100];//int readCount = 0;//while((readCount = is.read(buff,0,100)) > 0){//baos.write(buff,0,readCount);//}//byte [] inbyte = baos.toByteArray();//icon =  new ImageIcon(inbyte);////C:本地磁碟圖片,圖片太大,會導致空白顯示//image =  new ImageIcon("D:/1.png").getImage();//D:代碼產生的BufferedImage二維碼圖片Hashtable hints = new Hashtable();hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");BitMatrix matrix = new MultiFormatWriter().encode("http://www.vcspark.com/", BarcodeFormat.QR_CODE, 300, 300,hints);int width = matrix.getWidth();int height = matrix.getHeight();BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);for(int x = 0;x < width; x++){for(int y = 0;y < height; y++){image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);}}icon = new ImageIcon(image);}catch(Exception e){System.out.println("初始化失敗"+e.getMessage());e.printStackTrace();}label.setIcon(icon);//label.setIcon(new ImageIcon(image));} }


 

測試二維碼產生結果:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.