TEST MASTER
TEST MASTER

Reputation: 33

GDI+ Create a mask from an image

I like to be able to split the image from the canvas and leave the background alone. The result should be like the ImageB.png(the white area is transparent) below. The code I wrote below is in asp.net C# webform.

ImageA.png (Image with background)

ImageA(Image with background)

ImageB.png(Image with the lady, the white area should be transparent)

Image has been removed from background

ASP.NET C# webform code.

  protected void Page_Load(object sender, EventArgs e)
    {
        //Load image
        Bitmap loadImage = new Bitmap(Server.MapPath("ImageA.png"));
        //Create a canvas to work on
        Bitmap canvas = new Bitmap(loadImage.Width, loadImage.Height);
        // create graphic on canvas
        Graphics graphicOnCanvas = Graphics.FromImage(canvas);
        graphicOnCanvas.DrawImage(loadImage, 0, 0, loadImage.Width, loadImage.Height);//Draw the graphic to the canvas

        //*****REMOVE IMAGE FROM BACKGROUND ?????????????????????? ********/


        #region Output image on screen
        MemoryStream msOut = new MemoryStream();
        canvas.Save(msOut, ImageFormat.Png);//must leave as png to output as png
        canvas.Dispose();//Dispose the canvas
        Byte[] BitmaptoBytes = msOut.ToArray();
        //convert bitmapholder to byte[] - ended
        BitmaptoBytes = null;
        Response.ClearHeaders();
        Response.ContentType = "image/png";//to product a better jpeg we have to use this because event if using the codec to do it it still doesn't look good http://msdn.microsoft.com/en-us/library/aa479306.aspx
        //disable 1 line below to prevent download from viewing
        // Response.AddHeader("Content-Disposition", "attachment; filename=" + ProductImage.Substring(0, ProductImage.Length - Reverse(ProductImage).Split('.')[0].Length-1) + ".png");//changing the file name extension
        Response.AddHeader("Content-Length", msOut.Length.ToString());
        msOut.WriteTo(Response.OutputStream);//Sending image out
        Response.End();
        loadImage.Dispose();
        #endregion
    }

Upvotes: 1

Views: 1346

Answers (1)

Ani
Ani

Reputation: 10906

You will probably need to go through each pixel (using a WriteableBitmap) and determine if the current pixel is a "background" pixel (you can do this with an exact, "fuzzy" match or alpha test) - and then replace it with white or any other color you wish.

Here's how you can access all the pixels in a WriteableBitmap.

Upvotes: 1

Related Questions