【发布时间】:2013-10-15 15:18:56
【问题描述】:
我正在尝试将压缩位图添加为另一个可执行文件的资源,但遇到了错误。错误是:
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 转换为 1 维数组,但是如何?
非常感谢任何帮助:)
编辑:
我现在已经尝试了从 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,然后转换为字节,但没有成功。
所以如果任何人可以告诉我如何做到这一点,那就太好了。
【问题讨论】:
-
如果你想写一个位图,你为什么要把它们的数组传递给 WriteResource?
-
究竟是什么错误?将鼠标悬停在位图字节上-它有多大(或检查返回)...您是否更改了 WriteResource 中
UpdateResource的参数?我想我知道出了什么问题,但是Didn't success对于通过 cmets 进行调试非常模糊
标签: arrays vb.net bitmap resources