views:

124

answers:

1

I am saving an image bytes array as a thumbnail. The problem is that the transparent background color is black in my image.

Below is my code:

MemoryStream memoryStream = new MemoryStream(pbytImageByteArray);

System.Drawing.Image imgImageSource = System.Drawing.Image.FromStream(memoryStream);

double dblOrgnWidth = imgImageSource.Width;
double dblOrgnHeight = imgImageSource.Height;

double dblRatio = (dblOrgnWidth / dblOrgnHeight) * 100;

double dblScaledWidth = pintWidth;
double dblScaledHeight = 0;

dblScaledHeight = (dblScaledWidth / dblRatio) * 100;
System.Drawing.Bitmap bitmapImage = new System.Drawing.Bitmap(System.Convert.ToInt32(dblScaledWidth), System.Convert.ToInt32(dblScaledHeight));

bitmapImage.SetResolution(imgImageSource.HorizontalResolution, imgImageSource.VerticalResolution);
System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmapImage);
graphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;            
ImageAttributes imageAttributes = new ImageAttributes();            
graphics.DrawImage(imgImageSource, new System.Drawing.Rectangle(0, 0, System.Convert.ToInt32(dblScaledWidth), System.Convert.ToInt32(dblScaledHeight)), 0, 0, System.Convert.ToInt32(dblOrgnWidth), System.Convert.ToInt32(dblOrgnHeight), System.Drawing.GraphicsUnit.Pixel);

MemoryStream outputMemoryStream = new MemoryStream();
bitmapImage.Save(outputMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
bitmapImage.GetThumbnailImage(System.Convert.ToInt32(dblScaledWidth), System.Convert.ToInt32(dblScaledHeight), null, IntPtr.Zero);
imgImageSource.Dispose();
bitmapImage.Dispose();
graphics.Dispose();
return outputMemoryStream.ToArray();
A: 

JPEG doesn't support transparency. Save as a PNG.

Alternatively, if you know the background color that this will be on, you could set the transparent pixels to that color. If you are using semi-transparent pixels, then you would have to blend the pixels with that color.

Here is an article that explains alpha blending:

http://www.c-sharpcorner.com/UploadFile/mahesh/DrawTransparentImageUsingAB10102005010514AM/DrawTransparentImageUsingAB.aspx

If you are interested in a commercial solution for that (Disclaimer: I work for Atalasoft), DotImage Photo has a class, FlattenAlphaCommand, that can do this in a couple of lines of code.

Lou Franco