Chinaunix首页 | 论坛 | 博客
  • 博客访问: 130310
  • 博文数量: 17
  • 博客积分: 2510
  • 博客等级: 少校
  • 技术积分: 320
  • 用 户 组: 普通用户
  • 注册时间: 2007-10-28 10:38
文章分类

全部博文(17)

文章存档

2009年(1)

2008年(16)

我的朋友

分类: Java

2008-11-25 11:11:03

package cn.js.fan.util;
  
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
  
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
import magick.ImageInfo;
import magick.MagickException;
import magick.MagickImage;
  
public class JMagickServlet extends HttpServlet {
  
    /**
     * Constructor of the object.
     */

    public JMagickServlet() {
        super();
    }
  
    /**
     * Destruction of the servlet.

     */

    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log

        // Put your code here

    }
  
    /**
     * The doGet method of the servlet.

     *
     * This method is called when a form has its tag value method equals to get.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request,response);
    }
  
    /**
     * The doPost method of the servlet.

     *
     * This method is called when a form has its tag value method equals to post.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
  
  
        //获取图片URL

        String imageURL = request.getParameter("url");
  
        //获取服务器保存缩略照片文件夹的路径

        String realURL = this.getServletConfig().getServletContext().getRealPath("/")+"upfile\\wml\\";
        //截取图片的相对路径

        String tempURL = imageURL.substring(imageURL.indexOf("upfile"));
        System.out.println(tempURL.substring(7));
        //组合成文件在服务器的绝对路径

        String str = (tempURL.substring(7)).replaceAll("/", "\\\\");
        //获取原图片的绝对路径

        String str1 = imageURL.substring(imageURL.indexOf("upfile")).replaceAll("/", "\\\\");
        String n_url = this.getServletConfig().getServletContext().getRealPath("/")+str1;
           
        String wapURL = realURL+str;
  
        if((new File(wapURL).exists())) {//判断该图片是否已经缩小

            System.out.println("该图片已缩小");
            this.imageStream(wapURL, request, response);//输出图像的文件流

            return ;
        }
           
           
           
           
        //获取图片的绝对路径

        String normalPicURL = this.getServletConfig().getServletContext().getRealPath("/")+"upfile\\"+str;
        FileInputStream in = new FileInputStream(normalPicURL);
  
        BufferedImage bi = ImageIO.read(in);
        int x = bi.getWidth();//获取图片的宽

        int y = bi.getHeight();//获取图片的高

        int narrow_x = 0;
        int narrow_y = 0;
  
        //判断图片是否需要缩小

        if(x > 120 || y > 120) {
            if(x > y) {
                narrow_y = y/(x/120);
                narrow_x = 120;
            }
            if(y > x) {
                narrow_x = x/(y/120);
                narrow_y = 120;
            }
        }else{
            System.out.println("图片不用缩小");
            this.imageStream(normalPicURL, request, response);//输出图像的文件流

            return;
        }
           
           
           
           
        String [] s = tempURL.split("/");
        String path = "";
        //判断路径上的文件夹是否存在,不存在则创建

        for(int i=1; i<s.length-1; i++) {
            File f2 = new File(realURL+s[i]);
            if(!f2.exists()) {
                f2.mkdir();
            }
            realURL += s[i]+"\\";
            path += s[i]+"/";
               
        }
        //图片生成的路径

        String URL = realURL+s[s.length-1];
           
        System.out.println(n_url);
        //图片进行缩略

        try{
            System.setProperty("jmagick.systemclassloader","no");
            ImageInfo info = new ImageInfo(n_url);
            MagickImage image = new MagickImage(info);
            MagickImage scaleImg = image.scaleImage(narrow_x, narrow_y);
            scaleImg.setFileName(URL);
            scaleImg.writeImage(info);
            scaleImg.destroyImages();
            image.destroyImages();
            this.imageStream(URL, request, response);//输出

               
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
       
       
    public void imageStream(String url,HttpServletRequest request, HttpServletResponse response) {
        try {
            String [] str = url.split("\\.");
            FileInputStream in = new FileInputStream(url);
               
            int i = in.available();
            byte [] data = new byte[i];
            in.read(data);//读取图像数据流

            in.close();
  
            response.setContentType("image/"+str[str.length-1]);
            OutputStream out = response.getOutputStream();
            out.write(data);//将图像数据写入输出流

            out.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block

            e.printStackTrace();
        }
    }
  
    /**
     * Initialization of the servlet.

     *
     * @throws ServletException if an error occurs
     */

    public void init() throws ServletException {
        // Put your code here

    }
  
}

package cn.js.fan.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

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

import magick.ImageInfo;
import magick.MagickException;
import magick.MagickImage;

public class JMagickServlet extends HttpServlet {

    /**
     * Constructor of the object.
     */

