代码之家  ›  专栏  ›  技术社区  ›  Asim Sajjad

为什么透明像素在我的图像中显示为黑色?

  •  1
  • Asim Sajjad  · 技术社区  · 14 年前

    我正在将图像字节数组保存为缩略图。问题是我的图像中透明的背景色是黑色的。

    以下是我的代码:

    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();
    
    1 回复  |  直到 14 年前
        1
  •  0
  •   Lou Franco    14 年前

    jpeg不支持透明度。保存为PNG。

    或者,如果知道将启用的背景颜色,可以将透明像素设置为该颜色。如果您使用的是半透明像素,则必须将像素与该颜色混合。

    下面是一篇解释alpha混合的文章:

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

    如果您对这方面的商业解决方案感兴趣(免责声明:我为AtalaSoft工作), DotImage Photo 有一个班, FlattenAlphaCommand ,这可以在几行代码中完成。