在线文档教程

自定义上传生成图片及上传图片案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>预览</title>
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <script src="/public/js/jquery-3.4.1.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="/public/js/html2canvas.js"></script>
    <style type="text/css" media="all">
        @font-face{
            font-family: "myfont";
            /*src: url("//cdn.mys360.com.mixinnet.cn/2022-01-30_61f61387e38b4.woff");*/
            src: url("//cdn.mys360.com.mixinnet.cn/2022-01-30_61f664165cdd1.woff");
        }
        body{background-color:#000}
        .main{width:600px;margin:auto;position:relative;background:#f4f4f4;border:5px solid #d6d6d6;margin-top:5px}
        .mysdiv{position:relative}
        .yinying{position:absolute;right:0;bottom:-54px}
        .mp{padding:30px}
        .mp1{padding:5px;background-color:#d6d6d6}
        img{width:100%}
        .xia{display:flex}
        .xia img{width:calc(50% - 10px);margin:5px;float:left}
        .mpa{display:flex;border:5px solid #d6d6d6}
        .btn {background-color: #FF5722;padding: 10px 60px;text-decoration: none;color: white;margin: 10px;}
        .gangbi {
            position: absolute;
            width: 200px;
            bottom: 60px;
            right: 10px;
        }
        .input {
            border: unset;
            background-color: rgb(255 255 255 / 0%);
            position: absolute;
            left: 80px;
            top: 90px;
            width: 339px;
            text-align: center;
            font-size: 30px;
            color: #535455;
            font-weight: bold;
            font-family:myfont;
        }
    </style>
</head>
<body style="margin:0px;padding: 0px">
    {if get('id',3)==3}
    <div class="main">
        <div class="mysdiv">
            <div class="mp">
                <input type="file" onchange="inputFileBase64('inputFileImg','showimg');" id="inputFileImg" style="display: none;">
                <a href="javascript:;" onclick="get_a('inputFileImg')" class="mpa">
                    <img id="showimg" src="http://cdn.mys360.com.mixinnet.cn/2022-01-30_61f6549872fa5.png">
                </a>
            </div>
            <img src="http://cdn.mys360.com.mixinnet.cn/2022-01-30_61f61ff03b26a.png" class="yinying">
        </div>
        <div class="mysdiv xia">
            <div class="mp1">
                <input type="file" onchange="inputFileBase64('inputFileImg1','showimg1');" id="inputFileImg1" style="display: none;">
                <a href="javascript:;" onclick="get_a('inputFileImg1')">
                    <img id="showimg1" src="http://cdn.mys360.com.mixinnet.cn/2022-01-30_61f6549872fa5.png">
                </a>
                <input type="file" onchange="inputFileBase64('inputFileImg2','showimg2');" id="inputFileImg2" style="display: none;">
                <a href="javascript:;" onclick="get_a('inputFileImg2')">
                    <img id="showimg2" src="http://cdn.mys360.com.mixinnet.cn/2022-01-30_61f6549872fa5.png">
                </a>
            </div>
        </div>
    </div>
    {/if}
    {if get('id',3)==2}
    <div class="main" style="width: 500px;">
        <div class="mysdiv">
            <div class="mp">
                <input type="file" onchange="inputFileBase64('inputFileImg','showimg');" id="inputFileImg" style="display: none;">
                <a href="javascript:;" onclick="get_a('inputFileImg')" class="mpa">
                    <img id="showimg" src="http://cdn.mys360.com.mixinnet.cn/2022-01-30_61f6549872fa5.png">
                </a>
            </div>
            <img src="http://cdn.mys360.com.mixinnet.cn/2022-01-30_61f61ff03b26a.png" class="yinying">
        </div>
        <div class="mysdiv">
            <div class="mp1">
                <input type="file" onchange="inputFileBase64('inputFileImg1','showimg1');" id="inputFileImg1" style="display: none;">
                <a href="javascript:;" onclick="get_a('inputFileImg1')">
                    <img id="showimg1" src="http://cdn.mys360.com.mixinnet.cn/2022-01-30_61f6549872fa5.png">
                </a>
            </div>
        </div>
    </div>
    {/if}
    {if get('id',3)==1}
    <div class="main" style="width: 500px;border: unset;">
        <div class="mysdiv">
            <div class="mp">
                <input type="text" value="" class="input">
                <input type="file" onchange="inputFileBase64('inputFileImg','showimg');" id="inputFileImg" style="display: none;">
                <a href="javascript:;" onclick="get_a('inputFileImg')" class="mpa">
                    <img id="showimg" src="http://cdn.mys360.com.mixinnet.cn/2022-01-30_61f6609ede354.jpg">
                </a>
            </div>
            <img src="http://cdn.mys360.com.mixinnet.cn/2022-01-30_61f66160f3b01.png" class="gangbi">
            <img src="http://cdn.mys360.com.mixinnet.cn/2022-01-30_61f61ff03b26a.png" class="yinying" style="bottom: -34px;">
        </div>
 
    </div>
    {/if}
    <div align="center" style="margin-top: 50px;">
        <a href="s-kan.html?id=3" class="btn">
            3张
        </a>
        <a href="s-kan.html?id=2" class="btn">
            2张
        </a>
        <a href="s-kan.html?id=1" class="btn">
            1张
        </a>
        <a href="javascript:;" onclick="main()" class="btn">
            生成图片
        </a>
        <a href="javascript:;" onclick="mainup()" class="btn">
            生成外联
        </a>
    </div>
    <div align="center" style="margin-top: 50px;">
        <input type="text" value="" class="geturl" style="width: 500px;height: 30px;">
    </div>
</body>
<script> 
function get_a(id) {
  document.getElementById(id).click();
}
//当input发生改变时调用
function inputFileBase64(id, imgid) {
  var call = upload_file(id, [".png", ".jpg"], imgid);
}
/**
 * 返回input type[file]框 属性
 * 返回格式{base64,width,height}
 * @param input_img_id  input框id
 * @param format        支持格式json对象形势['.png','.jpg']
 */
function upload_file(input_img_id, format, imgid) {
  if (document.getElementById(input_img_id).value != "") {
    var fileExt = document
      .getElementById(input_img_id)
      .value.substr(
        document.getElementById(input_img_id).value.lastIndexOf(".")
      )
      .toLowerCase(); //获得文件后缀名
    var data = { code: false, message: "转码失败,不支持该后缀名" };
    for (var i = 0; i < format.length; i++) {
      //循环判断是否合法
      if (fileExt == format[i]) {
        data = { code: true };
      }
    }
    if (!data["code"]) {
      document.getElementById(input_img_id).value = "";
      return data;
    }
    var file = document.getElementById(input_img_id);
    var data = createReader(file.files[0], imgid);
  }
}
/**
 * 上一个方法调用
 * 返回图片信息 {code,base_64,width,height}
 * @param file
 */
function createReader(file, imgid) {
  var reader = new FileReader();
  reader.onload = function (evt) {
    var image = new Image();
    image.onload = function () {
      data = {
        code: true,
        base_64: evt.target.result, //base64格式
        width: this.width, //图片宽度
        height: this.height, //图片高度
        message: "转码成功"
      };
      //写自己的代码
      // document.getElementsByTagName('img')[0].src=data.base_64;
      document.getElementById(imgid).src = data.base_64;
    };
    image.src = evt.target.result;
  };
  reader.readAsDataURL(file);
}
// 生成图片
function main(){
    html2canvas($(".main")[0], {
        backgroundColor: "transparent",
        useCORS: true,
        background: "#ffffff", // 一定要添加背景颜色,否则出来的图片,背景全部都是透明的
        dpi: 300, // 处理模糊问题
    }).then(function(canvas) {
        imgUri = canvas.toDataURL();
        //  console.log(imgUri); //生成base64的编码图片
        $(".main").css("border","unset");
        $(".main").html('<img src="' + imgUri + '" style="display: block;">');
    })
}
// 生成并且上传图片
function mainup(){
    html2canvas($(".main")[0], {
        backgroundColor: "transparent",
        useCORS: true,
        background: "#ffffff", // 一定要添加背景颜色,否则出来的图片,背景全部都是透明的
        dpi: 300, // 处理模糊问题
    }).then(function(canvas) {
        base64 = canvas.toDataURL();
        // 压缩
        dealImage(base64, 700, useImg);
        function useImg(base64) {
            str= base64;
            ajaxup(convertBase64UrlToBlobpic(str))
        }
    })
}
/**  
 * 将以base64的图片url数据转换为Blob  
 * @param urlData  
 * 用url方式表示的base64图片数据  
 */  
function convertBase64UrlToBlobpic(urlData){  
    var bytes=window.atob(urlData.split(',')[1]);        //去掉url的头,并转换为byte  
    //处理异常,将ascii码小于0的转换为大于0  
    var ab = new ArrayBuffer(bytes.length);  
    var ia = new Uint8Array(ab);  
    for (var i = 0; i < bytes.length; i++) {  
        ia[i] = bytes.charCodeAt(i);  
    }  
    return new Blob( [ab] , {type : 'image/jpg'});  
} 
// ajax上传
function ajaxup(file){  
    var formFile = new FormData();
    formFile.append("file",file,"图片.jpg"); 
    var data = formFile;
    $.ajax({  
        url : "/admin-up-up.html",
        type : "POST",  
        data : data,  
        dataType:"text",  
        processData : false,
        contentType : false, 
        success:function(res){ 
            obj = JSON.parse(res);
            $('.geturl').val(obj.path)
        //     alert(obj.path);
        }
    }) 
} 
//压缩方法
function dealImage(base64, w, callback) {
  var newImage = new Image();
  var quality = 0.6; //压缩系数0-1之间
  newImage.src = base64;
  newImage.setAttribute("crossOrigin", "Anonymous"); //url为外域时需要
  var imgWidth, imgHeight;
  newImage.onload = function () {
    imgWidth = this.width;
    imgHeight = this.height;
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    if (Math.max(imgWidth, imgHeight) > w) {
      if (imgWidth > imgHeight) {
        canvas.width = w;
        canvas.height = (w * imgHeight) / imgWidth;
      } else {
        canvas.height = w;
        canvas.width = (w * imgWidth) / imgHeight;
      }
    } else {
      canvas.width = imgWidth;
      canvas.height = imgHeight;
      quality = 0.6;
    }
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
    var base64 = canvas.toDataURL("image/jpeg", quality); //压缩语句
    callback(base64); //必须通过回调函数返回,否则无法及时拿到该值
  };
}

</script>
</html>