C# 如何保持png的透明度?
我创建了一个函数,允许将上传的透明.png文件插入SQL Server数据库,并通过HttpHandler在网页上显示 虽然这一切工作,png透明度改变为黑色时,它在网页上查看。有没有办法保持透明度 以下是我的图像服务,它从MVC控制器插入数据库:C# 如何保持png的透明度?,c#,image,png,transparency,C#,Image,Png,Transparency,我创建了一个函数,允许将上传的透明.png文件插入SQL Server数据库,并通过HttpHandler在网页上显示 虽然这一切工作,png透明度改变为黑色时,它在网页上查看。有没有办法保持透明度 以下是我的图像服务,它从MVC控制器插入数据库: public void AddImage(int productId, string caption, byte[] bytesOriginal) { string jpgpattern = ".jpg|.JPG"; string p
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通道。使用像素格式。Format32bppRgb对我不起作用。但是,在绘制新图像时使用oldImage.PixelFormat是有效的。因此相应的代码行变成:
using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, oldImage.PixelFormat))
尝试使用
Format32bppArgb
来保留alpha(即“A”)。请避免在问题标题前加上“C”或类似的前缀。这就是标签的用途。你知道你原来的.png是8位还是全彩的吗?Matthew,没错!谢谢。马克,我不知道,但马修的评论是答案。我想一定是PixelFormat.Format32bppArgb,而不是PixelFormat.Format32bppRgb。因为根据它的解释性评论,8位没有被使用。