加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:19:32 所属栏目:百科 来源:网络整理
导读:我创建了一个函数,允许上传的透明.png文件插入到SQL Server数据库中,并通过HttpHandler显示在网页上. 虽然这一切都有效,但是当在网页上查看时,png透明度会变为黑色.有没有办法保持透明度? 这是我从MVC控制器插入数据库的图像服务: public void AddImage(in
我创建了一个函数,允许上传的透明.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通道.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读