Upload a picture and take a screenshot of the circled profile

Use Cropper.js to crop the image,
and then use ajaxfileupload.js to upload the file


<script src="~/Content/scripts/plugins/cropper/Cropper.js"></script>
<link href="~/Content/scripts/plugins/cropper/Cropper.css" rel="stylesheet" />
<script src="~/Content/scripts/plugins/uploadify/ajaxfileupload.js"></script>
<style>
    body{
    
    
        padding:20px;
    }
    /* Ensure the size of the image fit the container perfectly */
    img {
    
    
        display: block;
        /* This rule is very important, please don't ignore this */
        max-width: 100%;
    }

    .cropper-view-box, .cropper-face {
    
    
        border-radius: 50%;
    }
    #croper{
    
    
        width: 825px;
        height: 497px;
    }
    .upload_td{
    
    
        position:relative;
    }
    #fileupload{
    
    
       position: absolute; top: 0; bottom: 0; left: 0;right: 0; opacity: 0;
       height:100%;
    }
    .upload-div{
    
    
        text-align: top;
    }
    #upload{
    
    
        width: 100px; height: 100px; vertical-align: middle;
    }
</style>
<script>
    var keyValue = request('keyValue');
    var cropper;
    var imagepath;
    $(function () {
    
    
        initControl();
    });
    //初始化控件
    function initControl() {
    
    
        //获取表单
        GetComboBox();
        if (!cropper) {
    
    
            Crop_init();
        }
      

        if (!!keyValue) {
    
    
            $.SetForm({
    
    
                url: "../../ActivityManage/ZF_Official/GetFormJson",
                param: {
    
     keyValue: keyValue },
                success: function (data) {
    
    
                    $("#form1").SetWebControls(data);
                }
            })
        }
        AddEvent(document.getElementById("CutDown"), "click",CutDown);
    }
    /**
     * 添加事件
     * @@param dom :such as document.getElementById("xx")
     * @@param event:"click"
     * @@param fn:执行方法
     */
    function AddEvent(dom, event, fn) {
    
    
        dom.addEventListener(event, fn);
    }
    //保存表单;
    function AcceptClick() {
    
    
        if (!$('#form1').Validform()) {
    
    
            return false;
        }
        var postData = $("#form1").GetWebControls(keyValue);
        postData["OfficialImage"] = imagepath;
        $.SaveForm({
    
    
            url: "../../ActivityManage/ZF_Official/SaveForm?keyValue=" + keyValue,
            param: postData,
            loading: "正在保存数据...",
            success: function () {
    
    
                $.currentIframe().$("#gridTable").trigger("reloadGrid");
            }
        })
    }
    /**
     * 获得combox
     * */
    function GetComboBox() {
    
    
        $("#Moldid").ComboBox({
    
    
            url: "../../ActivityManage/ZF_Mold/GetListJson",
            param: {
    
    
                queryJson: JSON.stringify({
    
    
                    IsEnable: true
                }),
            },
            id: "Moldid",
            text: "MoldName",
            description: "选择分类",
            height: "170px"
        });
    }
    /**
     * 裁剪图片初始化
     * */
    function Crop_init() {
    
    
        const image = document.getElementById('image');
        cropper = new Cropper(image, {
    
    
            viewMode:2,
            aspectRatio: 9 / 9,
          
        });
    }
    /**
     * 预览图片
     * @@param ev
     */
    function uploadify(ev) {
    
    
        var that = this;
        const file = document.getElementById('fileupload');
        const fileObj = file.files[0];
        const windowURL = window.URL || window.webkitURL;
        const img = document.getElementById('image');
        if (file && fileObj) {
    
    
            $("#croper").removeClass("hide");
            $(".alert").removeClass("hide");
            const dataURl = windowURL.createObjectURL(fileObj);
            img.setAttribute('src', dataURl);
            cropper.replace(dataURl, false);
            //替换图片
        }
    }
    /**
     * 裁剪图片
     * */
    function CutDown() {
    
    
        let ans = cropper.getData();
        $.ajaxFileUpload({
    
    
            url: "/ActivityManage/ZF_Official/UploadFile",
            secureuri: false,
            data: {
    
    
                X: Math.round(ans.x),
                Y: Math.round(ans.y),
                width: Math.round(ans.width),
                height: Math.round(ans.height)
            },
            fileElementId: 'fileupload',
            dataType: 'json',
            success: function (data) {
    
    
                document.getElementById("upload").setAttribute("src", data.message);
                imagepath = data.message;
            }
        });
    }
