对于我当前的 WPF 应用程序,我必须缩小一些 System.Drawing.Image
(我从 PNG 文件加载的对象(其中一些具有透明背景)。我已经尝试了多种方法调整图像的大小,并且所有这些都在之后有一个较小的图像方面工作得很好。但不幸的是,它们都使图像失去了透明度。
我最后的尝试是使用 ImageResizer 一个外部库来完成工作,因为我希望它能轻松处理这个问题,但我仍然遇到同样的问题:原始图像以透明背景显示;显示的调整大小的图像以黑色背景显示。
这是我使用 ImageResizer 库的代码:
ImageResizer.Instructions inst = new ImageResizer.Instructions("width=" + newWidth.ToString() + ";height=" + newHeight.ToString() + ";format=png;mode=max");
ImageResizer.ImageJob job = new ImageResizer.ImageJob(originalImage, typeof(System.Drawing.Bitmap), inst);
job.Build();
return job.Result as System.Drawing.Image;
这些是我的另外两种方法,它们基本上也提供了相同的结果(图像调整大小:尚未;透明度保留:否):
return originalImage.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero); // Transparency gets lost
return new System.Drawing.Bitmap(originalImage, new System.Drawing.Size(newWidth, newHeight)); // Transparency gets lost
关于我必须做什么才能在调整大小时保持透明度的任何想法?
问候
拉尔夫
最佳答案
ImageResizer 总是保持透明度。
在图像的编码(或显示)过程中,您正在失去透明度,这发生在您从 ImageResizer 夺走控制权之后。不是传入 typeof(System.Drawing.Bitmap)
,而是传入输出路径或输出流。
var i = new Instructions(){ Width = newWidth,Height = newHeight, OutputFormat= OutputFormat.Png, Mode= FitMode.Max};
new ImageJob(originalImage, "output.png", i).Build();
如果您取而代之的是原始位图,ImageResizer 无法控制图像的编码方式。
您没有具体说明如何使用结果,这一点非常重要。如果您没有将它们写入磁盘或流,而是显示它们,那么您在错误的地方寻找问题。负责将结果合成到显示表面的代码可能无法将图像视为 32 位图像,而是忽略了 alpha channel 。
关于c# - 使用 Image Resizer 调整大小时在 System.Drawing.Image 中丢失透明度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25872283/