jsp向页面显示图片,找不到文件时直接使用java画图

来源:互联网 发布:炉石传说盒子 mac 3.0 编辑:程序博客网 时间:2024/06/08 03:27
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {String imgId = request.getParameter("fileId");TSysMapService tsysMapService = (TSysMapService) Framework.getEngine().getContainer().getComponent("tsysMapService");// 鍥剧墖SERVICETSysMap image = tsysMapService.getTSysMapById(imgId);// String// fileFullPath=image.getFilePath()+File.separator+image.getFileName();File file = new File(image.getFilePath());FileInputStream input = null;if (file.exists()) {try {input = new FileInputStream(image.getFilePath());String contentType = "image/*";int i = input.available();byte[] data = new byte[i];input.read(data);input.close();response.setContentType(contentType);OutputStream outStream = response.getOutputStream();outStream.write(data);outStream.close();} catch (Exception e) {e.printStackTrace();PrintWriter out = response.getWriter();out.println("图片无法打开");out.close();}} else {BufferedImage buffer = new BufferedImage(100, 80,BufferedImage.TYPE_INT_RGB);Graphics2D g2 = buffer.createGraphics();Font font = new Font("宋体", Font.BOLD, 12);g2.setFont(font);// actually do the drawingg2.setColor(Color.gray);g2.fillRect(0, 0, 100, 80);g2.setColor(Color.BLACK);g2.drawString("找不到图片", 10, 30);// set the content type and get the output streamresponse.setContentType("image/png");OutputStream os = response.getOutputStream();// output the image as pngImageIO.write(buffer, "png", os);os.close();}}


     参考:Generating Images with JSPs and Servlets

 

原创粉丝点击