</script>
<div style="margin-top: 20px; margin-right: 30px;">
    <table class="form">
        <tr>
            <td class="formTitle">公众号名字<font face="宋体">*</font></td>
            <td class="formValue">
                <input id="OfficialName"  isvalid="yes" checkexpession="NotNull" type="text" class="form-control" />
            </td>
            <td class="formTitle">所属分类<font face="宋体">*</font></td>
            <td>
                <div id="Moldid"  isvalid="yes" checkexpession="NotNull" type="select" class="ui-select" style="float: left; width: 84px; margin-right: 1px;"></div>
            </td>
        </tr>
        <tr>
            <td class="formTitle">公众号访问地址<font face="宋体">*</font></td>
            <td class="formValue">
                <input id="OfficialAddress"  isvalid="yes" checkexpession="NotNull" type="text" class="form-control" />
            </td>
            <td class="formTitle">公众号图片</td>
            <td class="formValue upload_td">
                <input id="fileupload" name="fileupload" type="file" class="form-control" onchange="uploadify()" accept="image/gif, image/jpg, image/png,image/jpeg," />
                <div class="upload-div">
                    <img id="upload" src="~/Content/images/icon_app_add.png" />
                </div>
            </td>
        </tr>
        <tr>
            <td class="formTitle">排序</td>
            <td class="formValue">
                <input id="Sord" type="text" class="form-control" />
            </td>
        </tr>
    </table>
    <div class="alert hide alert-success" role="alert">
         图片操作区
         <div class="btn btn-info" id="CutDown">裁剪</div>
    </div>
    <div class="hide" id="croper">
        <img id="image" src="~/Content/images/UserCard01.png" />
    </div>
</div>


The background code needs to receive the original picture, where the picture was taken

  /// <summary>
        /// 上传头像 这里X,Y为图片的左上角的定位,width和height为宽高
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadFile(string X,string Y,string width,string height)
        {
    
    
            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            //没有文件上传,直接返回
            if (files[0].ContentLength == 0 || string.IsNullOrEmpty(files[0].FileName))
            {
    
    
                return HttpNotFound();
            }

            string FileEextension = Path.GetExtension(files[0].FileName);
            string virtualPath = string.Format("/Upload/Sign_Imgs/{0}{1}", Guid.NewGuid().ToString(), ".png");
            string fullFileName = Server.MapPath("~" + virtualPath);

            //创建文件夹,保存文件
            string path = Path.GetDirectoryName(fullFileName);
            Directory.CreateDirectory(path);

            using (var image =Image.Load(files[0].InputStream))
            {
    
    
                image.Mutate(x => x.Crop(new Rectangle(Convert.ToInt32(X), Convert.ToInt32(Y), Convert.ToInt32(width), Convert.ToInt32(height))));
                using (Image destRound = image.Clone(x => x.ConvertToAvatar(new Size(200, 200), 100)))
                {
    
    
                    destRound.Save(fullFileName,new PngEncoder());
                }
            }
            return Success(virtualPath);
        }

Then use SixLabors to modify the background image

using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using SixLabors.Primitives;
using SixLabors.Shapes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Huajie.Application.WwwInterface.Helper.SixLabors
{
    
    
    public static class SixLaborsHelper
    {
    
    
        // Implements a full image mutating pipeline operating on IImageProcessingContext
        public static IImageProcessingContext ConvertToAvatar(this IImageProcessingContext processingContext, Size size, float cornerRadius)
        {
    
    
            return processingContext.Resize(new ResizeOptions
            {
    
    
                Size = size,
                Mode = ResizeMode.Crop
            }).ApplyRoundedCorners(cornerRadius);
        }
        // This method can be seen as an inline implementation of an `IImageProcessor`:
        // (The combination of `IImageOperations.Apply()` + this could be replaced with an `IImageProcessor`)
        private static IImageProcessingContext ApplyRoundedCorners(this IImageProcessingContext ctx, float cornerRadius)
        {
    
    
            Size size = ctx.GetCurrentSize();
            IPathCollection corners = BuildCorners(size.Width, size.Height, cornerRadius);

            var graphicOptions = new GraphicsOptions(true)
            {
    
    
                AlphaCompositionMode = PixelAlphaCompositionMode.DestOut // enforces that any part of this shape that has color is punched out of the background
            };
            // mutating in here as we already have a cloned original
            // use any color (not Transparent), so the corners will be clipped
            return ctx.Fill(graphicOptions, Rgba32.LimeGreen, corners);
        }

        private static IPathCollection BuildCorners(int imageWidth, int imageHeight, float cornerRadius)
        {
    
    
            // first create a square
            var rect = new RectangularPolygon(-0.5f, -0.5f, cornerRadius, cornerRadius);

            // then cut out of the square a circle so we are left with a corner
            IPath cornerTopLeft = rect.Clip(new EllipsePolygon(cornerRadius - 0.5f, cornerRadius - 0.5f, cornerRadius));

            // corner is now a corner shape positions top left
            //lets make 3 more positioned correctly, we can do that by translating the original around the center of the image

            float rightPos = imageWidth - cornerTopLeft.Bounds.Width + 1;
            float bottomPos = imageHeight - cornerTopLeft.Bounds.Height + 1;

            // move it across the width of the image - the width of the shape
            IPath cornerTopRight = cornerTopLeft.RotateDegree(90).Translate(rightPos, 0);
            IPath cornerBottomLeft = cornerTopLeft.RotateDegree(-90).Translate(0, bottomPos);
            IPath cornerBottomRight = cornerTopLeft.RotateDegree(180).Translate(rightPos, bottomPos);

            return new PathCollection(cornerTopLeft, cornerBottomLeft, cornerTopRight, cornerBottomRight);
        }
    }
}





Guess you like

Origin blog.csdn.net/zt13502162671/article/details/105436308