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?
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.