我正在尝试将压缩位图添加为另一个可执行文件的资源,但遇到了错误。错误是:
Value of type 'System.Drawing.Bitmap' cannot be converted to '1-dimensional array of System.Drawing.Bitmap'
这是我的伪代码:
模块 1:
Imports System.Runtime.InteropServices
Module ResourceWriter
Private Function ToPtr(ByVal data As Object) As IntPtr
Dim h As GCHandle = GCHandle.Alloc(data, GCHandleType.Pinned)
Dim ptr As IntPtr
Try
ptr = h.AddrOfPinnedObject()
Finally
h.Free()
End Try
Return ptr
End Function
<DllImport("kernel32.dll", SetLastError:=True)> _
Private Function UpdateResource(ByVal hUpdate As IntPtr, ByVal lpType As String, ByVal lpName As String, ByVal wLanguage As UShort, ByVal lpData As IntPtr, ByVal cbData As UInteger) As Boolean
End Function
<DllImport("kernel32.dll", SetLastError:=True)> _
Private Function BeginUpdateResource(ByVal pFileName As String, <MarshalAs(UnmanagedType.Bool)> ByVal bDeleteExistingResources As Boolean) As IntPtr
End Function
<DllImport("kernel32.dll", SetLastError:=True)> _
Private Function EndUpdateResource(ByVal hUpdate As IntPtr, ByVal fDiscard As Boolean) As Boolean
End Function
Public Function WriteResource(ByVal filename As String, ByVal bmp As Bitmap()) As Boolean
Try
Dim handle As IntPtr = BeginUpdateResource(filename, False)
Dim file1 As Bitmap() = bmp
Dim fileptr As IntPtr = ToPtr(file1)
Dim res As Boolean = UpdateResource(handle, "BitMaps", "0", 0, fileptr, Convert.ToUInt32(file1.Length))
EndUpdateResource(handle, False)
Catch ex As Exception
Return False
End Try
Return True
End Function
End Module
在窗体中,在按钮下:
'...here's code to compress the image, commented out for now
Dim bmp1 As Bitmap = Compressed
WriteResource("C:UsersAdminDesktopTestfile.exe", bmp1)
但它不起作用。我应该对模块或按钮下的代码进行哪些更改?我看到我应该在将图像放入资源之前将System.Drawing.Bitmap转换为一维数组,但是如何呢?
任何帮助都非常感谢:)
编辑:
我现在已经尝试了从谷歌和MSDN找到的所有答案,但我无法弄清楚。因此,如果有人能展示如何做到这一点,我将不胜感激。这是我尝试过的方法之一。
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'...
Dim bmp1 As Bitmap = Compressed
Dim Converted = ConvertToByteArray(bmp1)
WriteResource("C:UsersAdminDesktopTestfile.exe", Converted)
End Sub
Public Shared Function ConvertToByteArray(ByVal value As Bitmap) As Byte()
Dim bitmapBytes As Byte()
Using stream As New System.IO.MemoryStream
value.Save(stream, value.RawFormat)
bitmapBytes = stream.ToArray
End Using
Return bitmapBytes
End Function
是的,我在模块 1 中将 Bitmap() 更改为 Byte();但它在运行时返回了"Value cannot be NULL"
。
我还尝试将其保存为IO.MemoryStream
然后转换为字节,但没有成功。
因此,如果有人能告诉我如何做到这一点,那就太好了。
通过将 () 放在此处的类型名称后,将参数声明为位图数组:
Public Function WriteResource(ByVal filename As String, ByVal bmp As Bitmap()) As Boolean
如果您不希望它是一个数组,请删除 ():
Public Function WriteResource(ByVal filename As String, ByVal bmp As Bitmap) As Boolean
你遇到的第一个问题在Ryan的回答中得到了很好的解决(Dim file1 As Bitmap() = bmp
也是错误的);第二个问题是你掩盖了一个不同的问题。
如果您参考 MSDN 上的 UpdateResource,您将看到cbdata
是要写入的字节数,即位图的字节数。 您的代码正在传递数组的大小。 此外,lpData
应该是指向数据的长指针,也是"Note that this is the raw binary data to be stored
"。 您不能像尝试的那样传递位图。
位图类的 save 方法将允许您保存到内存流中,从中可以获取字节和字节计数并将其馈送到 UpdateResource。