我正在尝试将压缩位图添加为另一个可执行文件的资源,但遇到了错误。错误是:
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:\Users\Admin\Desktop\Testfile.exe", bmp1)
但它不起作用。我应该对模块或按钮下的代码进行哪些更改?我看到我应该在将图像放入资源之前将System.Drawing.Bitmap转换为一维数组,但是如何?
任何帮助深表感谢 :)
编辑:
我现在已经尝试了从 google 和 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:\Users\Admin\Desktop\Testfile.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
是的,我在 Module1 处将 Bitmap() 更改为 Byte();但它"Value cannot be NULL"
在运行时返回。
我也尝试将其另存为IO.MemoryStream
然后转换为字节但没有成功。
因此,如果有人能告诉我如何做到这一点,那就太好了。