从c#中的byte arrray中删除0个值

时间:2015-10-22 12:20:17

标签: javascript c# canvas

我有这段代码:

[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是一个函数,它接受base64字符串并将其转换为二进制并将图像保存到服务器

base64数据来自在上传时加载图像的画布  图像看起来像这样: enter image description here

我的问题不会显示,除非您在新标签中打开示例图像,您可以看到它周围有白色边框,因为当它上传到画布时它不适合画布大小

我的问题是如何在将图像保存到服务器(0 byte)之前从图像中删除那些白色边框(从字节数组中删除bw.write(data)) 我试过这段代码,但它不适用于我:

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);

这是客户端代码:

        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

2 个答案:

答案 0 :(得分:0)

如果您只想从字节数组中删除0,那么您可能不能使用LINQ吗?通过导入命名空间,您可以使用此代码检查数组中的所有0值,并选择不为0的值并将其重写为数组:

class Refresh extends AsyncTask<String,Void,Void>{

    @Override
    protected Void doInBackground(String... params) {
        try {
            Download(getResources().getString(R.string.link));
        }catch (Exception e){
            createNetErrorDialog();

        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        try{
            views();
        }catch (Exception e){
            Toast.makeText(MainActivity.this,
                    "Error",
                    Toast.LENGTH_LONG).show();
            cancel(true);
        }

        lstPost.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {
                Intent intent = new Intent(MainActivity.this, WebviewActivity.class);
                Bundle bundle = new Bundle();

                Document xmlFeed = rssfeed
                        .getRSSFromServer(getResources().getString(R.string.link));
                NodeList nodes = xmlFeed.getElementsByTagName(getResources().getString(R.string.item));
                Element item = (Element) nodes.item(position);
                String summary = rssfeed.getValue(item, key_summary);
                String title = rssfeed.getValue(item, key_title);
                bundle.putString(getResources().getString(R.string.tag_summary), summary);
                bundle.putString(getResources().getString(R.string.tag_title), title);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }
}




void Download(String url) throws Exception{
    lists.clear();

        Document xmlFeed = rssfeed.getRSSFromServer(url);
        NodeList nodes = xmlFeed.getElementsByTagName("entry");
        for (int i = 0; i < nodes.getLength(); i++) {
            Element item = (Element) nodes.item(i);
            HashMap<String, Object> feed = new HashMap<String, Object>();
            feed.put(key_title, rssfeed.getValue(item, key_title));
            feed.put(key_summary, rssfeed.getValue(item, key_summary));
            feed.put(key_link, rssfeed.getValue(item, key_link));
            //feed.put(key_date, rssfeed.getValue(item, key_date));
            post_lists.add(feed);
            lists.add(feed.get(key_title).toString());
        }

}


void views(){
    lstPost = (ListView) findViewById(R.id.lstPosts);

    adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_2, android.R.id.text1, lists) {

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = super.getView(position, convertView, parent);
            TextView txt1 = (TextView) view
                    .findViewById(android.R.id.text1);
            TextView txt2 = (TextView) view
                    .findViewById(android.R.id.text2);
            HashMap<String, Object> data = post_lists.get(position);
            txt1.setText(Html.fromHtml(data.get(key_title).toString()));

            if (data.get(key_summary).toString().length() > 125) {

                txt2.setText(Html.fromHtml((data.get(key_summary).toString()).substring(0, 125) + "..."));
            } else {

                txt2.setText(Html.fromHtml(data.get(key_summary).toString()));
            }
            return view;
        }

    };

    TextView dateview=(TextView) findViewById(R.id.date);
    Calendar rightNow = Calendar.getInstance();
    DateFormat formatter = new SimpleDateFormat(getResources().getString(R.string.date_format));

    dateview.setText(getResources().getString(R.string.lastupdate) + formatter.format(rightNow.getTime()));
    lstPost.setAdapter(adapter);
}


protected void createNetErrorDialog() {

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(getResources().getString(R.string.errorbox))
            .setTitle("Unable to connect")
            .setCancelable(false)
            .setPositiveButton("Settings",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            Intent i = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
                            startActivity(i);
                        }
                    }
            )
            .setNeutralButton("Refresh",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            new Refresh().execute(getResources().getString(R.string.link));
                        }
                    })
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            finish();
                        }
                    }
            );
    AlertDialog alert = builder.create();
    alert.show();
}

希望这会对你有所帮助。

此致 沃伦

答案 1 :(得分:0)

一种解决方案是使用像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);

            } 
        }
    }

EntropyCrop处理器会将图像裁剪到最大熵区域。换句话说,它将删除图像周围的空白。

ImageProcessor.Web项目中还有一个基于URL的web api。

代码参考: