1. 程式人生 > >vue圖片上傳元件,包括base64、二進位制上傳及圖片旋轉

vue圖片上傳元件,包括base64、二進位制上傳及圖片旋轉

       最近做的vue專案中好多涉及到圖片上傳的,為了方便開發就進行了相關總結。因為公司有好多專案,並且使用的是不同後臺語言,有的需要通過base64字串傳遞,有的需要轉換成二進位制資料流傳遞,有的可以直接使用from表單進行提交。後來有涉及到ios上拍照圖片會旋轉的問題,也一併進行了封裝。好了廢話不多說直接上程式碼。

<!DOCTYPE html><html>
<head>    <meta charset="utf-8" />    <title>圖片上傳</title></head>
<body>    <
form id="upImg">        <input type='file' accept="image/*" name="avatar" placeholder="" id="img" />    </form>    <img src="" alt="" id='preImg'>    <!-- 需要引入exif.js外掛 -->    <script src='./exif.js'></script>    <script>        var domImg = document.querySelector
('#img')        //新增DOM事件        domImg.onchange = function upLoadImg(e, type) {            let files = e.target.files || e.dataTransfer.files;            if (!files.length) return;            if (files[0].type.indexOf("image") < 0) {                alert("上傳了非圖片");                return;            }            if
(files[0].size > 5 * 1000000) {                alert("上傳檔案過大");                return;            }            // 圖片壓縮成base64            compress(e.target, (base64, imgFile) => {                var upImage = new FormData();                upImage.append("fileName", imgFile.name);                var blob = convertImgDataToBlob(base64);                upImage.append("file", blob);
                //上傳圖片介面                this.$http({                    method: "POST",                    url: interfaced.aliYun,                    body: upImage                }).then(                    res => {                        console.log(res);                    },                    err => {                        console.log(err);                    }                );            });            //將base64轉換成二進位制函式            function convertImgDataToBlob(base64Data) {                var format = "image/jpeg";                var base64 = base64Data;                var code = window.atob(base64.split(",")[1]);                var aBuffer = new window.ArrayBuffer(code.length);                var uBuffer = new window.Uint8Array(aBuffer);                for (var i = 0; i < code.length; i++) {                    uBuffer[i] = code.charCodeAt(i) & 0xff;                }                var blob = null;                try {                    blob = new Blob([uBuffer], {                        type: format                    });                } catch (e) {                    window.BlobBuilder =                        window.BlobBuilder ||                        window.WebKitBlobBuilder ||                        window.MozBlobBuilder ||                        window.MSBlobBuilder;                    if (e.name == "TypeError" && window.BlobBuilder) {                        var bb = new window.BlobBuilder();                        bb.append(uBuffer.buffer);                        blob = bb.getBlob("image/jpeg");                    } else if (e.name == "InvalidStateError") {                        blob = new Blob([aBuffer], {                            type: format                        });                    } else {}                }                return blob;            }            //將圖片壓縮成base64函式            function compress(event, callback) {                //圖片方向角                var Orientation = null;                 var file = event.files[0];                var reader = new FileReader();
                //獲取照片方向角屬性,使用者旋轉控制                 EXIF.getData(file, function() {                     EXIF.getAllTags(this);                     Orientation = EXIF.getTag(this, 'Orientation');                 });
                reader.onload = function (e) {                    var image =document.createElement("img");                    image.onload = function () {                        //使用canvas重繪圖片                        var canvas = document.createElement("canvas");                        var x = this.width;                        var y = this.height;                        this.width = 375 * 2;                        this.height = this.width / x * y;                        var width = this.width;                        var height = this.height;                        canvas.width = this.width;                        canvas.height = this.height;                        var context = canvas.getContext("2d");                        context.clearRect(0, 0, width, height);                        //對圖片進行旋轉                        switch (Orientation) {                            case 3:                                context.rotate(180 * Math.PI / 180);                                context.drawImage(this, -this.width, -this.height, this.width, this.height);                                break;                            case 6:                                context.rotate(90 * Math.PI / 180);                                context.drawImage(this, 0, -this.width, this.height, this.width);                                break;                            case 8:                                context.rotate(270 * Math.PI / 180);                                context.drawImage(this, -this.height, 0, this.height, this.width);                                break;                            case 2:                                context.translate(this.width, 0);                                context.scale(-1, 1);                                context.drawImage(this, 0, 0, this.width, this.height);                                break;                            case 4:                                context.translate(this.width, 0);                                context.scale(-1, 1);                                context.rotate(180 * Math.PI / 180);                                context.drawImage(this, -this.width, -this.height, this.width, this.height);                                break;                            case 5:                                context.translate(this.width, 0);                                context.scale(-1, 1);                                context.rotate(90 * Math.PI / 180);                                context.drawImage(this, 0, -this.width, this.height, this.width);                                break;                            case 7:                                context.translate(this.width, 0);                                context.scale(-1, 1);                                context.rotate(270 * Math.PI / 180);                                context.drawImage(this, -this.height, 0, this.height, this.width);                                break;                            default:                                context.drawImage(this, 0, 0, this.width,this.height);                        }
                        var quality = 0.9; //壓縮程度                        var data;                        var result;                        var length;                        //控制圖片上傳的大小,注意若圖片過大 ajax上傳的時候會出現引數為null的錯誤                        //這裡如果圖片過大會將圖片壓縮程度放大                        do {                            data = canvas.toDataURL("image/jpeg", quality);                            length = data.length;                            result = (length / 4 * 3 + 1023) / 1024; //計算壓縮後圖片的大小                            quality -= 0.05;                        } while (result > 450);                        //data:base64                        document.querySelector('#preImg').src = data                        callback(data, event.files[0]);                    };                    image.src = e.target.result;                };                reader.readAsDataURL(file);            }        }    </script></body>
</html>