1. 程式人生 > >頭像圖片的裁剪和上傳

頭像圖片的裁剪和上傳

頁面程式碼

    //index.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>圖片裁併剪上傳</title>
<link rel="stylesheet" href="css/index.css"/>
<script type="text/javascript"
src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js">
</script> </head> <body> <input type="file" id="src-img-input"/> <div> <div class="clip-container"></div> <div class="target-image-container"></div> </div> <script
type="text/javascript" src="js/index.js">
</script> </body> </html>

css樣式

    /* index.css CSS Document */
div.clip-container{width:200px; float:left;}
div.clip-box{
    width:100%;
    position:relative;
    overflow:hidden;
    font-size:0;
}
div.clip-box img{width:100%;}
div.selected-part
{ position:absolute; left:0; top:0; outline:rgba(0, 0, 0, 0.8) solid 10000px; cursor:move; } div.target-image-container{ width:200px; height:200px; float:left; margin-left:15px; } canvas{width:100%;}

javascript程式碼

    //index.js
    // JavaScript Document
$(function(){
    var srcInput=$("#src-img-input");
    var container=$(".clip-container");
    var clipContents="<div class='clip-box'>"+
    "<div class='selected-part'></div>"+
    "<img class='src-image'/></div>"+
    "<button class='clip-btn'>裁剪</button>";
    srcInput.change(function(){
        container.html(clipContents);
        var clipObj=$.clipObj();
        var reader=new FileReader();
        reader.readAsDataURL(this.files[0]);
        reader.onload=function(){
            clipObj.srcImage.src=this.result;
            setTimeout(function(){
                clipObj.init();
            },100);
            reader=null;
        };
    });
    $.clipObj=function(){
        var clipBox=container.find(".clip-box");
        clipBox.srcImage=clipBox.find(".src-image")[0];
        clipBox.size={
            width:0,
            height:0
        };
        //裁剪框
        clipBox.selectedBox=(function(){
            var selectedBox=clipBox.find(".selected-part");
            selectedBox.position={
                left:0,
                top:0
            };
            selectedBox.size=0;
            selectedBox.setSize=function(size){
                this.css({
                    width:size+"px",
                    height:size+"px"
                });
                this.size=size;
            };
            selectedBox.move=function(offset){
                var offsetX=offset.x, 
                offsetY=offset.y,
                posLeft=this.position.left,
                posTop=this.position.top,
                size=this.size,
                width=clipBox.size.width,
                height=clipBox.size.height,
                left,top;
                if(size+posLeft+offsetX>width){
                    left=width-size;
                }
                else{
                    left=posLeft+offsetX;
                }
                if(size+posTop+offsetY>height){
                    top=height-size;
                }
                else{
                    top=posTop+offsetY;
                }
                left=left<0?0:left;
                top=top<0?0:top;
                this.css({
                    left:left+"px",
                    top:top+"px"
                });
                this.position={
                    left:left,
                    top:top
                };
            };
            (function(){
                selectedBox.lastPoint=null;
                function getOffset(event){
                    var x,y;
                    x=event.clientX;
                    y=event.clientY;

                    if(!selectedBox.lastPoint){
                        selectedBox.lastPoint={
                            x:x,
                            y:y
                        };
                    }

                    var offset={
                        x:x-selectedBox.lastPoint.x,
                        y:y-selectedBox.lastPoint.y
                    };
                    selectedBox.lastPoint={
                        x:x,
                        y:y
                    };
                    return offset;
                }
                selectedBox.on("mousedown",function(event){
                    getOffset(event);
                });
                selectedBox.on("mousemove",function(event){
                    if(!selectedBox.lastPoint){
                        return;
                    }
                    var offset=getOffset(event);
                    selectedBox.move(offset);
                });
                selectedBox.on("mouseup",function(){
                    selectedBox.lastPoint=null;
                });
            })();
            return selectedBox;
        })();
        clipBox.init=function(){
            $(".target-image-container").html("");
            var width=this.width();
            var height=this.height();
            this.size={
                width:width,
                height:height
            };
            var size=width>height?height:width;
            this.selectedBox.setSize(size);
        };
        (function(){
            clipBox.clipImage=function(){
                var nw=this.srcImage.naturalWidth,
                nh=this.srcImage.naturalHeight,
                size=nw>nh?nh:nw;
                size=size>1000?1000:size;
                var canvas=$("<canvas class='target-image' width='"+size+"' height='"+size+" '></canvas>")[0],
                ctx=canvas.getContext("2d");
                var scale=nw/this.size.width,
                x=this.selectedBox.position.left*scale,
                y=this.selectedBox.position.top*scale,
                w=this.selectedBox.size*scale,
                h=this.selectedBox.size*scale;
                ctx.drawImage(this.srcImage,x,y,w,h,0,0,size,size);

                var uploadBtn=$("<button class='upload-btn'>上傳</button>");
                $(".target-image-container").html("").append(canvas).append(uploadBtn);
                uploadBtn.click(function(){
                    var src=canvas.toDataURL();
                    src=src.split(",")[1];
                    src=window.atob(src);

                    var ua=new Uint8Array(src.length);
                    for(var i=0;i<src.length;i++){
                        ua[i]=src.charCodeAt(i);
                    }
                    // canvas.toDataURL 返回的預設格式就是 image/png
                    var blob=new Blob([ua],{type:"image/png"});
                    var fd=new FormData();
                    fd.append("upload",blob);//fd.append("upload",blob,"檔名");
                    $.ajax({
                        url:"upload",
                        type:"POST",
                        data:fd,
                        processData: false,
                        contentType: false,
                        success:function(){
                            alert("上傳成功!");
                        }
                    });
                });
            };
            $(".clip-btn").on("click",function(){
                clipBox.clipImage();
            });
        })();

        return clipBox;
    };

});

Action程式碼

    public class PicClipUpload extends ActionSupport{
    private File upload;
    private String uploadContentType;
    private String uploadFileName;
    private String savedPath;
    public File getUpload() {
        return upload;
    }
    public void setUpload(File upload) {
        this.upload = upload;
    }
    public String getUploadContentType() {
        return uploadContentType;
    }
    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }
    public String getUploadFileName() {
        return uploadFileName;
    }
    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }
    public String getSavedPath() {
        return ServletActionContext.getServletContext().getRealPath(savedPath);
    }
    public void setSavedPath(String savedPath) {
        this.savedPath = savedPath;
    }
    public String execute(){
        try{
            InputStream in=new FileInputStream(upload);
            OutputStream out=new FileOutputStream(
                    new File(this.getSavedPath(),this.getUploadFileName()+".png"));
            byte[] buff=new byte[1024];
            int len=0;
            while(-1!=(len=in.read(buff))){
                out.write(buff, 0, len);
            }
            in.close();
            out.close();
        }
        catch(Exception r){

        }
        return "success";
    }
}

struts配置

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE struts PUBLIC
         "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
         "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>    
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />
    <include file="struts-default.xml"/>
    <package name="picupload" extends="struts-default">
        <action name="upload" class="com.util.PicClipUpload">
            <param name="savedPath">/uploadedfiles</param>
            <result name="success">success.jsp</result>
        </action>
    </package>
</struts>