2010-06-01 180 views
1

我將圖像字節數組保存爲縮略圖。問題是透明背景顏色在我的圖像中是黑色的。爲什麼透明像素在圖像中顯示爲黑色?

下面是我的代碼:

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(); 

回答

0

JPEG不支持透明度。另存爲PNG。

或者,如果您知道將會打開的背景顏色,則可以將透明像素設置爲該顏色。如果您使用半透明像素,則必須將像素與該顏色混合。

這裏是解釋alpha混合的文章:

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

如果你有興趣去了解(聲明:我Atalasoft工作)商業解決方案,DotImage Photo有一個類,FlattenAlphaCommand,可在幾行代碼中執行此操作。