    public JMagickServlet() {
        super();
    }

    /**
     * Destruction of the servlet.

     */

    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log

        // Put your code here

    }

    /**
     * The doGet method of the servlet.

     *
     * This method is called when a form has its tag value method equals to get.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request,response);
    }

    /**
     * The doPost method of the servlet.

     *
     * This method is called when a form has its tag value method equals to post.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {


        //获取图片URL

        String imageURL = request.getParameter("url");

        //获取服务器保存缩略照片文件夹的路径

        String realURL = this.getServletConfig().getServletContext().getRealPath("/")+"upfile\\wml\\";
        //截取图片的相对路径

        String tempURL = imageURL.substring(imageURL.indexOf("upfile"));
        System.out.println(tempURL.substring(7));
        //组合成文件在服务器的绝对路径

        String str = (tempURL.substring(7)).replaceAll("/", "\\\\");
        //获取原图片的绝对路径

        String str1 = imageURL.substring(imageURL.indexOf("upfile")).replaceAll("/", "\\\\");
        String n_url = this.getServletConfig().getServletContext().getRealPath("/")+str1;
        
        String wapURL = realURL+str;

        if((new File(wapURL).exists())) {//判断该图片是否已经缩小

            System.out.println("该图片已缩小");
            this.imageStream(wapURL, request, response);//输出图像的文件流

            return ;
        }
        
        
        
        
        //获取图片的绝对路径

        String normalPicURL = this.getServletConfig().getServletContext().getRealPath("/")+"upfile\\"+str;
        FileInputStream in = new FileInputStream(normalPicURL);

        BufferedImage bi = ImageIO.read(in);
        int x = bi.getWidth();//获取图片的宽

        int y = bi.getHeight();//获取图片的高

        int narrow_x = 0;
        int narrow_y = 0;

        //判断图片是否需要缩小

        if(x > 120 || y > 120) {
            if(x > y) {
                narrow_y = y/(x/120);
                narrow_x = 120;
            }
            if(y > x) {
                narrow_x = x/(y/120);
                narrow_y = 120;
            }
        }else{
            System.out.println("图片不用缩小");
            this.imageStream(normalPicURL, request, response);//输出图像的文件流

            return;
        }
        
        
        
        
        String [] s = tempURL.split("/");
        String path = "";
        //判断路径上的文件夹是否存在,不存在则创建

        for(int i=1; i<s.length-1; i++) {
            File f2 = new File(realURL+s[i]);
            if(!f2.exists()) {
                f2.mkdir();
            }
            realURL += s[i]+"\\";
            path += s[i]+"/";
            
        }
        //图片生成的路径

        String URL = realURL+s[s.length-1];
        
        System.out.println(n_url);
        //图片进行缩略

        try{
            System.setProperty("jmagick.systemclassloader","no");
            ImageInfo info = new ImageInfo(n_url);
            MagickImage image = new MagickImage(info);
            MagickImage scaleImg = image.scaleImage(narrow_x, narrow_y);
            scaleImg.setFileName(URL);
            scaleImg.writeImage(info);
            scaleImg.destroyImages();
            image.destroyImages();
            this.imageStream(URL, request, response);//输出

            
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    
    public void imageStream(String url,HttpServletRequest request, HttpServletResponse response) {
        try {
            String [] str = url.split("\\.");
            FileInputStream in = new FileInputStream(url);
            
            int i = in.available();
            byte [] data = new byte[i];
            in.read(data);//读取图像数据流

            in.close();

            response.setContentType("image/"+str[str.length-1]);
            OutputStream out = response.getOutputStream();
            out.write(data);//将图像数据写入输出流

            out.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block

            e.printStackTrace();
        }
    }

    /**
     * Initialization of the servlet.

     *
     * @throws ServletException if an error occurs
     */

    public void init() throws ServletException {
        // Put your code here

    }

}


页面显示

Java代码
<img src="/servlet/JMagickServlet?url=图片路径"/>

<img src="/servlet/JMagickServlet?url=图片路径"/>

如果在多个web都使用 JMagick 时可能会出现 jmagick.dll already loaded in another classloader 的报错,原因是 JVM 已经载入了, 可以把 jmagick.jar 的包 放到 服务器的lib里面去 解决。
17:54 浏览 (80) 评论 (0) 分类: Java 收藏 2008-09-17
缩略显示servlet生成验证码
Java代码
package image;
  
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.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
  
public class ImageCode extends HttpServlet {
  
    /**
     * Constructor of the object.
     */

    public ImageCode() {
        super();
    }
  
    /**
     * Destruction of the servlet.

     */

    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log

