如何保存图像文件?

时间:2012-07-29 14:27:15

标签: .net vb.net

我有这段代码:

    Dim myStream As Stream = Nothing
    Dim openFileDialog1 As New OpenFileDialog()

    openFileDialog1.InitialDirectory = "C:\Users\Desktop\Sample Pictures"
    openFileDialog1.Filter = "Pictures|*.jpg|Text|*.txt"

    If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            myStream = openFileDialog1.OpenFile()
            If (myStream IsNot Nothing) Then

              ' Insert code to read the stream here.

            End If
        End Sub
    End Class

我需要将 myStream 中的文件复制到某个目标文件夹。 知道如何实现它吗?

3 个答案:

答案 0 :(得分:1)

你可以使用:

Image img = Image.FromStream(myStream);

Image img = Image.FromFile(path);

而且,除以:

img.Save("new location");

[样品在C#中]

答案 1 :(得分:1)

假设myDestinationDir是您要复制文件的路径,那么

If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then 
    ' Extract the filename part from the full filename returned by openDialog.'
    Dim selectedFile As String = Path.GetFileName(openFileDialog1.FileName)
    ' Append to the destinationDir the filename extracted'
    Dim destFile As String = Path.Combine(myDestinationDir, selectedFile)
    ' Copy with overwrite (if overwrite is not desidered, use the overload with False as 3 arg'
    System.IO.File.Copy(openFileDialog1.FileName, destFile)
End Sub 

这会将所选文件复制到目标文件夹,覆盖具有相同名称的现有文件。

答案 2 :(得分:0)

这是我为一些实验软件编写的真实代码的片段。

    Dim strPath As String
    Dim fStream As FileStream
    Dim fileName As String

    Try
   '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    'Get path from textbox
    strPath = txtSavePath.Text.ToLower

    'Check directory existence, if not, create it
    If Directory.Exists(strPath) Then

    Else
        Try
            Directory.CreateDirectory(strPath)
        Catch ex As Exception

            MessageBox.Show("Error in Creating Directory, Code : " & ex.ToString)
        End Try

    End If

    'Set current active directory
    Directory.SetCurrentDirectory(strPath)

    'Create Filename
    fileName = txtFileName.Text.ToUpper & "_" & DateTime.Now.ToString("yyyyMMdd_HH_mm_ss")


    'Write/Create file
    fStream = File.Open(fileName & ".png", FileMode.Create)
    fStream.Write(byteData, 0, nLength)
    fStream.Close()
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    'Display On Window
        picGraphDisplay.BackgroundImage = Image.FromFile(fileName & ".png")
        txtSavedFileName.Text = fileName & ".png"
    Catch ex As Exception
        CheckVisaStatus(errorStatus)
        MessageBox.Show(ex.ToString)

    End Try

在这种情况下,文件流将图像的字节数据写入文件。从哪里获取字节图像取决于你。在这种情况下,一个好主意是为您的文件使用一个特定的名称,使用系统的DateTime.Now在这里完成。

希望它能给你一些想法。干杯