补充上次发的 图片压缩 剪切功能

来源:互联网 发布:es6数组去重 编辑:程序博客网 时间:2024/04/30 08:36

package com.ad.web.servlet.userimg.servlet;

import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;

import cn.richinfo.cmail.common.config.PropertiesUtil;

import com.ad.web.common.CommonConst;
import com.ad.web.servlet.userimg.imgprocess.cutimg.cutPic;
import com.ad.web.servlet.userimg.imgprocess.zipimg.zipPic;
import com.ad.web.servlet.userimg.pojo.Message;
import com.google.gson.Gson;

@SuppressWarnings("serial")
public class ImgUpload extends HttpServlet
{
    private static final Logger log = Logger.getLogger(ImgUpload.class);

    final String[] allowtype = new String[] { "jpg", "gif", "bmp", "jpeg",
            "png", "JPG","PNG","GIF","BMP","JPEG" }; // 允许上传的文件格式的列表

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

    @SuppressWarnings( { "deprecation", "unchecked" })
    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException
    {

        String imgsize = PropertiesUtil.getProperty(CommonConst.IMG_SIZE);
        int upmaxsize = 3;
        if (imgsize != null && !"".equals(imgsize))
        {
            upmaxsize = Integer.parseInt(imgsize);
        }
        long MAX_SIZE = upmaxsize * 1024 * 1024;// 设置上传文件最大为 1M

        String maindomain = "";
        Cookie[] cookies = request.getCookies();
        if (cookies != null)
        {
            for (int i = 0; i < cookies.length; i++)
            {
                String cookieName = cookies[i].getName();
                if ("maindomain".equals(cookieName))
                {
                    maindomain = cookies[i].getValue();

                }
            }
        }

        String retr ="";
        String fc=request.getParameter("func");
        if(fc!=null && !"".equals(fc))
        {
            fc=StringEscapeUtils.escapeHtml(fc);
            retr=URLEncoder.encode(fc, "UTF-8");
        }
        
        
        
        
        
        String path = null;
        FileItem fileItem = null;
        FileItem fileUploadItem = null;
        File file = null;
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String x1 = "0";
        String y1 = "0";
        String w1 = "0";
        String h1 = "0";

        String flag = request.getParameter("flag");// 0:表示上传剪切和压缩 1:剪切和压缩

        // 2:表示只上传
        String url = "";
        try
        {
            if ("0".equals(flag))
            {
                DiskFileItemFactory dfif = new DiskFileItemFactory();
                dfif.setSizeThreshold(4 * 1024);
                if (!(new File(request.getRealPath("/") + "uploadtemp")
                        .isDirectory()))
                {
                    new File(request.getRealPath("/") + "uploadtemp").mkdir();
                }
                dfif.setRepository(new File(request.getRealPath("/")
                        + "uploadtemp"));
                ServletFileUpload sfu = new ServletFileUpload(dfif);

                List fileList = null;
                fileList = sfu.parseRequest(request);
                if (fileList == null || fileList.size() == 0)
                {
                    resMessage(out, "ERROR", "没有发现文件", "", maindomain);
                    return;
                }
                Iterator fileItr = fileList.iterator();

                while (fileItr.hasNext())
                {
                    long size = 0;
                    fileItem = (FileItem) fileItr.next();
                    if (fileItem.isFormField())
                    {
                        String name = fileItem.getFieldName();
                        String v = fileItem.getString();
                        if ("x".equals(name))
                        {
                            x1 = v;
                        }
                        if ("y".equals(name))
                        {
                            y1 = v;
                        }
                        if ("w".equals(name))
                        {
                            w1 = v;
                        }
                        if ("h".equals(name))
                        {
                            h1 = v;
                        }
                        if ("u".equals(name))
                        {
                            url = v;
                        }
                    }
                    else
                    {
                        fileUploadItem = fileItem;
                        path = fileItem.getName();
                        size = fileItem.getSize();
                        if ("".equals(path) || size == 0)
                        {
                            resMessage(out, "ERROR", "没有发现文件", retr, maindomain);
                            return;
                        }
                    }
                }
                if ("".equals(path) || path == null)
                {
                    resMessage(out, "ERROR", "没有发现文件", retr, maindomain);
                    return;
                }
                String t_name = path.substring(path.lastIndexOf("\\") + 1);
                String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
                // 拒绝接受规定文件格式之外的文件类型
                int allowFlag = 0;
                int allowedExtCount = allowtype.length;
                for (; allowFlag < allowedExtCount; allowFlag++)
                {
                    if (allowtype[allowFlag].equals(t_ext))
                    {
                        break;
                    }
                }
                if (allowFlag == allowedExtCount)
                {
                    String message = "";
                    for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++)
                    {
                        message += "*." + allowtype[allowFlag] + " ";
                    }
                    resMessage(out, "ERROR", "文件格式不正确,请上传:" + message, retr,
                            maindomain);
                    return;
                }

                if (fileUploadItem.getSize() > MAX_SIZE)
                {
                    resMessage(out, "ERROR", "最大上传:" + upmaxsize + "M", retr,
                            maindomain);
                    return;
                }

                long now = System.currentTimeMillis();
                String prefix = String.valueOf(now);

                String newpath = PropertiesUtil.getProperty(CommonConst.IMG);
                String[] confimg = newpath.split("/");
                List<String> imgPath = new ArrayList<String>();
                for (int i = 0; i < confimg.length; i++)
                {
                    imgPath.add(confimg[i]);
                }
                int y, m, d;
                Calendar cal = Calendar.getInstance();
                y = cal.get(Calendar.YEAR);
                m = cal.get(Calendar.MONTH);
                d = cal.get(Calendar.DATE);
                imgPath.add(String.valueOf(y));
                imgPath.add(String.valueOf(m + 1));
                imgPath.add(String.valueOf(d));
                imgPath.add(String.valueOf(y) + "-" + String.valueOf(m + 1)
                        + "-" + String.valueOf(d));
                String webdir = request.getRealPath("/");
                String resPath = "";
                String temp = "";
                String newdir = "";
                for (int j = 0; j < imgPath.size(); j++)
                {
                    resPath = resPath + imgPath.get(j) + "/";
                    temp = temp + imgPath.get(j) + "/";
                    newdir = webdir + temp;
                    if (!(new File(newdir).isDirectory()))
                    {
                        new File(newdir).mkdir();
                    }
                }
                String imgpath = newdir + prefix + "." + t_ext;
                fileUploadItem.write(new File(imgpath));

                boolean bo = isImage(new File(imgpath));
                if (bo)
                {
                    long now_new = System.currentTimeMillis();
                    String prefix_new = String.valueOf(now_new);
                    String imgpath_new = newdir + prefix_new + "." + t_ext;
                    Message mesg = imgproccess(imgpath,imgpath_new, x1, y1, w1, h1);
                    if ("S_OK".equals(mesg.getCode()))
                    {
                        //resPath = "/" + resPath + prefix + "." + t_ext;
                        resPath = "/" + resPath + prefix_new + "." + t_ext;
                        resMessage(out, "S_OK", resPath, retr, maindomain);
                    }
                    else
                    {
                        File del_file = new File(imgpath);
                        if (del_file.isFile() && del_file.exists())
                        {
                            del_file.delete();
                        }
                        resMessage(out, "ERROR", "文件格式错误", retr, maindomain);
                    }
                }
                else
                {
                    resMessage(out, "ERROR", "文件格式错误", retr, maindomain);
                }

            }
            else if ("1".equals(flag))
            {
                DiskFileItemFactory dfif = new DiskFileItemFactory();
                dfif.setSizeThreshold(4 * 1024);
                if (!(new File(request.getRealPath("/") + "uploadtemp")
                        .isDirectory()))
                {
                    new File(request.getRealPath("/") + "uploadtemp").mkdir();
                }
                dfif.setRepository(new File(request.getRealPath("/")
                        + "uploadtemp"));
                ServletFileUpload sfu = new ServletFileUpload(dfif);
                List fileList = null;
                fileList = sfu.parseRequest(request);
                if (fileList == null || fileList.size() == 0)
                {
                    resMessage(out, "ERROR", "没有发现文件", "", maindomain);
                    return;
                }
                Iterator fileItr = fileList.iterator();

                while (fileItr.hasNext())
                {
                    fileItem = (FileItem) fileItr.next();
                    if (fileItem.isFormField())
                    {
                        String name = fileItem.getFieldName();
                        String v = fileItem.getString();
                        if ("x".equals(name))
                        {
                            x1 = v;
                        }
                        if ("y".equals(name))
                        {
                            y1 = v;
                        }
                        if ("w".equals(name))
                        {
                            w1 = v;
                        }
                        if ("h".equals(name))
                        {
                            h1 = v;
                        }
                        if ("u".equals(name))
                        {
                            url = v;
                        }
                    }
                    else
                    {
                        fileUploadItem = fileItem;
                        path = fileItem.getName();

                    }
                }
                String webdir1 = request.getRealPath("/");
                String pathnew =  webdir1 + url;
                

                // 判断文件是否为图片
                
                String t_name = url.substring(0,url.lastIndexOf("/") + 1);
                String t_ext = url.substring(url.lastIndexOf(".") + 1);
                
                long now_new = System.currentTimeMillis();
                String prefix_new = String.valueOf(now_new);
                
                String imgpath_new = webdir1 + t_name+prefix_new + "." + t_ext;
                Message mesg = imgproccess(pathnew, imgpath_new,x1, y1, w1, h1);


                if ("S_OK".equals(mesg.getCode()))
                {
                    String newPaht=t_name+prefix_new + "." + t_ext;
                    resMessage(out, "S_OK", newPaht, retr, maindomain);
                }
                else
                {
                    resMessage(out, "ERROR", "文件格式错误", retr, maindomain);
                }

            }
            else if ("2".equals(flag))
            {
                DiskFileItemFactory dfif = new DiskFileItemFactory();
                dfif.setSizeThreshold(4 * 1024);
                if (!(new File(request.getRealPath("/") + "uploadtemp")
                        .isDirectory()))
                {
                    new File(request.getRealPath("/") + "uploadtemp").mkdir();
                }
                dfif.setRepository(new File(request.getRealPath("/")
                        + "uploadtemp"));
                ServletFileUpload sfu = new ServletFileUpload(dfif);

                List fileList = null;
                fileList = sfu.parseRequest(request);
                if (fileList == null || fileList.size() == 0)
                {
                    resMessage(out, "ERROR", "没有发现文件", "", maindomain);
                    return;
                }
                Iterator fileItr = fileList.iterator();

                while (fileItr.hasNext())
                {
                    long size = 0;
                    fileItem = (FileItem) fileItr.next();
                    if (fileItem.isFormField())
                    {
                        continue;
                    }
                    else
                    {
                        fileUploadItem = fileItem;
                        path = fileItem.getName();
                        size = fileItem.getSize();
                        if ("".equals(path) || size == 0)
                        {
                            resMessage(out, "ERROR", "没有发现文件", retr, maindomain);
                            return;
                        }
                    }
                }
                if ("".equals(path) || path == null)
                {
                    resMessage(out, "ERROR", "没有发现文件", retr, maindomain);
                    return;
                }
                String t_name = path.substring(path.lastIndexOf("\\") + 1);
                String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
                // 拒绝接受规定文件格式之外的文件类型
                int allowFlag = 0;
                int allowedExtCount = allowtype.length;
                for (; allowFlag < allowedExtCount; allowFlag++)
                {
                    if (allowtype[allowFlag].equals(t_ext))
                    {
                        break;
                    }
                }
                if (allowFlag == allowedExtCount)
                {
                    String message = "";
                    for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++)
                    {
                        message += "*." + allowtype[allowFlag] + " ";
                    }
                    resMessage(out, "ERROR", "文件格式不正确:" + message, retr,
                            maindomain);
                    return;
                }

                if (fileUploadItem.getSize() > MAX_SIZE)
                {
                    resMessage(out, "ERROR", "最大上传" + upmaxsize + "M", retr,
                            maindomain);
                }

                long now = System.currentTimeMillis();
                String prefix = String.valueOf(now);

                String newpath = PropertiesUtil.getProperty("img");
                String[] confimg = newpath.split("/");
                List<String> imgPath = new ArrayList<String>();
                for (int i = 0; i < confimg.length; i++)
                {
                    imgPath.add(confimg[i]);
                }
                int y, m, d;
                Calendar cal = Calendar.getInstance();
                y = cal.get(Calendar.YEAR);
                m = cal.get(Calendar.MONTH);
                d = cal.get(Calendar.DATE);
                imgPath.add(String.valueOf(y));
                imgPath.add(String.valueOf(m + 1));
                imgPath.add(String.valueOf(d));
                imgPath.add(String.valueOf(y) + "-" + String.valueOf(m + 1)
                        + "-" + String.valueOf(d));
                String webdir = request.getRealPath("/");
                String resPath = "/";
                String temp = "";
                String newdir = "";
                for (int j = 0; j < imgPath.size(); j++)
                {
                    resPath = resPath + imgPath.get(j) + "/";
                    temp = temp + imgPath.get(j) + "/";
                    newdir = webdir + temp;
                    if (!(new File(newdir).isDirectory()))
                    {
                        new File(newdir).mkdir();
                    }
                }
                String imgpath = newdir + prefix + "." + t_ext;
                fileUploadItem.write(new File(imgpath));
                boolean bo = isImage(new File(imgpath));
                if (bo)
                {
                    resPath = resPath + prefix + "." + t_ext;
                    resMessage(out, "S_OK", resPath, retr, maindomain);
                }
                else
                {
                    File del_file = new File(imgpath);
                    if (del_file.isFile() && del_file.exists())
                    {
                        del_file.delete();
                    }
                    resMessage(out, "ERROR", "文件格式错误", retr, maindomain);
                }

            }
            else
            {
                resMessage(out, "ERROR", "文件格式错误", retr, maindomain);
            }

        }
        catch (FileUploadException e)
        {

            log.error("user imager upload is error", e);
            resMessage(out, "ERROR", "文件格式错误", retr, maindomain);

        }
        catch (Exception e)
        {
            log.error("upload img is error", e);
            resMessage(out, "ERROR", "文件格式错误", retr, maindomain);

        }
        finally
        {
            if (out != null)
            {
                out.close();
            }
            if (file != null)
            {
                if (file.exists())
                {
                    file.delete();
                }
            }
        }
    }

    public static void resMessage(PrintWriter out, String code, String message,
            String retr, String maindomain)

    {
        try
        {
            StringBuffer sbf = new StringBuffer();
            sbf.append("{");
            sbf.append("\"code\":").append("\"").append(code).append("\"")
                    .append(",");
            sbf.append("\"var\":").append("\"").append(message).append("\"");
            sbf.append("}");
            out.println("<html><head>");
            out.println("</head>");
            out.println("<body>");
            out.println("<script type='text/javascript'>");
            if (!"".equals(maindomain))
            {
                out.println("document.domain='" + maindomain + "';");
            }
            if ("".equals(retr))
            {
                out.println("parent.callback(" + sbf.toString() + ");");
            }
            else
            {
                out.println("parent." + retr + "(" + sbf.toString() + ");");
            }
            out.println("</script>");
            out.println("</body>");
            out.println("</html>");
            out.flush();
            out.close();
        }
        finally
        {
            if (out != null)
            {
                out.close();
            }
        }

    }

    public Message  imgproccess(String path,String pathNew, String x, String y,
            String width, String height)
    {
        Message remsg=null;
        Gson gson = new Gson();
        cutPic cut = new cutPic();
        String message = cut.cutpic(path, pathNew, checkNum(x), checkNum(y),
                checkNum(width), checkNum(height));
        Message msg = gson.fromJson(message, Message.class);
        if ("S_OK".equals(msg.getCode()))
        {
            zipPic t1 = new zipPic();
            remsg=t1.resizeImg(pathNew, pathNew, 96, 96);
        }
        else
        {
            remsg=new Message();
            remsg.setCode("ERROR");
            remsg.setVar(msg.getVar());
            return remsg;
        }

        return remsg;

    }

    public static int checkNum(String number)
    {
        try
        {
            String chk = "";
            if (!"".equals(number))
            {
                java.util.regex.Pattern pattern = java.util.regex.Pattern
                        .compile("\\d+\\.\\d*");
                java.util.regex.Matcher match = pattern.matcher(number);
                if (match.matches() == true)
                {
                    String[] nubmers = number.split("\\.");
                    chk = nubmers[0];
                    return Integer.parseInt(chk);
                }

                java.util.regex.Pattern patr = java.util.regex.Pattern
                        .compile("^[1-9]\\d*$");
                java.util.regex.Matcher mach = patr.matcher(number);
                if (mach.matches() == false)
                {
                    return 0;
                }
                else
                {
                    return Integer.parseInt(number);
                }

            }
            else
            {
                return 0;
            }
        }
        catch (Exception e)
        {
            log.error("checkNum is error:", e);
            return 0;
        }

    }

    public static boolean isImage(File imageFile)
    {
        if (!imageFile.exists())
        {
            return false;
        }
        Image img = null;
        try
        {
            img = ImageIO.read(imageFile);
            if (img == null || img.getWidth(null) <= 0
                    || img.getHeight(null) <= 0)
            {
                return false;
            }
            return true;
        }
        catch (Exception e)
        {

            return false;
        }
        finally
        {
            img = null;

        }
    }

}


