简体   繁体   English

如何检查基本的64编码图像在剃刀中是否包含除白色以外的任何颜色c#

[英]how to check if a base 64 encoded image contains any color but white in razor c#

I am working on a form that contains a jSignature element, which is a jquery plugin to store user made signatures to base64 strings(or other formats). 我正在处理一个包含jSignature元素的表单,这是一个jquery插件,用于将用户签名存储到base64字符串(或其他格式)。

The main issue is that if I try to edit an entry in my List I need to be able to check whether the Signature is empty or not. 主要问题是,如果我尝试编辑列表中的条目,则需要能够检查签名是否为空。

So simplified; 如此简化; validate if a base64 string contains black or is just pure white. 验证base64字符串是包含黑色还是纯白色。

Now the different approaches I took and why they failed: 现在,我采用了不同的方法以及它们失败的原因:

  • saving the source string of an empty signature and comparing it to the new signature 保存空签名的源字符串并将其与新签名进行比较

this has failed since whenever I had a different resolution while adding an entry, the source string would be different from the one previously saved, empty one. 这失败了,因为每当添加条目时,如果我有不同的分辨率,源字符串就会与之前保存的空字符串不同。

  • creating a method in JS to calculate the percentage amount of a color in the base64 string(if not 100% white, there is a signature) 在JS中创建一个方法来计算base64字符串中颜色的百分比(如果不是100%白色,则有签名)

this failed since I need to be able to store the value this method returns in ac# property. 这失败了,因为我需要能够将此方法返回的值存储在ac#属性中。 But apparently the C# part of razor and the inline JS do not exist at the same time. 但是显然,剃须刀的C#部分和内联JS不同时存在。 This would be necessary to check if the signature is empty in an if that either shows the jSignature element to add a signature of a picture of the previously added one 这对于检查签名是否为空是必要的,如果签名中显示jSignature元素以添加先前添加的图片的签名,则签名是否为空。

  • creating a similar method to check the colors of an image with C#(in the cshtml) 创建类似的方法以使用C#检查图像的颜色(在cshtml中)

this would work if I had access to the data layer of the app(which ofc I do have but for this project it would be preferable to not change or add anything there). 如果我可以访问应用程序的数据层(我确实拥有ofc,但是对于此项目,最好不要在其中更改或添加任何内容),则此方法将起作用。 The problem is that i cannot use the datatype Bitmap in a cshtml file. 问题是我无法在cshtml文件中使用数据类型位图。

I am really just looking for a different approach that could work, but if I should add any code snippets just ask for it and i will gladly do it. 我真的只是在寻找一种可行的其他方法,但是如果我要添加任何代码段,只需提出要求,我会很乐意这样做。

Any help is appreciated! 任何帮助表示赞赏!

Edit: updated with code of cshtml: 编辑:更新为cshtml代码:

           @if (!editMode && !formDisabled || signatureEmpty)
            {
                <div class="form-group" style="margin:5%">
                    <div class="form-inline" for="sign">
                        <label class="control-label" style="float:left; margin-top:2%">Unterschrift</label>
                        <button type="button" class="btn btn-primary" style="float:right; margin-bottom:1%; background-color:dodgerblue" onclick="refreshSignature()"><span class="glyphicon glyphicon-refresh"></span></button>                    
                    </div>
                    <div style="width:100%; margin-left:0%;" height:auto" name="sign">
                        <div disabled="@formDisabled" id="signature" class="">

                        </div>
                    </div>
                </div>
            }
            else if(!signatureEmpty) //signature->show image 
            {
                <div class="form-group" style="margin:5%">
                    <div class="form-inline" for="signDisabled">
                        <label class="control-label" style="float:left">Unterschrift</label>
                    </div>
                    <img id="testtest" src="@zeitaufzeichnung.Signature"/> <!--format Signature: data:image/png;base64,i1234lkj123;k4;l1j34l1kj3j...-->
                </div>
            }
            else
            {
                <div class="form-group" style="margin:5%">
                    <label class="control-label" style="float:left">keine Unterschrift vorhanden</label>
                </div>
            }

and the java script methods that should change the C# signatureEmpty attribute(mainly the checkIfSignatureIsEmpty method): 以及应该更改C#signatureEmpty属性的Java脚本方法(主要是checkIfSignatureIsEmpty方法):

function getColors(ctx) {

        // Get the canvas data
        var pixels = ctx.getImageData(0, 0, ctx.width, ctx.height),
            data = pixels.data,

        // Set up our output object to collect color data
        output = {};

        // For each color we encounter, check the
        // output object. If the color already exists
        // there, simply increase its counted value.
        // If it does not, create a new key.
        for (var i = 0; i < data.length; i += 4) {
            var r = data[i],
                g = data[i + 1],
                b = data[i + 2],
                col = rgbToHex(r, g, b);

            if (output[col])
                output[col]++
            else
                output[col] = 1
        }

        // Count total
        var total = 0;
        for (var key in output) {
            total = total + parseInt(output[key])
        }
        output.total = total;

        // Return the color data as an object
        return output;
    }

    function checkIfSignatureIsEmpty(source)
    {
        var img = new Image();
        img.src = source;
        img.id = "img";
        img.name = "img";

        img.onload=function(){
            var imageData = extract_colors(img);
            if (imageData[0] / imageData.total == 1) {
                return true;
            } else {
                return false;
            }
        }
    }

    function extract_colors(img) {
        var canvas = document.createElement("canvas");
        var c = canvas.getContext('2d');
        c.width = canvas.width = img.width;
        c.height = canvas.height = img.height;
        c.clearRect(0, 0, c.width, c.height);
        c.drawImage(img, 0, 0, img.width, img.height);
        return getColors(c);
    }

    function rgbToHex(r, g, b) {
        return ((r << 16) | (g << 8) | b).toString(16);
    }

I finally convinced myself to create a method in the data-layer of the application. 我终于说服自己在应用程序的数据层中创建一个方法。

Here is the code in case anybody needs it: 如果有人需要,下面是代码:

public static bool IsSignatureEmpty(string base64Source)
    {
        Bitmap signatureBM = null;

        try
        {
            byte[] byteBuffer = Convert.FromBase64String(base64Source.Replace("data:image/png;base64,", ""));
            MemoryStream memoryStream = new MemoryStream(byteBuffer);

            memoryStream.Position = 0;

            signatureBM = (Bitmap)Bitmap.FromStream(memoryStream);

            memoryStream.Close();
            memoryStream = null;
            byteBuffer = null;
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message);
        }

        int width = signatureBM.Width;
        int height = signatureBM.Height;

        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                //Name==0 would equal the color white
                if (signatureBM.GetPixel(x, y).Name != "0")
                {
                    return false;
                }
            }
        }
        return true;
    }

if you would really want to use pure JS/Html use the js code from above and refer to the comment by Marco: 如果您真的想使用纯JS / HTML,请使用上面的js代码,并参考Marco的评论:

Instead of using c# just set a javascript variable. 代替使用c#而是设置一个javascript变量。 Use a different querystring or route value for editMode and then just hide the div using javascript 对editMode使用不同的查询字符串或路由值,然后使用javascript隐藏div

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM