以编程方式用白色填充替换图像中的透明区域?
我有一个 PNG 图像,我正在通过 .NET 中的 System.Drawing API 对其进行操作。它有大的透明区域,我想用白色填充替换透明区域,以便图像中没有透明区域。在图像编辑程序中很容易...但到目前为止,我在 C# 中还没有成功做到这一点。
有人可以给我一些指点吗?
I've got a PNG image that I'm operating on via the System.Drawing API in .NET. It has large transparent regions, and I would like to replace the transparent regions with white fill--so that there are no transparent regions in the image. Easy enough in an image editing program... but so far I've had no success doing this in C#.
Can someone give me some pointers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不知道如何检测透明像素。我知道如果 Alpha 为 0,则完全透明,如果为 255,则不透明。我不确定您是否应该检查 Alpha == 0 或 Alpha != 255 ;如果您可以尝试一下并向我提供反馈,这将会有所帮助。
来自 MSDN
I'm not sure how to detect transparent pixel. I know if the Alpha is 0 it's completly transparent and if it's 255 it's opaque. I'm not sure if you should check for Alpha == 0 or Alpha != 255 ; if you can try it and give me a feedback that would be helpful.
From MSDN
我的示例:
这是不同的,因为:
我使用
LockBits
而不是GetPixel
和SetPixel
。它更快,但更难理解。这是一个稍微修改过的示例: MSDN我正在获取真正的 aplha 值正如我在对你的问题的评论中所说的那样。这将使透明度为 50% (128) 的黑色看起来像灰色而不是黑色。原因是“在图形编辑器中用白色替换 alpha”,我想象在填充白色的图像下面创建新图层,然后将两个图层压平在一起。这个例子也会有同样的效果。
My example:
This is different bacause:
I use
LockBits
insteadGetPixel
andSetPixel
. It is much more faster, but little harder to understand. It's a little modified example from : MSDNI'm taking real aplha value into consideration, as I said in the comment to your question. This will make black with 50% transparency (128) look like gray instead of black. Reason for this is by "replace alpha with white in graphics editor" I imagine creating new layer underneath you image filled with white and then flattening both layers together. This example will have same effect.
一旦你有了位图对象的句柄,只需执行以下操作:
Once you have a handle to the bitmap object, just do something like:
这可能过于简化了您的问题,但如果它位于表单或其他现成的控件上,您可以简单地将背景绘制为白色,然后再将图像放置在顶部。
This may be oversimplifying your problem, but if it's on a form or other readily available control, you could simply paint the background White before placing the Image on top.