java swing实现简单图片显示(测试生成图片快捷方式)

原链接:https://yq.aliyun.com/articles/58303

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值