C#将图片转化为黑白图片

最近项目需要将上传的图片转化为黑白图片

在网上找了很多资料,测试通过,上代码

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Drawing;

using System.Drawing.Imaging;

using System.IO;



namespace Test

{

    public partial class WebForm1 : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            Bitmap b = new Bitmap(Server.MapPath("1.jpg"));

            for (int x = 0; x < b.Width; x++)

            {

                for (int y = 0; y < b.Height; y++)

                {

                    Color pixel = b.GetPixel(x, y);

                    int val = (pixel.R + pixel.G + pixel.B) / 3;

                    b.SetPixel(x, y, Color.FromArgb(val, val, val));



                }

            }

            //b.Save(Server.MapPath("New1.jpg"));  //存储图片



            //直接显示图片

            MemoryStream ms = new MemoryStream();

            b.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

            byte[] bytes = ms.GetBuffer();  //byte[]   bytes=   ms.ToArray(); 



            Response.ContentType = "image/Jpeg";

            Response.BinaryWrite(bytes);

            Response.End();

        }

    }

}

 

你可能感兴趣的:(C#)