如何保留PNG透明度?

6
我创建了一个函数,允许上传透明的.png文件插入到SQL Server数据库中,并通过HttpHandler在网页上显示。

虽然这一切都有效,但是当它在网页上查看时,png透明度会变为黑色。有没有一种方法可以保留透明度?

这是我的图像服务,它从MVC控制器插入数据库:

public void AddImage(int productId, string caption, byte[] bytesOriginal)
{
    string jpgpattern = ".jpg|.JPG";
    string pngpattern = ".png|.PNG";
    string pattern = jpgpattern;

    ImageFormat imgFormat = ImageFormat.Jpeg;

    if (caption.ToLower().EndsWith(".png"))
    {
    imgFormat = ImageFormat.Png;
    pattern = pngpattern;
    }

    ProductImage productImage = new ProductImage();
    productImage.ProductId = productId;
    productImage.BytesOriginal = bytesOriginal;
    productImage.BytesFull = Helpers.ResizeImageFile(bytesOriginal, 600, imgFormat);
    productImage.BytesPoster = Helpers.ResizeImageFile(bytesOriginal, 198, imgFormat);
    productImage.BytesThumb = Helpers.ResizeImageFile(bytesOriginal, 100, imgFormat);
    productImage.Caption = Common.RegexReplace(caption, pattern, "");

    productImageDao.Insert(productImage);
}

这里是“ResizeImageFile”帮助函数:

public static byte[] ResizeImageFile(byte[] imageFile, int targetSize, ImageFormat imageFormat)
{
    using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile)))
    {
        Size newSize = CalculateDimensions(oldImage.Size, targetSize);
        using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb))
        {
            using (Graphics canvas = Graphics.FromImage(newImage))
            {
            canvas.SmoothingMode = SmoothingMode.AntiAlias;
            canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
            canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
            canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));
            MemoryStream m = new MemoryStream();
            newImage.Save(m, imageFormat);
            return m.GetBuffer();
            }
        }
    }
}

我需要怎样做才能保留PNG图片的透明度呢?请提供一些例子。我对图像处理并不是很熟悉。

谢谢。


2
尝试使用Format32bppArgb来保留Alpha通道(即'A')。 - Matthew Flaschen
请避免在您的问题标题中加上"C#"或类似的前缀。这就是标签的作用。 - M.Babcock
你知道你原始的.png是8位还是全彩色吗? - Mark Ransom
马克,我不知道,但马修的评论是答案。 - Kahanu
2个回答

5

也许尝试将像素格式从PixelFormat.Format24bppRgb更改为PixelFormat.Format32bppRgb。您需要额外的8个位来保存Alpha通道。


我猜应该是PixelFormat.Format32bppArgb,而不是PixelFormat.Format32bppRgb。因为根据它的解释注释,这8位未被使用。 - bafsar

3

使用PixelFormat.Format32bppRgb对我来说不起作用。然而有效的方法是在绘制新图像时使用oldImage.PixelFormat。所以相应的代码行变成了:

using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, oldImage.PixelFormat))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接