Hi Team
Please let me know is it possible to remove white space around PNG image through SPIRE API.
Thanks in advance
static void Main(string[] args)
{
Image image = Image.FromFile(inputImagePath);
Bitmap bmp = new Bitmap(image);
Bitmap bitmap = CutImageWhitePart(bmp);
bitmap.Save("output.png", ImageFormat.Png);
}
public static Bitmap CutImageWhitePart(Bitmap bmp)
{
int top = 0, left = 0, right = bmp.Width, bottom = bmp.Height;
for (int i = 0; i<bmp.Height; i++)
{
bool find = false;
for (int j = 0; j<bmp.Width; j++)
{
Color c = bmp.GetPixel(j, i);
if (!IsWhite(c))
{
top = i;
find = true;
break;
}
}
if (find)
break;
}
for (int i = 0; i < bmp.Width; i++)
{
bool find = false;
for (int j = top; j < bmp.Height; j++)
{
Color c = bmp.GetPixel(i, j);
if (!IsWhite(c))
{
left = i;
find = true;
break;
}
}
if (find)
break;
}
for (int i = bmp.Height - 1; i >= 0; i--)
{
bool find = false;
for (int j = left; j < bmp.Width; j++)
{
Color c = bmp.GetPixel(j, i);
if (!IsWhite(c))
{
bottom = i;
find = true;
break;
}
}
if (find)
break;
}
for (int i = bmp.Width - 1; i >= 0; i--)
{
bool find = false;
for (int j = 0; j <= bottom; j++)
{
Color c = bmp.GetPixel(i, j);
if (!IsWhite(c))
{
right = i;
find = true;
break;
}
}
if (find)
break;
}
//Clone part of a bitmap object
Rectangle cloneRect = new Rectangle(left, top, right - left, bottom - top);
Bitmap cloneBitmap = bmp.Clone(cloneRect, bmp.PixelFormat);
bmp.Dispose();
return cloneBitmap;
}
//Determine whether white and pure transparent (tolerance of 10 points)
public static bool IsWhite(Color c)
{
//Pure transparency is also white,RGB 255 is pure white
if (c.A < 10 || (c.R > 245 && c.G > 245 && c.B > 245))
return true;
return false;
}