| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
jopen
10年前发布

imgareaselect+java实现图片裁剪保存

1、需求包:

jquery.imgareaselect.js

jquery.imgareaselect.pack.js

jquery-1.6.1.min.js

ajaxfileupload-min.js

json-lib-2.3-jdk15.jar

commons-fileupload-1.2.2.jar

 

2、前端页面

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">        <html xmlns="http://www.w3.org/1999/xhtml">        <head>        <title></title>        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />        <link href="css/imgareaselect-default.css" rel="stylesheet" type="text/css" />        <script type="text/javascript" src="js/jquery-1.6.1.min.js"></script>        <script type="text/javascript" src="js/ajaxfileupload-min.js"></script>        <script type="text/javascript" src="js/jquery.imgareaselect.min.js"></script>        <script type="text/javascript" src="js/jquery.imgareaselect.pack.js"></script>        <script type="text/javascript" src="js/upload.js"></script>        </head>        <body>            <input type="hidden" name="x1" value="0" />            <input type="hidden" name="y1" value="0" />            <input type="hidden" name="x2" value="100" />            <input type="hidden" name="y2" value="100" />             <input id="fileToUpload" name="fileToUpload" type="file" onchange="uploadImage();"/>            <div id="facediv" style="display:none;z-index:100;">                <img id="face" />            </div>        </body>        </html>  
    function uploadImage() {            $.ajaxFileUpload( {                url : 'photo',// 需要链接到服务器地址                fileElementId : 'fileToUpload',// 文件选择框的id属性                dataType : 'json',// 服务器返回的格式,可以是json                data : {"operation":1},                success : function(data) {                    if (data['result'] == 1) {                        $("#facediv").css({"display":"block"});                        $("#face").attr("src",data['path']);                                                $('<div><img src="' + data['path'] + '" style="position: relative;" /><div>')                            .css({                                float: 'left',                                position: 'relative',                                overflow: 'hidden',                                width: '100px',                                height: '100px'                            }).insertAfter($('#face'));                                                $('<button id="btnSubmit">提交</button>')                        .click(function (){                            cutImage(data['path']);                        }).insertAfter($('#facediv'));                                                $('#face').imgAreaSelect({                            maxWidth: 100, maxHeight: 100,                            minWidth: 63, minHeight:63,                            x1:0,y1:0,x2:100,y2:100,                            aspectRatio: '1:1',                             onSelectChange: function (img, selection) {                                var scaleX = 100 / (selection.width || 1);                                var scaleY = 100 / (selection.height || 1);                                                              $('#face + div > img').css({                                    width: Math.round(scaleX * 400) + 'px',                                    height: Math.round(scaleY * 300) + 'px',                                    marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',                                    marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'                                });                            },                            onSelectEnd: function (img, selection) {                                $('input[name="x1"]').val(selection.x1);                                $('input[name="y1"]').val(selection.y1);                                $('input[name="x2"]').val(selection.x2);                                $('input[name="y2"]').val(selection.y2);                            }                         });                    }                },                error : function(data) {                }            });        }                function cutImage(path) {            $.ajax( {                type : "POST",                url:"photo",                dateType:"json",                data:{"operation":2,"x1":$('input[name="x1"]').val(),                "x2":$('input[name="x2"]').val(),                "y1":$('input[name="y1"]').val(),                "y2":$('input[name="y2"]').val(),                "path":path},                success : function(data) {                    top.location.href="photo_view.vm?path="+data["path"];                },                error:function(data) {                                    }            });        }  
3、后台处理:
    public class PhotoServlet extends HttpServlet {                    private static final long serialVersionUID = 5653610348191435218L;                    @Override            protected void doPost(HttpServletRequest request, HttpServletResponse resp)                    throws ServletException, IOException {                                String requestType = request.getContentType();                if (requestType != null && requestType.indexOf("multipart/form-data") != -1) {                    FileItemFactory factory = new DiskFileItemFactory();                    ServletFileUpload upload = new ServletFileUpload(factory);                    List items;                    try {                        items = upload.parseRequest(request);                        Iterator iter = items.iterator();                        String webRoot = request.getSession().getServletContext()                        .getRealPath("/");                        while (iter.hasNext()) {                            FileItem item = (FileItem) iter.next();                            if (!item.isFormField()) {                                String suffix = item.getName().substring(item.getName().lastIndexOf("."));                                String name = String.valueOf(System.currentTimeMillis());                                StringBuffer sourcePath = new StringBuffer();                                sourcePath.append(webRoot);                                sourcePath.append(File.separator);                                sourcePath.append("tmp");                                sourcePath.append(File.separator);                                sourcePath.append(name);                                sourcePath.append("_source");                                sourcePath.append(suffix);                                                                File imageFile= new File(sourcePath.toString());                                if (!imageFile.getParentFile().exists()) {                                    imageFile.getParentFile().mkdirs();                                }                                item.write(imageFile);                                                                          JSONObject result = new JSONObject();                                result.put("result", 1);                                result.put("path", "http://localhost:8080/testxml/tmp/" + imageFile.getName());                                                                this.responseJSON(resp, result.toString());                                break;                            }                        }                    } catch (FileUploadException e) {                        // TODO Auto-generated catch block                        e.printStackTrace();                    } catch (Exception e) {                        // TODO Auto-generated catch block                        e.printStackTrace();                    }                } else {                    Integer x1 = Integer.parseInt(request.getParameter("x1"));                    Integer y1 = Integer.parseInt(request.getParameter("y1"));                    Integer x2 = Integer.parseInt(request.getParameter("x2"));                    Integer y2 = Integer.parseInt(request.getParameter("y2"));                    String path = request.getParameter("path");                    String fileName = path.substring(path.lastIndexOf("/")+1);                    String suffix = fileName.substring(fileName.lastIndexOf("."));                                        String webRoot = request.getSession().getServletContext().getRealPath("/");                                        StringBuffer sourcePath = new StringBuffer();                    sourcePath.append(webRoot);                    sourcePath.append(File.separator);                    sourcePath.append("tmp");                    sourcePath.append(File.separator);                    sourcePath.append(fileName);                                        StringBuffer targetPath = new StringBuffer();                    targetPath.append(webRoot);                    targetPath.append(File.separator);                    targetPath.append("tmp");                    targetPath.append(File.separator);                    targetPath.append(fileName.substring(0, fileName.lastIndexOf("_")));                    targetPath.append(suffix);                                        cutImage(suffix.substring(1), sourcePath.toString(), targetPath.toString(),                            x1, y1, x2, y2);                                        new File(sourcePath.toString()).delete();                                        JSONObject result = new JSONObject();                    result.put("result", 1);                    result.put("path", "http://localhost:8080/testxml/tmp/" + fileName.substring(0, fileName.lastIndexOf("_")) + suffix);                    resp.setContentType("application/json");                    this.responseJSON(resp, result.toString());                }            }            protected void responseJSON(HttpServletResponse response, String jsonStr) {                response.setCharacterEncoding("utf-8");                PrintWriter writer;                try {                    writer = response.getWriter();                    writer.write(jsonStr);                    writer.flush();                } catch (IOException e) {                }            }            public static void cutImage(String suffix, String sourcePath, String targetPath,                    int x1, int y1, int x2, int y2) {                try {                    Image img;                    ImageFilter cropFilter;                    File sourceImgFile = new File(sourcePath);                    BufferedImage bi = ImageIO.read(sourceImgFile);                    int srcWidth = bi.getWidth();                    int srcHeight = bi.getHeight();                    int destWidth = x2 - x1;                    int destHeight = y2 - y1;                    if (srcWidth >= destWidth && srcHeight >= destHeight) {                        Image image = bi.getScaledInstance(srcWidth, srcHeight,                                Image.SCALE_DEFAULT);                        cropFilter = new CropImageFilter(x1, y1, destWidth, destHeight);                        img = Toolkit.getDefaultToolkit().createImage(                                new FilteredImageSource(image.getSource(), cropFilter));                        BufferedImage tag = new BufferedImage(destWidth, destHeight,                                BufferedImage.TYPE_INT_RGB);                        Graphics g = tag.getGraphics();                        g.drawImage(img, 0, 0, null);                        g.dispose();                        ImageIO.write(tag, suffix, new File(targetPath));                                   }                } catch (Exception e) {                    e.printStackTrace();                }            }                }  

 本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1410338908445.html
图片裁剪 图形/图像处理