c# – 如何保持png透明度?

前端之家收集整理的这篇文章主要介绍了c# – 如何保持png透明度?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我创建了一个函数,允许上传的透明.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透明度,我需要做些什么?请举例说明.我真的不是图像处理方面的专家.

谢谢.

解决方法

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

猜你在找的C#相关文章