jsp--- 在jsp页面上显示随机图片

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Images extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//利用bufferedImage 构建图片
		BufferedImage image=new BufferedImage(120, 25, BufferedImage.TYPE_INT_RGB);
		Graphics g= image.getGraphics();
	
		setBackground(g);
		
		setBorder(g);
		drawRandomLine(g);
		drawRandomNum(g);
		
		response.setContentType("image/jpeg");
		
		ImageIO.write(image, "jpg", response.getOutputStream());
		
	}

	/*
	 * 在图片上画字
	 */
	private void drawRandomNum(Graphics g) {
		// TODO Auto-generated method stub
		
		 g.setColor(Color.RED);
		 g.setFont(new Font("宋体",Font.BOLD,20));
		 String date[]={"你","是","我","的","全","世","界","哈","了","都"};
		 
		 int x=10;
		 for (int i = 0; i < 4; i++) {
			 
			int index=  new Random().nextInt(date.length);
			g.drawString(date[index], x, 20);
			
			x+=30;
		}
	}
	
/*
 * 在图片上画线
 */
	private void drawRandomLine(Graphics g) {
		
			g.setColor(Color.GREEN);
			for (int i = 0; i < 4; i++) {
				//起始坐标
				int x=new Random().nextInt(120);
				int y=new Random().nextInt(25);
				
				int x1=new Random().nextInt(120);
				int y1=new Random().nextInt(25);
				g.drawLine(x, y, x1, y1);
				
			}
		
	}

	/*
	 * 在图片上填充颜色
	 */
	private void setBorder(Graphics g) {
		// TODO Auto-generated method stub
		g.setColor(Color.WHITE);
		g.fillRect(1, 1, 118, 23);
		
	}

	/*
	 * 设置背景色
	 */
	private void setBackground(Graphics g) {
		// TODO Auto-generated method stub
		g.setColor(Color.BLUE);
		g.fillRect(0, 0, 120, 25);
	}

}

  

转载于:https://www.cnblogs.com/qurui1997/p/10549026.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值