CypherNet
CypherNet

Reputation: 51

Remove white Background in the image still has white edges c#

I am trying to write code that would remove the white background from jpeg-images, can save them in same format.

Here is my code so far:

string imgPath = Server.MapPath("~/App_Files/" + Profile.CompanyName + "/Temp/test.jpg");
Bitmap bmp = RADBase.ImageHandler.LoadImage(imgPath);
bmp.MakeTransparent(Color.White);
System.Drawing.Imaging.ImageFormat format = new System.Drawing.Imaging.ImageFormat(Guid.NewGuid());
bmp.Save(imgPath, format);

It removes the white background, but there are still white edges on the image. not sure how to get the complete white background removed?

Upvotes: 0

Views: 7268

Answers (2)

daniel59
daniel59

Reputation: 916

One way would be to create a range of colors, which look white and check each pixel if it is a "white". Then you can set these pixels to Color.Transparent:

string imgPath = Server.MapPath("~/App_Files/" + Profile.CompanyName + "/Temp/test.jpg");
Bitmap source = new Bitmap(imgPath);
source.MakeTransparent();
for (int x = 0; x < source.Width; x++)
{
    for (int y = 0; y < source.Height; y++)
    {
        Color currentColor = source.GetPixel(x, y);
        if (currentColor.R >= 220 && currentColor.G >= 220 && currentColor.B >= 220)
        {
            source.SetPixel(x, y, Color.Transparent);
        }
    }
}
source.Save(imgPath);

This is a rough solution, because it is hard say, if one color is white or not. Maybe there you have to adjust the range for better result. Another point is that also some colors of the t-shirt look white, so these will be transparent too.

Upvotes: 3

SedatD
SedatD

Reputation: 1

you should clean all white catefories, You can see categories below link. You can see especially grey and white categories (grey category = gri kategorisi, white category = beyaz category). You can remove colors with their RBG values.

Here Categories

Upvotes: -4

Related Questions