将 PNG 文件从资源复制到本地文件夹

Copy a PNG file from the Resources to a local folder

我正在为应用程序创建安装程序,但在将 PNG 文件从我的资源复制到本地文件夹时遇到问题。

我尝试了 File.CopyFile.WriteAllBytes() 等常用方法,但似乎没有任何效果。我只得到错误:

bitmap cannot be converted to Byte()

If System.IO.File.Exists(FileFolderOther & "\LogoReport.png") = False Then
    File.Copy(My.Resources.Logo_Reports, FileFolderOther & "\LogoReport.png", True)
End If

If System.IO.File.Exists(FileFolderOther & "\LogoReport.png") = False Then
    File.WriteAllBytes(FileFolderOther & "\LogoReport.png", My.Resources.Logo_Reports)
End If

我只想将文件(PNG、TXT 等)从 My.Resources 复制到本地文件夹。

My.Resources.[SomeImage] returns 一个图像对象。

您可以使用Image.Save方法将图像保存到光盘:

Dim destinationPath = Path.Combine(FileFolderOther, "LogoReport.png")
Using myLogo As Bitmap = My.Resources.Logo_Reports
    myLogo.Save("d:\testImage.png", ImageFormat.Png)
End Using

仅当您出于某种原因不想覆盖同名文件时才需要进行 File.Exist() 检查。如果文件存在,将无错覆盖。

Using 语句允许处理由 ResourceManager 工厂创建的图像。如果您需要存储该图像,请将其分配给 Field/Property 并在容器 Form/owner Class 为 closed/disposed.

时将其处理掉

您已对图像类型进行硬编码 (.Png)。
也许那是该位图的正确原始格式。如果您不知道资源图像(或任何其他图像)的类型是什么,并且想保留原始格式,则可以使用 Image.RawFormat.Guid property and determine the correct ImageCodecInfo comparing the Guid with the Codec FormatID [=42 派生用于创建位图的编解码器=].

我正在添加 EncoderParameter,将图像质量设置为 100%

Using myLogo As Bitmap = My.Resources.Logo_Reports
    Dim codec As ImageCodecInfo = ImageCodecInfo.GetImageEncoders().
        FirstOrDefault(Function(enc) enc.FormatID = myLogo.RawFormat.Guid)

    ' Assunimg codec is not nothing, otherwise abort
    Dim fileName = $"LogoReport.{codec.FormatDescription.ToLower()}"
    Dim qualityParam As EncoderParameter = New EncoderParameter(ImageCodec.Quality, 100L)
    Dim codecParms As EncoderParameters = New EncoderParameters(1)
    codecParms.Param(0) = qualityParam

    Dim destinationPath = Path.Combine(FileFolderOther, fileName)
    myLogo.Save(destinationPath, codec, codecParms)
End Using

完成并且我已经正确测试了它,但要知道我在项目文件夹 "Debug\TmpFolder\" 中创建了一个名为 "TmpFolder" 的新文件夹,然后尝试此代码:

Private Sub BtbCopyFromResource_Click(sender As Object, e As EventArgs) Handles BtbCopyFromResource.Click
    Try
        'My.Computer.FileSystem.CurrentDirectory is the function for ===> current Project path, namly to Debug Folder
        My.Resources.LogoReports.Save(My.Computer.FileSystem.CurrentDirectory & "\TmpFolder\db3451.png")
        MsgBox("Done")
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

希望对各位兄弟有所帮助。 ^_^