使用.NET将两个PNG图像组合成一个图像

问题描述:

我在我的应用程序中有两个(实际上很多)PNG(.png)图像。这两处都有透明区域。使用.NET将两个PNG图像组合成一个图像

我想在我的应用程序中将两个图像合并起来,并将结果显示在图片框中。稍后我想通过按钮保存结果。

到目前为止,我设法找到两个图像并将它们结合起来,但它似乎透明的东西不会工作。我的意思是,如果您将一张图片放在另一张图片上,则只有顶部图片可见,因为显然图片的背景是纯白色的框。它不是。

这里有点我的代码:

Dim Result As New Bitmap(96, 128) 
    Dim g As Graphics = Graphics.FromImage(Result) 
    Dim Name As String 
    For Each Name In BasesCheckList.CheckedItems 
     Dim Layer As New Bitmap(resourcesPath & "Bases\" & Name) 
     For x = 0 To Layer.Width - 1 
      For y = 0 To Layer.Height - 1 
       Result.SetPixel(x, y, Layer.GetPixel(x, y)) 
      Next 
     Next 
     Layer = Nothing 
    Next 

resourcesPath是通向我的资源文件夹中。 Bases是其中的一个文件夹。而Name是图片的名称。

我相信你的缩放问题可能与具有不同DPI的图像有关。如果是这种情况,你真的想要DrawImage(),因为它会重新调整图像,以便它们匹配图形对象的DPI。一个警告:如果你没有提供尺寸DrawImage()它与DrawImageUnscaled()出于某种原因做了同样的事情。

Dim result As New Bitmap(96, 128) 

Dim directoryName As String = String.Format("{0}Bases", resourcesPath) 
Using g As Graphics = Graphics.FromImage(result) 
    For Each imageName As String In BasesCheckList.CheckedItems 
     Dim fileName As String = IO.Path.Combine(directoryName, imageName) 
     Using layer As New Bitmap(fileName) 
      g.DrawImage(layer, 0, 0, 96, 128) 
     End Using 
    Next 
End Using 

更详细的讨论是在Xtreme VB Talk论坛上,您决定交叉发布。不要在将来这样做,因为它会增加电线穿过的可能性,每个人都会浪费时间。

问题是您正在尝试手动完成此操作。别。有很多用于绘制图像的库例程,他们知道如何正确处理透明度。

Dim Result As New Bitmap(96, 128) 
Dim g As Graphics = Graphics.FromImage(Result) 
Dim Name As String 
For Each Name In BasesCheckList.CheckedItems 
    Dim Layer As New Bitmap(resourcesPath & "Bases\" & Name) 
    g.DrawImageUnscaled(Layer, 0, 0); 
    Layer = Nothing 
Next 
+0

谢谢,除了一件事之外,它似乎可以工作:我用于预览所得图像的图片框似乎显示图像的“调整大小”版本。最后,我用PictureBox.Image = Result ....我不明白为什么图像显示那样... – Voldemort 2011-01-05 22:22:06

+0

@Omega:您的图像与您正在写入的位图大小相同吗? – 2011-01-05 22:24:48

+0

是的,位图“结果”是96x128,我用来测试的两个位图也是96x128。然而,图片框似乎放大了2的结果... – Voldemort 2011-01-05 22:37:20