Combining two PNG images into one image using .NET

狂风中的少年 提交于 2019-12-22 18:15:09

问题


I have two (actually many) PNG (.png) images in my application. Both have transparent areas here and there.

I want, in my application, to take both images, combine them, and display the result in a picture box. Later I want to save the result through a button.

So far I managed to find the two images and combine them, but it seems the transparency thing won't work. I mean, if you put one image over another, only the top image is visible as the result because, apparently, the image's background is a plain white box. Which it is not.

Here is a bit of my code:

    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 is the path to my resources folder. Bases is a folder in it. And Name is the image's name.


回答1:


I believe your scaling problems are possibly related to the images having a different DPI. If this is the case, you really want DrawImage() because it will rescale images so they match the DPI of the Graphics object. One caveat: if you don't provide a size to DrawImage() it does the same thing as DrawImageUnscaled() for some reason.

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

More detailed discussion is at the Xtreme VB Talk forum, where you decided to cross-post. Don't do that in the future as it increases the probability that wires will get crossed and everyone will waste time.




回答2:


The problem is you're trying to do this by hand. Don't. There are plenty of library routines for drawing images, and they know how to handle transparency properly.

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


来源:https://stackoverflow.com/questions/4609478/combining-two-png-images-into-one-image-using-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!