移動端預覽壓縮上傳圖片

移動端預覽壓縮上傳圖片

推薦一個使用成熟的解決方案:https://github.com/think2011/...html

文章已同步個人github筆記 https://github.com/ymblog/blog,歡迎你們加star~~,加star後人生更加美好……

原理介紹

移動端圖片上傳,經過FileReader生成base64圖片資源進行預覽,經過canvas進行圖片的壓縮,將圖片url轉換成Blob對象上傳。ios

實現方案

  • 初始頁面佈局
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>圖片上傳</title>
</head>
    <style>    
        img{
            display:block;
            width:200px;
        }
    </style>
<body>
    <input type="file" accept="image/*" multiple id="upload" onchange="previewImg(this,'preview-img')">
    <img src="" alt="" id="preview-img">
</body>
</html>
  • 移動端file有兼容上的問題,解決方案:
<input type="file" id="upload" class="upload" accept="image/*" multiple />
  • 使用FileReader進行圖片預覽
/**
 * [previewImg 預覽圖片]
 * @param  {[type]} input [文件上傳input]
 * @param  {[type]} obj   [description]
 * @return {[type]}       [description]
 */
function previewImg(input,imgObj) {
    var maxsize = 300 * 1024;//超過300k進行壓縮
    //是否支持
    if (typeof FileReader === 'undefined') {
        alert("抱歉,你的瀏覽器不支持 FileReader,請使用現代瀏覽器操做!");
        input.setAttribute('disabled','disabled');
    }
    if(input.files && input.files[0]){
        var file = input.files[0],
            reader = new FileReader();
        if(!/image\/\w+/.test(file.type)) {
            alert('不是有效的圖片文件!');
            return;
        }
        reader.onload = function(e){
            var result = this.result;//獲取到base64的圖片
            //大於300k圖片進行壓縮
            if(result.length >= maxsize){
                var img = new Image();
                img.src = result;
                img.onload = function(){
                    compressSrc = compress(img,0.8,100);
                    $(imgObj).setAttribute('src',compressSrc);
                    //ajax dataURLtoBlob(compressSrc);
                }
            }else{
                $(imgObj).setAttribute('src',result);
                //ajax dataURLtoBlob(result);
            }
        }
    }
}
  • 使用canvas圖片壓縮,不過在ios中圖片大於2000000像素就沒法使用canvas壓縮,就須要瓦片繪製。
/**
 * [compress 壓縮圖片]
 * @param  {[dom]} sourceImg [圖片dom]
 * @param  {[int]0-1} scale     [縮小的尺寸比例]
 * @param  {[int]0-100} quality   [清晰質量]
 * @return {[object]}           [圖片源]
 */
function compress(sourceImg,scale,quality){
    var area = sourceImg.width * sourceImg.height,//源圖片的總大小
        height = sourceImg.height * scale,
        width = sourceImg.width * scale,
        compressCvs = document.createElement('canvas');//壓縮的圖片畫布
    //壓縮的圖片配置寬高
    compressCvs.width = width;
    compressCvs.height = height;
    var compressCtx = compressCvs.getContext("2d");
    //解決ios 圖片大於2000000像素沒法用drawImage的bug
    if(area > 2000000 && navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)){
        //瓦片繪製
        var smallCvs = document.createElement("canvas"),
            smallCtx = smallCvs.getContext("2d"),
            count = Math.ceil(area / 1000000),//分割的數量
            cvsWidth = width / count,//每一個小canvas的寬度
            picWidth = sourceImg.width / count;//分割成小圖片的寬度
        smallCvs.height = compressCvs.height;
        smallCvs.width =  width / count;
        //拼湊成大的canvas
        for(var i = 0;i < count;i ++){
            smallCtx.drawImage(sourceImg,i*picWidth,0,picWidth,sourceImg.height,0,0,cvsWidth,height);
            compressCtx.drawImage(smallCvs,i*cvsWidth,0,cvsWidth,height);
        }
    }else{
        compressCtx.drawImage(sourceImg,0,0,sourceImg.width,sourceImg.height,0,0,width,height);
    }
    //將canvas轉換成base64
    return compressCvs.toDataURL('image/jpeg',quality/100);
}
function $(id){
    return document.getElementById(id);
}
  • 將圖片url轉換爲blob對象
/**
 * [dataURLtoBlob 將base64轉換爲blob對象]
 * @param  {[type]} dataurl [圖片源base64]
 * @return {[object]}         [圖片源blob對象]
 */
function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {type:mime});
}

使用說明

這個只是一個移動端預覽壓縮上傳圖片實現的demo,會有一些兼容性和bug問題,你們能夠本身修改和擴展git

結束,撒花~~~github

文章已同步個人github筆記 https://github.com/ymblog/blog,歡迎你們加star~~,加star後人生更加美好……
相關文章
相關標籤/搜索