I'm building an Image upload tool that resizes an image to fit a fixed size but it's adding a black background instead of a transparent one to the filler space around the image.
I've read that the Bitmap needs to be set to a PixelFormat with an Alpha layer and that I can set the Graphics clear colour to transparent but I'm still getting the same problem.
My images are mostly jpegs. Here is the code:
private void ResizeImage(Image Original, Int32 newWidth, Int32 newHeight, String pathToSave)
{
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
int originalWidth = Original.Width;
int originalHeight = Original.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)newWidth / (float)originalWidth);
nPercentH = ((float)newHeight / (float)originalHeight);
if (nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = System.Convert.ToInt16((newWidth -
(originalWidth * nPercent)) / 2);
}
else
{
nPercent = nPercentW;
destY = System.Convert.ToInt16((newHeight -
(originalHeight * nPercent)) / 2);
}
int destWidth = (int)(originalWidth * nPercent);
int destHeight = (int)(originalHeight * nPercent);
Bitmap bmp = new Bitmap(newWidth, newHeight, PixelFormat.Format32bppArgb);
bmp.SetResolution(Original.HorizontalResolution, Original.VerticalResolution);
using (Graphics Graphic = Graphics.FromImage(bmp))
{
Graphic.CompositingQuality = CompositingQuality.HighQuality;
Graphic.Clear(Color.Red);
Graphic.CompositingMode = CompositingMode.SourceCopy;
Graphic.SmoothingMode = SmoothingMode.AntiAlias;
Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
Graphic.DrawImage(
Original,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, originalWidth, originalHeight),
GraphicsUnit.Pixel
);
bmp.Save(pathToSave,Original.RawFormat);
}
}
No, you made that background red, not black. Use Color.Transparent if you want to have the alpha of the background set to 0. Or just omit the Clear(), it is the default for a new bitmap. And avoid Original.RawFormat in the Save() call, you don't want to use an image format that doesn't support transparency. Png is always good. And be sure that whatever method you use to display the resulting bitmap supports transparency as well. With a well defined background color. You'll get black when it doesn't, Color.Transparent has R, G and B at 0. Black.
What is the input format of your image? If it is jpg, the it is probably because jpg does not support transparency. You can try to use an output format of PNG which does support transparency: