使用java的画图类

来源:互联网 发布:网络高级工视频 编辑:程序博客网 时间:2024/06/03 04:37

今天写一个验证码的小程序,顺便也就学习了用java的Image的类画图的一些知识。

//得到图片缓存区BufferedImage bi=new BufferedImage(150, 70, BufferedImage.TYPE_INT_RGB);//得到绘制环境(得到图片的笔)这支笔是这幅图片定制的笔Graphics2D g2=(Graphics2D) bi.getGraphics();g2.setColor(Color.WHITE);//通过这支笔可以设置字体、颜色等操作g2.fillRect(0, 0, 150, 70);//填充整张图片g2.setColor(Color.RED);g2.drawRect(0, 0, 150-1, 70-1);//画边框g2.setColor(Color.BLACK);g2.setFont(new Font("宋体",Font.PLAIN,30));//字体:名称,格式,字号g2.drawString("hello", 3, 50);ImageIO.write(bi,"JPEG",new FileOutputStream("F:/hello.jpg"));//将所得图片缓存区中的内容画出去
如果要实现画出验证码,只需要加上相应的随机函数就可以了;
private int w=70;//输出图片的长和宽private int h=35;private Random r=new Random();private String[] fontname={"宋体","黑体","楷体","雅黑","楷体"};private String codes="123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";private Color bgColor=new Color(255,255,255);//背景色白色private String text;//验证码上的字符
在以上的各个数组中取随机下标拼接出来就是验证码了。



如果要在GUI上画图,可以写一个继承JPanel的类,重写里面的paint方法,

    public void paint(Graphics g) {
BufferedImage bi=new BufferedImage(150, 70, BufferedImage.TYPE_INT_RGB);
Graphics2D g2=(Graphics2D) bi.getGraphics();
//然后就可以用g2这支笔在图片上画图

   g.drawImage(bi, 0, 0, this);//这里的g是画板的笔,用来将图片画在画板上。
//上面的this是observer,也就是画板    }