【问题标题】:Copy a PNG file from the Resources to a local folder将资源中的 PNG 文件复制到本地文件夹
【发布时间】:2019-04-19 13:44:24
【问题描述】:

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

我已经尝试过像File.CopyFile.WriteAllBytes() 这样的常用方法,但似乎没有任何效果。我只得到错误:

位图无法转换为 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 复制到本地文件夹。

【问题讨论】:

    标签: .net vb.net graphics resources gdi+


    【解决方案1】:

    My.Resources.[SomeImage] 返回一个 Image 对象。

    您可以使用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 工厂创建的图像。如果您需要存储该图像,请将其分配给字段/属性并在容器 Form/owner 类关闭/处置时处置它。


    您已硬编码图像类型 (.Png)。
    也许那是该位图的正确原始格式。如果您不知道资源图像(或任何其他图像)的类型,并且希望保留原始格式,则可以使用 Image.RawFormat.Guid 属性派生用于创建位图的编解码器并确定正确的ImageCodecInfo 将 Guid 与 Codec FormatID 属性进行比较。

    我正在添加一个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
    

    【讨论】:

      【解决方案2】:

      它已经完成并且我已经正确地测试了它,但是要知道我在项目文件夹“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
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-10
        • 1970-01-01
        相关资源
        最近更新 更多