java实现图片上传后裁剪,把白色背景变成透明图(电子印章)

应用场景:企业在白纸上盖上印章,然后软件实现透明的电子印章,在后续业务流程中使用!

A4纸-----------------------------------------处理后-------------------------------------->电子印章

--------> 

 

实现共分为3步

1. 图片上传后预览

<%@ page import="java.io.File" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.*" %>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>
<%@ page import="org.apache.commons.fileupload.FileItem" %>
<%@ page import="net.coobird.thumbnailator.Thumbnails" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<% if(request.getMethod().toUpperCase().equals("GET")){ //GET %>
<html>
<head>
    <title>上传图片</title>
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
    <script type="text/javascript" src="js/jquery.min.js"></script>
</head>
<body>
<form method="post" action="index.jsp" enctype="multipart/form-data">
    <input type="file" name="file" value="选择图片" />
    <input type="submit" value="下一步" />
</form>
</body>
</html>
<% }else{
    //POST file upload
    //commons-fileupload-1.3.2.jar
    //commons-io-2.5.jar
    //commons-logging
    //Thumbnails
    String uploadsdir = request.getSession().getServletContext().getRealPath("/uploads") + File.separator;
    String yyyyMM = (new SimpleDateFormat("yyyy-MM")).format(new Date());
    File file = new File(uploadsdir + yyyyMM);
    if (!file.exists()) {
        file.mkdirs();
    }
    if (file.canWrite()) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletContext servletContext = request.getSession().getServletContext();
        File repository = (File)servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(1024*1024*10);//最大10M
        try {
            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            if(iter.hasNext()) {
                FileItem item = (FileItem)iter.next();
                String fileName;
                String contentType;
                if (!item.isFormField()) {
                    fileName = item.getName();
                    contentType = item.getContentType();
                    if (contentType != null && "image/jpeg,image/gif,image/png,image/bmp,image/x-png,image/pjpeg".indexOf(contentType) == -1) {
                        response.sendRedirect("index.jsp?error=1");//不是图片类型
                    } else {
                        String last = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                        String filename = UUID.randomUUID().toString().toLowerCase().replaceAll("-","") + last;
                        File savedFile = new File(file, filename);
                        item.write(savedFile);
                        //压缩 width 1000
                        Thumbnails.of(savedFile.getAbsolutePath()).width(1000)
                                .toFile(savedFile.getAbsoluteFile());
                        response.sendRedirect("corp.jsp?u=uploads/" + yyyyMM + "/" + filename);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("index.jsp?error=5");//上传异常
        }
    } else {
        response.sendRedirect("index.jsp?error=2");//文件夹不可写
    }

} %>

2.预览后进行裁剪

<%@ page import="java.io.File" %>
<%@ page import="net.coobird.thumbnailator.Thumbnails" %>
<%@ page import="java.io.InputStream" %>
<%@ page import="java.io.FileInputStream" %>
<%@ page import="java.awt.image.BufferedImage" %>
<%@ page import="javax.imageio.ImageIO" %>
<%@ page import="java.awt.*" %>
<%@ page import="javax.swing.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<% if(request.getMethod().toUpperCase().equals("GET")){ //GET %>
<html>
<head>
    <title>图片裁剪</title>
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
    <script src="js/jquery.min.js"></script>
    <script src="js/jquery.Jcrop.min.js"></script>
    <script type="text/javascript">

        jQuery(function($){

            var jcrop_api;

            $('#target').Jcrop({
                onChange:   showCoords,
                onSelect:   showCoords,
                onRelease:  clearCoords
            },function(){
                jcrop_api = this;
            });

            $('#coords').on('change','input',function(e){
                var x1 = $('#x1').val(),
                    x2 = $('#x2').val(),
                    y1 = $('#y1').val(),
                    y2 = $('#y2').val();
                jcrop_api.setSelect([x1,y1,x2,y2]);
            });

        });

        // Simple event handler, called from onChange and onSelect
        // event handlers, as per the Jcrop invocation above
        function showCoords(c)
        {
            $('#x1').val(c.x);
            $('#y1').val(c.y);
            $('#x2').val(c.x2);
            $('#y2').val(c.y2);
            $('#w').val(c.w);
            $('#h').val(c.h);
        };

        function clearCoords()
        {
            $('#coords input').val('');
        };

    </script>
    <link rel="stylesheet" href="css/jquery.Jcrop.min.css" type="text/css" />
    <style type="text/css">
        *{ margin:0px; padding:0px;}
    </style>
</head>
<body>
<!-- This is the image we're attaching Jcrop to -->
<img src="<%=request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/" %><%=request.getParameter("u") %>" id="target" alt="上传图"/>
<!-- This is the form that our event handler fills -->
<form id="coords"
      class="coords"
      onsubmit="return false;"
      method="post"
      action="corp.jsp">
    <input type="hidden" name="u" value="<%=request.getParameter("u") %>" />
    <div class="inline-labels" style="display: none;">
        <label>X1 <input type="text" size="4" id="x1" name="x1" /></label>
        <label>Y1 <input type="text" size="4" id="y1" name="y1" /></label>
        <label>X2 <input type="text" size="4" id="x2" name="x2" /></label>
        <label>Y2 <input type="text" size="4" id="y2" name="y2" /></label>
        <label>W <input type="text" size="4" id="w" name="w" /></label>
        <label>H <input type="text" size="4" id="h" name="h" /></label>
    </div>
</form>

<input type="button" style="position:fixed;right: 10px; top: 10px; z-index: 999; padding: 10px" onclick='$("#coords")[0].submit();' value="下一步" />
</body>
</html>
<% }else{ //POST file corp
    String u = request.getParameter("u");
    String x1 = request.getParameter("x1");
    String x2 = request.getParameter("x2");
    String y1 = request.getParameter("y1");
    String y2 = request.getParameter("y2");
    String w = request.getParameter("w");
    String h = request.getParameter("h");
    if(u!=null&&w!=null&&h!=null&&x1!=null&&x2!=null) {
        int int_x1 = Integer.parseInt(x1);
        int int_y1 = Integer.parseInt(y1);
        int int_w = Integer.parseInt(w);
        int int_h = Integer.parseInt(h);
        String uploadsdir = request.getSession().getServletContext().getRealPath("/");
        String filepath = uploadsdir + u;
        //crop to png
        File inputfile = new File(filepath);
        File outfile = new File(filepath.substring(0,filepath.lastIndexOf("."))+".png");
        Thumbnails.of(inputfile).sourceRegion(int_x1, int_y1, int_w, int_h)
                .size(int_w, int_h).outputFormat("png") .toFile(outfile);
        //to apla
        transApla(outfile);
        //png file
        u=u.substring(0,u.lastIndexOf("."))+".png";
        response.sendRedirect("show.jsp?u=" + u);
    }
} %>
<%!
//去掉图片背景
public void transApla(File file){
    InputStream is=null;
    try {
        is = new FileInputStream(file);
        // 如果是MultipartFile类型,那么自身也有转换成流的方法:is = file.getInputStream();
        BufferedImage bi = ImageIO.read(is);
        Image image = (Image) bi;
        ImageIcon imageIcon = new ImageIcon(image);
        BufferedImage bufferedImage = new BufferedImage(imageIcon.getIconWidth(), imageIcon.getIconHeight(),
                BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
        g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver());
        int alpha = 0;
        for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage.getHeight(); j1++) {
            for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage.getWidth(); j2++) {
                int rgb = bufferedImage.getRGB(j2, j1);

                int R = (rgb & 0xff0000) >> 16;
                int G = (rgb & 0xff00) >> 8;
                int B = (rgb & 0xff);
                if (((255 - R) < 30) && ((255 - G) < 30) && ((255 - B) < 30)) {
                    rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff);
                }

                bufferedImage.setRGB(j2, j1, rgb);

            }
        }

        g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());
        ImageIO.write(bufferedImage, "png", file);// 直接输出文件
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if(is!=null){
           try{
            is.close();
           }catch (Exception e){}
        }
    }
}
%>

3.裁剪图片进行png转换,然后白色背景变透明图

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>预览</title>
</head>
<body>
    <img src="<%=request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/" %><%=request.getParameter("u") %>" width="250" />
    <input type="submit" value="保存" />
</body>
</html>

百度网盘:https://pan.baidu.com/s/1u-QzDZQWvnsODPfm7eaE9g

 

 

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qilin001cs/article/details/80696310
个人分类: java
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