        // Put your code here

    }
  
    /**
     * The doGet method of the servlet.

     *
     * This method is called when a form has its tag value method equals to get.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
  
        doPost(request,response);
    }
  
    /**
     * The doPost method of the servlet.

     *
     * This method is called when a form has its tag value method equals to post.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try{
            int width = 50;
            int height = 20;
            response.setContentType("image/jpeg");
            String s = "";
            Random random = new Random();
            for(int i=0; i<4; i++) {
                s += String.valueOf(random.nextInt(9));
            }
            System.out.println("验证码:"+s);
            HttpSession session = request.getSession();
            session.setAttribute("validataCode", s);
            ServletOutputStream out = response.getOutputStream();
            BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
            Graphics g = image.getGraphics();
            g.setColor(getRandColor(200, 250));
            //填充矩形

            g.fillRect(0, 0, width, height);
             Font mFont = new Font("Times New Roman", Font.BOLD, 18);// 设置字体

             g.setFont(mFont);
             g.setColor(getRandColor(160, 200));
             Random r = new Random();
             //随机的生成一些线

             for (int i = 0; i < 155; i++) {
                 int x2 = r.nextInt(width);
                 int y2 = r.nextInt(height);
                 int x3 = r.nextInt(12);
                 int y3 = r.nextInt(12);
                 g.drawLine(x2, y2, x2 + x3, y2 + y3);
             }
       
             g.setColor(new Color(20 + random.nextInt(110), 20 + random
                     .nextInt(110), 20 + random.nextInt(110)));
       
             g.drawString(s, 2, 16);
             g.dispose();
             // 输出图象到页面

             ImageIO.write((BufferedImage) image, "JPEG", out);
             out.close();
        }catch(Exception e) {
            e.printStackTrace();
        }
           
    }
       
    private Color getRandColor(int fc, int bc) { // 给定范围获得随机颜色

        Random random = new Random();
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
  
  
    /**
     * Initialization of the servlet.

     *
     * @throws ServletException if an error occurs
     */

    public void init() throws ServletException {
        // Put your code here

    }
  
}

package image;

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.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ImageCode extends HttpServlet {

    /**
     * Constructor of the object.
     */

    public ImageCode() {
        super();
    }

    /**
     * Destruction of the servlet.

     */

    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log

        // Put your code here

    }

    /**
     * The doGet method of the servlet.

     *
     * This method is called when a form has its tag value method equals to get.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request,response);
    }

    /**
     * The doPost method of the servlet.

     *
     * This method is called when a form has its tag value method equals to post.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try{
            int width = 50;
            int height = 20;
            response.setContentType("image/jpeg");
            String s = "";
            Random random = new Random();
            for(int i=0; i<4; i++) {
                s += String.valueOf(random.nextInt(9));
            }
            System.out.println("验证码:"+s);
            HttpSession session = request.getSession();
            session.setAttribute("validataCode", s);
            ServletOutputStream out = response.getOutputStream();
            BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
            Graphics g = image.getGraphics();
            g.setColor(getRandColor(200, 250));
            //填充矩形

            g.fillRect(0, 0, width, height);
             Font mFont = new Font("Times New Roman", Font.BOLD, 18);// 设置字体

     g.setFont(mFont);
     g.setColor(getRandColor(160, 200));
     Random r = new Random();
     //随机的生成一些线

          for (int i = 0; i < 155; i++) {
     int x2 = r.nextInt(width);
     int y2 = r.nextInt(height);
     int x3 = r.nextInt(12);
     int y3 = r.nextInt(12);
     g.drawLine(x2, y2, x2 + x3, y2 + y3);
     }
    
          g.setColor(new Color(20 + random.nextInt(110), 20 + random
     .nextInt(110), 20 + random.nextInt(110)));
    
     g.drawString(s, 2, 16);
     g.dispose();
     // 输出图象到页面

     ImageIO.write((BufferedImage) image, "JPEG", out);
     out.close();
        }catch(Exception e) {
            e.printStackTrace();
        }
        
    }
    
    private Color getRandColor(int fc, int bc) { // 给定范围获得随机颜色

        Random random = new Random();
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }


    /**
     * Initialization of the servlet.

     *
     * @throws ServletException if an error occurs
     */

    public void init() throws ServletException {
        // Put your code here

    }

}


WEB.XML配置
Java代码
<servlet>
  <servlet-name>ImageCode</servlet-name>
  <servlet-class>image.ImageCode</servlet-class>
</servlet>
  
<servlet-mapping>
  <servlet-name>ImageCode</servlet-name>
  <url-pattern>/servlet/ImageCode</url-pattern>
</servlet-mapping>

  <servlet>
    <servlet-name>ImageCode</servlet-name>
    <servlet-class>image.ImageCode</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>ImageCode</servlet-name>
    <url-pattern>/servlet/ImageCode</url-pattern>
  </servlet-mapping>

页面显示
Java代码
<img src="<%=request.getContextPath() %>/servlet/ImageCode">

阅读(1118) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~