一、cutPic

package com.ad.web.servlet.userimg.imgprocess.cutimg;


import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import javax.imageio.ImageIO;
import org.apache.log4j.Logger;


import com.ad.web.servlet.userimg.pojo.Message;
import com.google.gson.Gson;


public class cutPic
{
private static final Logger log = Logger.getLogger(cutPic.class);
private int x;


private int y;


private int width;


private int height;


public cutPic()
{


}


public cutPic(int x, int y, int width, int height)
{
this.x = x;
this.y = y;


this.width = width;
this.height = height;
}


public int getHeight()
{
return height;
}


public void setHeight(int height)
{
this.height = height;
}


public int getWidth()
{
return width;
}


public void setWidth(int width)
{
this.width = width;
}


public int getX()
{
return x;
}


public void setX(int x)
{
this.x = x;
}


public int getY()
{
return y;
}


public void setY(int y)
{
this.y = y;
}


public String cutpic(String srcImageFile, String descDir, int x1, int y1,
int w, int h)
{
Message msg=new Message();
Gson gson=new Gson();
try
{
System.setProperty("java.awt.headless", "true");
Image img;
ImageFilter cropFilter;
// 读取源图像
BufferedImage bi = ImageIO.read(new File(srcImageFile));
int srcWidth = bi.getWidth(); // 源图宽度
int srcHeight = bi.getHeight(); // 源图高度

log.error("cutpic ...:"+"x1:"+x1+"y1:"+y1+"w:"+w+" h:"+h+"  srcwith:"+srcWidth+" srcheiht:"+srcHeight);

if (srcWidth >= w && srcHeight >= h)
{
Image image = bi.getScaledInstance(srcWidth, srcHeight,Image.SCALE_DEFAULT);
// 剪切起始坐标点
int wth = w;
int hth = h;
int xx = x1;
int yy = y1;

// 四个参数分别为图像起点坐标和宽高
// 即: CropImageFilter(int x,int y,int width,int height)
cropFilter = new CropImageFilter(xx, yy, wth, hth);
img = Toolkit.getDefaultToolkit().createImage(
new FilteredImageSource(image.getSource(), cropFilter));
BufferedImage tag = new BufferedImage(wth, hth,
BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(img, 0, 0, null); // 绘制缩小后的图
g.dispose();
// 输出为文件
ImageIO.write(tag, "JPEG", new File(descDir));
msg.setCode("S_OK");
msg.setVar("succuess");
}
else
{
msg.setCode("ERROR");
msg.setVar("你期望剪切的高度或宽度大于图片实际高宽度,图片将不能被裁减");
log.error("你期望剪切的高度或宽度大于图片实际高宽度,图片将不能被裁减");
return gson.toJson(msg);
}
}
catch (Exception e)
{
msg.setCode("ERROR");
msg.setVar("文件格式错误");
log.error("图片剪切现错误:"+e.getMessage());
return gson.toJson(msg);

}
return gson.toJson(msg);
}
}

二、zipPic.java

package com.ad.web.servlet.userimg.imgprocess.zipimg;
import java.awt.Graphics2D;   
import java.awt.Image;   
import java.awt.geom.AffineTransform;   
import java.awt.image.AffineTransformOp;   
import java.awt.image.BufferedImage;   
import java.io.File;       
import java.io.FileOutputStream;
import java.io.IOException;     
import javax.imageio.ImageIO;   
import org.apache.log4j.Logger;  


import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class zipPic{   
private static final Logger log = Logger.getLogger(zipPic.class);
    public zipPic(){   
           
    }   
       

   //此方法压缩之后图片会变形
    public void imageOp(String inFilePath, String outFilePath, int width, int height){   
    System.setProperty("java.awt.headless", "true");
    File tempFile = new File(inFilePath); 
       log.error("infilepath="+inFilePath);
        Image image = null;   
        try {   
           image = ImageIO.read(tempFile);   
        } catch (IOException e) {   
         log.error("file path is error"); 
       }   
           
        int originalImageWidth = image.getWidth(null);   
        int originalImageHeight = image.getHeight(null);   
         log.error("1111");
        BufferedImage originalImage = new BufferedImage(   
                originalImageWidth,   
                originalImageHeight,   
                BufferedImage.TYPE_3BYTE_BGR);   
        log.error("222");
        Graphics2D g2d = originalImage.createGraphics();   
        g2d.drawImage(image, 0, 0, null);   
           
        BufferedImage changedImage =   
            new BufferedImage(   
                   width,   
                    height,   
                    BufferedImage.TYPE_3BYTE_BGR);   
           
        double widthBo = (double)width/originalImageWidth;   
        double heightBo = (double)width/originalImageHeight;   
           
        AffineTransform transform = new AffineTransform();   
        transform.setToScale(widthBo, heightBo);   
           
        AffineTransformOp ato = new AffineTransformOp(transform, null);   
        ato.filter(originalImage, changedImage);   
           
        File fo = new File(outFilePath);    
  
        try {   
            ImageIO.write(changedImage, "jpeg", fo);   
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
    } 
    
      //此方法压缩之后图片比较的清晰
public  void resizeImg(String imgsrc, String imgdist, int widthdist,
int heightdist)
{
try
{
System.setProperty("java.awt.headless", "true");
File srcfile = new File(imgsrc);
if (!srcfile.exists())
{
return;
}
Image src = javax.imageio.ImageIO.read(srcfile);
BufferedImage tag = new BufferedImage(widthdist, heightdist,
BufferedImage.TYPE_INT_RGB);
/*
* SCALE_SMOOTH:尺寸平滑 SCALE_AREA_AVERAGING:尺度区平均 SCALE_FAST:尺度快速
* SCALE_REPLICATE:尺度复制
*/
tag.getGraphics().drawImage(
src.getScaledInstance(widthdist, heightdist,
Image.SCALE_SMOOTH), 0, 0, null);
FileOutputStream out = new FileOutputStream(imgdist);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}  

三 、servlet 方法

package com.ad.web.servlet.userimg.servlet;


import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import com.ad.web.common.PropertiesUtil;
import com.ad.web.servlet.userimg.imgprocess.cutimg.cutPic;
import com.ad.web.servlet.userimg.imgprocess.zipimg.zipPic;


@SuppressWarnings("serial")
public class ImgUpload extends HttpServlet
{
private static final Logger log = Logger.getLogger(ImgUpload.class);

final String[] allowtype = new String[] { "jpg", "gif", "bmp", "jpeg",
"png", "JPG" }; // 允许上传的文件格式的列表


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


@SuppressWarnings( { "deprecation", "unchecked" })
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{


String imgsize=PropertiesUtil.getProperty("img_size");
int upmaxsize=3;
if(imgsize!=null && !"".equals(imgsize))
{
upmaxsize=Integer.parseInt(imgsize);
}
long MAX_SIZE = upmaxsize * 1024 * 1024;// 设置上传文件最大为 1M

String maindomain = "";
Cookie[] cookies = request.getCookies();
if (cookies != null)
{
for (int i = 0; i < cookies.length; i++)
{
String cookieName = cookies[i].getName();
if ("maindomain".equals(cookieName))
{
maindomain = cookies[i].getValue();


}
}
}


String retr = request.getParameter("func");
String path = null;
FileItem fileItem = null;
FileItem fileUploadItem = null;
File file = null;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String x1 = "0";
String y1 = "0";
String w1 = "0";
String h1 = "0";

String flag = request.getParameter("flag");// 0:表示上传剪切和压缩 1:剪切和压缩

// 2:表示只上传
String url = "";
try
{
if ("0".equals(flag))
{
DiskFileItemFactory dfif = new DiskFileItemFactory();
dfif.setSizeThreshold(4 * 1024);
if (!(new File(request.getRealPath("/") + "uploadtemp")
.isDirectory()))
{
new File(request.getRealPath("/") + "uploadtemp").mkdir();
}
dfif.setRepository(new File(request.getRealPath("/")
+ "uploadtemp"));
ServletFileUpload sfu = new ServletFileUpload(dfif);


List fileList = null;
fileList = sfu.parseRequest(request);
if (fileList == null || fileList.size() == 0)
{
log.error("file is not find");
resMessage(out, "ERROR", "没有发现文件", "", maindomain);
return;
}
Iterator fileItr = fileList.iterator();


while (fileItr.hasNext())
{
long size = 0;
fileItem = (FileItem) fileItr.next();
if (fileItem.isFormField())
{
String name = fileItem.getFieldName();
String v = fileItem.getString();
if ("x".equals(name))
{
x1 = v;
}
if ("y".equals(name))
{
y1 = v;
}
if ("w".equals(name))
{
w1 = v;
}
if ("h".equals(name))
{
h1 = v;
}
if ("u".equals(name))
{
url = v;
}
}
else
{
fileUploadItem = fileItem;
path = fileItem.getName();
size = fileItem.getSize();
if ("".equals(path) || size == 0)
{
resMessage(out, "ERROR", "没有发现文件", retr, maindomain);
return;
}
}
}
if ("".equals(path) || path == null)
{
resMessage(out, "ERROR", "没有发现文件", retr, maindomain);
return;
}
String t_name = path.substring(path.lastIndexOf("\\") + 1);
String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
// 拒绝接受规定文件格式之外的文件类型
int allowFlag = 0;
int allowedExtCount = allowtype.length;
for (; allowFlag < allowedExtCount; allowFlag++)
{
if (allowtype[allowFlag].equals(t_ext))
{
break;
}
}
if (allowFlag == allowedExtCount)
{
String message = "";
for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++)
{
message += "*." + allowtype[allowFlag] + " ";
}
resMessage(out, "ERROR", "文件格式不正确:" + message, retr,
maindomain);
return;
}


if (fileUploadItem.getSize() > MAX_SIZE)
{
resMessage(out, "ERROR", "最大上传:"+upmaxsize+"M", retr, maindomain);
return;
}


long now = System.currentTimeMillis();
String prefix = String.valueOf(now);


String newpath = PropertiesUtil.getProperty("img");
String[] confimg = newpath.split("/");
List<String> imgPath = new ArrayList<String>();
for (int i = 0; i < confimg.length; i++)
{
imgPath.add(confimg[i]);
}
int y, m, d;
Calendar cal = Calendar.getInstance();
y = cal.get(Calendar.YEAR);
m = cal.get(Calendar.MONTH);
d = cal.get(Calendar.DATE);
imgPath.add(String.valueOf(y));
imgPath.add(String.valueOf(m + 1));
imgPath.add(String.valueOf(d));
imgPath.add(String.valueOf(y) + "-" + String.valueOf(m + 1)
+ "-" + String.valueOf(d));
String webdir = request.getRealPath("/");
String resPath = "";
String temp = "";
String newdir = "";
for (int j = 0; j < imgPath.size(); j++)
{
resPath = resPath + imgPath.get(j) + "/";
temp = temp + imgPath.get(j) + "/";
newdir = webdir + temp;
if (!(new File(newdir).isDirectory()))
{
new File(newdir).mkdir();
}
}
String imgpath = newdir + prefix + "." + t_ext;
fileUploadItem.write(new File(imgpath));


imgproccess(imgpath, x1, y1, w1, h1);
resPath = "/" + resPath + prefix + "." + t_ext;
resMessage(out, "S_OK", resPath, retr, maindomain);


}
else if ("1".equals(flag))
{
DiskFileItemFactory dfif = new DiskFileItemFactory();
dfif.setSizeThreshold(4 * 1024);
if (!(new File(request.getRealPath("/") + "uploadtemp")
.isDirectory()))
{
new File(request.getRealPath("/") + "uploadtemp").mkdir();
}
dfif.setRepository(new File(request.getRealPath("/")
+ "uploadtemp"));
ServletFileUpload sfu = new ServletFileUpload(dfif);
List fileList = null;
fileList = sfu.parseRequest(request);
if (fileList == null || fileList.size() == 0)
{
log.error("file is not find");
resMessage(out, "ERROR", "没有发现文件", "", maindomain);
return;
}
Iterator fileItr = fileList.iterator();


while (fileItr.hasNext())
{
fileItem = (FileItem) fileItr.next();
if (fileItem.isFormField())
{
String name = fileItem.getFieldName();
String v = fileItem.getString();
if ("x".equals(name))
{
x1 = v;
}
if ("y".equals(name))
{
y1 = v;
}
if ("w".equals(name))
{
w1 = v;
}
if ("h".equals(name))
{
h1 = v;
}
if ("u".equals(name))
{
url = v;
}
}
else
{
fileUploadItem = fileItem;
path = fileItem.getName();

}
}
String webdir1 = request.getRealPath("/");
String pathnew = "/" + webdir1 + url;
imgproccess(pathnew, x1, y1, w1, h1);
resMessage(out, "S_OK", url, retr, maindomain);
}
else if ("2".equals(flag))
{
DiskFileItemFactory dfif = new DiskFileItemFactory();
dfif.setSizeThreshold(4 * 1024);
if (!(new File(request.getRealPath("/") + "uploadtemp")
.isDirectory()))
{
new File(request.getRealPath("/") + "uploadtemp").mkdir();
}
dfif.setRepository(new File(request.getRealPath("/")
+ "uploadtemp"));
ServletFileUpload sfu = new ServletFileUpload(dfif);


List fileList = null;
fileList = sfu.parseRequest(request);
if (fileList == null || fileList.size() == 0)
{
log.error("file is not find");
resMessage(out, "ERROR", "没有发现文件", "", maindomain);
return;
}
Iterator fileItr = fileList.iterator();


while (fileItr.hasNext())
{
long size = 0;
fileItem = (FileItem) fileItr.next();
if (fileItem.isFormField())
{
continue;
}
else
{
fileUploadItem = fileItem;
path = fileItem.getName();
size = fileItem.getSize();
if ("".equals(path) || size == 0)
{
resMessage(out, "ERROR", "没有发现文件", retr, maindomain);
return;
}
}
}
if ("".equals(path) || path == null)
{
resMessage(out, "ERROR", "没有发现文件", retr, maindomain);
return;
}
String t_name = path.substring(path.lastIndexOf("\\") + 1);
String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
// 拒绝接受规定文件格式之外的文件类型
int allowFlag = 0;
int allowedExtCount = allowtype.length;
for (; allowFlag < allowedExtCount; allowFlag++)
{
if (allowtype[allowFlag].equals(t_ext))
{
break;
}
}
if (allowFlag == allowedExtCount)
{
String message = "";
for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++)
{
message += "*." + allowtype[allowFlag] + " ";
}
resMessage(out, "ERROR", "文件格式不正确:" + message, retr,
maindomain);
return;
}


if (fileUploadItem.getSize() > MAX_SIZE)
{
resMessage(out, "ERROR", "最大上传"+upmaxsize+"M", retr, maindomain);
}


long now = System.currentTimeMillis();
String prefix = String.valueOf(now);


String newpath = PropertiesUtil.getProperty("img");
String[] confimg = newpath.split("/");
List<String> imgPath = new ArrayList<String>();
for (int i = 0; i < confimg.length; i++)
{
imgPath.add(confimg[i]);
}
int y, m, d;
Calendar cal = Calendar.getInstance();
y = cal.get(Calendar.YEAR);
m = cal.get(Calendar.MONTH);
d = cal.get(Calendar.DATE);
imgPath.add(String.valueOf(y));
imgPath.add(String.valueOf(m + 1));
imgPath.add(String.valueOf(d));
imgPath.add(String.valueOf(y) + "-" + String.valueOf(m + 1)
+ "-" + String.valueOf(d));
String webdir = request.getRealPath("/");
String resPath = "/";
String temp = "";
String newdir = "";
for (int j = 0; j < imgPath.size(); j++)
{
resPath = resPath + imgPath.get(j) + "/";
temp = temp + imgPath.get(j) + "/";
newdir = webdir + temp;
if (!(new File(newdir).isDirectory()))
{
new File(newdir).mkdir();
}
}
String imgpath = newdir + prefix + "." + t_ext;
fileUploadItem.write(new File(imgpath));
resPath = resPath + prefix + "." + t_ext;
resMessage(out, "S_OK", resPath, retr, maindomain);
}
else
{
resMessage(out, "S_OK", "文件格式错误", retr, maindomain);
}


}
catch (FileUploadException e)
{


log.error("user imager upload is error:" + e.getMessage());
resMessage(out, "ERROR", "文件格式错误", retr, maindomain);


}
catch (Exception e)
{
log.error("upload img is error:" ,e);
resMessage(out, "ERROR", "文件格式错误", retr, maindomain);


}
finally
{
if (out != null)
{
out.close();
}
if (file != null)
{
if (file.exists())
{
file.delete();
}
}
}
}


public static void resMessage(PrintWriter out, String code, String message,
String retr, String maindomain)


{
try
{
StringBuffer sbf = new StringBuffer();
sbf.append("{");
sbf.append("\"code\":").append("\"").append(code).append("\"")
.append(",");
sbf.append("\"var\":").append("\"").append(message).append("\"");
sbf.append("}");
out.println("<html><head>");
out.println("</head>");
out.println("<body>");
out.println("<script type='text/javascript'>");
if (!"".equals(maindomain))
{
out.println("document.domain='" + maindomain + "';");
}
if ("".equals(retr))
{
out.println("parent.callback(" + sbf.toString() + ");");
}
else
{
out.println("parent." + retr + "(" + sbf.toString() + ");");
}
out.println("</script>");
out.println("</body>");
out.println("</html>");
out.flush();
out.close();
}
finally
{
if (out != null)
{
out.close();
}
}


}


public static void imgproccess(String path, String x, String y,
String width, String height)
{
cutPic cut = new cutPic();
cut.cutpic(path, path, checkNum(x), checkNum(y), checkNum(width),
checkNum(height));
        
zipPic t1 = new zipPic();
t1.resizeImg(path, path, 96, 96);


}


public static int checkNum(String number)
{
try
{
String chk = "";
if (!"".equals(number))
{
java.util.regex.Pattern pattern = java.util.regex.Pattern
.compile("\\d+\\.\\d*");
java.util.regex.Matcher match = pattern.matcher(number);
if (match.matches() == true)
{
String[] nubmers = number.split("\\.");
chk = nubmers[0];
return Integer.parseInt(chk);
}


java.util.regex.Pattern patr = java.util.regex.Pattern
.compile("^[1-9]\\d*$");
java.util.regex.Matcher mach = patr.matcher(number);
if (mach.matches() == false)
{
return 0;
}
else
{
return Integer.parseInt(number);
}


}else
{
return 0;
}
}
catch (Exception e)
{
log.error("checkNum is error:",e);
return 0;
}


}
}

原创粉丝点击