欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java 实现输出随机图片实例代码

程序员文章站 2023-12-17 22:32:34
java  实现输出随机图片实例代码 输出随机图片(captcha图像):completely automated public turing test to...

java  实现输出随机图片实例代码

输出随机图片(captcha图像):completely automated public turing test to tell computers and humans apart (全自动区分计算机和人类的测试)

相关主要类(jdk 查看api)

bufferedimage:内存图像
graphics:画笔
imageio:输出图像

放在html页面上<img src/>

注意:浏览器默认会缓存图片

   public static int width = 120; 
public static int height = 25; 
 
public void doget(httpservletrequest request, httpservletresponse response) 
    throws servletexception, ioexception { 
 
  response.setcontenttype("text/html"); 
  //创建内存图像 
  bufferedimage image = new bufferedimage(width,height,bufferedimage.type_int_rgb); 
  //勾勒图像 
  graphics graphics = image.getgraphics(); 
  //设置背景 
  graphics.setcolor(color.white); 
  graphics.fillrect(0, 0, width, height); 
  //设置边框 
  graphics.setcolor(color.blue); 
  graphics.drawrect(1, 1, width-2, height-2); 
  //画干扰线 
  graphics.setcolor(color.yellow); 
  for(int i=0;i<8;i++){ 
    int xstart = new random().nextint(width); 
    int ystart = new random().nextint(height); 
    int xend = new random().nextint(width); 
    int yend = new random().nextint(height); 
    graphics.drawline(xstart, ystart, xend, yend); 
  } 
  //写随机数 
  graphics.setcolor(color.red); 
  int x = 5; 
  for(int i=0;i<4;i++){ 
    graphics.drawstring(new random().nextint(9)+"", x, 20); 
    x+=30; 
  } 
  response.setcontenttype("image/jpeg");//设置响应格式 
  imageio.write(image, "jpeg", response.getoutputstream()); 
   
} 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

上一篇:

下一篇: