简体   繁体   English

从C#中的字节错误中删除0个值

[英]removing 0 values from byte arrray in c#

I have this code : 我有这个代码:

[WebMethod]
public static string SaveImg(string imgdata)
{

    string Path = "UploadedImages/";
    string folderPath = HttpContext.Current.Server.MapPath(Path);
    Guid gid=Guid.NewGuid();
    string fileNameWitPath = folderPath + "img_" +gid  + ".png";

    FileStream fs = new FileStream(fileNameWitPath, FileMode.Create);
    BinaryWriter bw = new BinaryWriter(fs);

    byte[] data = Convert.FromBase64String(imgdata);

    bw.Write(data);
    bw.Close();
    bw.Dispose();
    return  "/" + Path +"img_"+ gid + ".png";
}

witch is a function that take a base64 string and convert it to binary and save the image to server witch是一个函数,它使用base64字符串并将其转换为二进制并将图像保存到服务器

the base64 data are taken from a canvas that load the image upon upload the image look like this : base64数据取自画布,该画布在上载图像时加载图像,如下所示: 在此处输入图片说明

my problem will not show unless you open the example image in a new tab, you can see that it contain white borders around it due to the fact that when it's been uploaded into the canvas it wont fit the canvas size 除非您在新标签页中打开示例图片,否则我的问题将不会显示,您可以看到它周围带有白色边框,原因是当将其上传到画布中时,它不适合画布大小

my question is how can i remove those white border from the image ( removing the 0 byte from the byte array ) before i save it to server ( bw.write(data) ) I tried this code but it did not work with me : 我的问题是我如何在将图像保存到服务器( bw.write(data) )之前从图像中删除那些白色边框(从字节数组中删除0 byte ),但是我尝试使用此代码,但不适用于我:

int i = data.Length - 1;
while(data[i] == 0)
   --i;
// now data[i] is the last non-zero byte
byte[] bar = new byte[i+1];
Array.Copy(data, bar, i+1);
bw.Write(data);

this is the client code : 这是客户代码:

        var canvas = $("#imageCanvas")[0];
        var ctx = canvas.getContext("2d");
        var uploadInput = $('#UploadFile');
        var width = 382;
        var height = 295;
uploadInput.on('change', function (e) {
            RemoveDisabledClass();
            handleImage(e);
        });

        function handleImage(e) {
            var reader = new FileReader();
            reader.onload = function (event) {
                var img = new Image();
                img.onload = function () {
                    // var canvas = ctx.canvas;
                    var hRatio = canvas.width / img.width;
                    var vRatio = canvas.height / img.height;
                    var ratio = Math.min(hRatio, vRatio);
                    var centerShift_x = (canvas.width - img.width * ratio) / 2;
                    var centerShift_y = (canvas.height - img.height * ratio) / 2;
                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    ctx.drawImage(img, 0, 0, img.width, img.height,
                                       centerShift_x, centerShift_y, img.width * ratio, img.height * ratio);
                }
                img.src = event.target.result;

            }
            reader.readAsDataURL(e.target.files[0]);
        }

        $("#btn_save").click(function () {
            if ($("#btn_save").hasClass("disabled")) return;
            $("#dv_Error").css("display", "none");
            var image = document.getElementById("imageCanvas").toDataURL();
            image = image.replace('data:image/png;base64,', '');
            $.ajax({
                type: 'POST',
                url: 'Default.aspx/SaveImg',
                data: '{ "imgdata" : "' + image + '" }',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (data) {
                    window.location.href = data.d;

                },
                error: function (request, status, error) {
                    $("#dv_Error").css("display", "block");

                }

            }); //ENd Ajax
        }); //End Click event

If you are wanting to simply remove the 0's from the byte array could you not maybe use LINQ? 如果只想从字节数组中删除0,就不能使用LINQ吗? by importing the namespace you can then use this code to check for all 0 values in array and select the values that arent 0 and rewrite it to the array: 通过导入名称空间,您可以使用以下代码检查数组中的所有0值,然后选择0之前的值并将其重写为数组:

data = data.Where(x => x != 0).ToArray();

Hope this helps you. 希望这对您有所帮助。

Regards, Warren 问候,沃伦

One solution would be to use something like ImageProcessor ( https://github.com/JimBobSquarePants/ImageProcessor ) - it includes a Processor that does exactly what you're looking for: 一种解决方案是使用类似ImageProcessor( https://github.com/JimBobSquarePants/ImageProcessor )的东西-它包含一个处理器,可以完全满足您的需求:

   // Read a file and resize it.
   byte[] source = File.ReadAllBytes(file);

   using (MemoryStream inStream = new MemoryStream(source))
       using (MemoryStream outStream = new MemoryStream())
           using (ImageFactory imageFactory = new ImageFactory())
           {
               // Load, remove whitespace around image and save an image.
               imageFactory.Load(inStream)
                    .EntropyCrop()
                    .Save(outStream);

            } 
        }
    }

the EntropyCrop Processor will crop the image to the area of greatest entropy. EntropyCrop处理器会将图像裁剪到最大熵的区域。 In other words, it will remove whitespace from around the image. 换句话说,它将删除图像周围的空白。

There's also a url-based web api available in the ImageProcessor.Web project. ImageProcessor.Web项目中还有一个基于URL的Web api。

Code References: 代码参考:

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

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