上传图片,裁剪图片,图片变圆形

裁剪图片及上传图片:

<!doctype html>
<html lang="zh-CN" id="index">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="format-detection" content="telephone=no, email=no" />
<meta name="keywords" content="">
<meta name="description" content="">
<title>图片裁剪</title>
<style>
body {
    margin: 0;
    text-align: center;
}
#clipArea {
    margin: 20px;
    height: 300px;
}
#file,
#clipBtn {
    margin: 20px;
}
#view {
    margin: 0 auto;
    width: 200px;
    height: 200px;
}
</style>
</head>
<body ontouchstart="">
<div id="clipArea"></div>
<button id="fileBtn" class="btn btn-default" onclick="ClickFile()" >选择宝宝图片</button>
<input type="file" id="file" accept="image/*" style="display: none;" >
<button id="clipBtn" class="btn btn-default" >确定</button>
<!-- <div id="view"></div>-->
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript" src="js/bootstrap.min.js"></script>
<script src="js/iscroll-zoom.js"></script>
<script src="js/hammer.js"></script>
<script src="js/lrz.all.bundle.js"></script>
<script src="js/jquery.photoClip.js"></script>
<script>
//document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
var clipArea = new bjj.PhotoClip("#clipArea", {
    size: [260, 260],//宽度,高度
    outputSize: [640, 640],
    file: "#file",
    //view: "#view",
    ok: "#clipBtn",
    loadStart: function() {
        console.log("照片读取中");
    },
    loadComplete: function() {
        console.log("照片读取完成");
    },
    clipFinish: function(dataURL) {
        
        var url="https://apidevelop.yla520.com/api/External/Base64ToImgFile";
        
        var obj={Base64:dataURL,Sex:1};

        //contentType:"application/json",
        
    $.ajax({  
            url: url,  
            type: "POST",  
            data: {strJson:JSON.stringify(obj)},  
            success: function (data) {
                location.href=  data;
                //window.open(data);
            }
        }); 
        
        console.log(dataURL);
        //alert(dataURL);
        //console.log(dataURL);
        console.log("照片读取完成");
        //window.open(url);
    }
});

function ClickFile()
{
    $("#file").click();
}


 //下载图片
      function download(base64Str) {
        let imgData = base64Str;
        this.downloadFile('测试.png', imgData);
      }


      //下载
      function downloadFile(fileName, content) {
        let aLink = document.createElement('a');
        let blob = this.base64ToBlob(content); //new Blob([content]);

        let evt = document.createEvent("HTMLEvents");
        evt.initEvent("click", true, true);//initEvent 不加后两个参数在FF下会报错  事件类型,是否冒泡,是否阻止浏览器的默认行为
        aLink.download = fileName;
        aLink.href = URL.createObjectURL(blob);
        console.log(aLink.href);
        // aLink.dispatchEvent(evt);
        //aLink.click()
        aLink.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));//兼容火狐
      }


      //base64转blob
      function base64ToBlob(code) {
        let parts = code.split(';base64,');
        let contentType = parts[0].split(':')[1];
        let raw = window.atob(parts[1]);
        let rawLength = raw.length;

        let uInt8Array = new Uint8Array(rawLength);

        for (let i = 0; i < rawLength; ++i) {
          uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], {type: contentType});
      }


//clipArea.destroy();
</script>
</body>
</html>

接收并处理图片:

[HttpPost("Base64ToImgFile")]
        public IActionResult Base64ToImgFile([FromForm]string strJson)
        {

            dynamic m= Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(strJson);
            string Base64 = m.Base64;
            Base64 = Base64.Replace("data:image/jpeg;base64,", "");
            int Sex = m.Sex;
            string basePath = "resource\\images\\public\\image\\";
            string posterPath = _AppConfigurtaionServices.AppConfigurations.UploadFileDir + basePath;
            posterPath += (Sex == 1 ? "NewYearBabyPosterBG.jpg" : "NewYearBabyPosterBG.jpg");//男女用不同的图

            Bitmap image = new Bitmap(posterPath);
            Bitmap headImage = YLYUN.Core.Helper.FileHelper.Base64ToImage(Base64);

            Graphics graph = Graphics.FromImage(image);
            //graph.DrawImage(headImage, 30, 800); //直接嵌入

            headImage = YLYUN.Core.Helper.FileHelper.CutEllipse(headImage, new Rectangle(0, 0, 620, 620), new Size(620, 620));



            //Bitmap image = YLYUN.Core.Helper.FileHelper.Base64ToImage();
            //Graphics graph = Graphics.FromImage(image);
            graph.DrawImage(headImage, 30, 30); //转换圆形后嵌入
            graph.Dispose();
            string savaPath = basePath + Guid.NewGuid().ToString() + ".jpg";
            string FilePath = _AppConfigurtaionServices.AppConfigurations.UploadFileDir + savaPath;
            image.Save(FilePath);
            //FileStream fs = new FileStream(Base64);
            //拿到裁剪图片与底图融合成新图片
            return Ok(_AppConfigurtaionServices.AppConfigurations.ResourceUrlPath + savaPath);
        }

 

CutEllipse:

/// <summary>
        /// 图片变圆形
        /// </summary>
        /// <param name="img"></param>
        /// <param name="rec"></param>
        /// <param name="size"></param>
        /// <param name="imgSavePath"></param>
        /// <returns></returns>
        public static Bitmap CutEllipse(Image img, Rectangle rec, Size size)
        {
            Bitmap bitmap = new Bitmap(size.Width, size.Height);
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                using (TextureBrush br = new TextureBrush(img, System.Drawing.Drawing2D.WrapMode.Clamp, rec))
                {
                    br.ScaleTransform(bitmap.Width / (float)rec.Width, bitmap.Height / (float)rec.Height);
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    g.FillEllipse(br, new Rectangle(Point.Empty, size));
                }
            }
            return bitmap;
        }

posted on 2020-01-15 14:28  DaivdHu  阅读(787)  评论(0编辑  收藏  举报

导航