如何将内存流转换为字符串数组,反之亦然

时间:2014-01-19 11:23:13

标签: vb.net memorystream

我有一个代码,我想从图像中获取流并将内存流转换为字符串数组并存储在变量中。但我的问题是我也想从字符串变量中获取图像并在图片框上绘画。

如果我喜欢这样的话     PictureBox1.Image = image.FromStream(memoryStream) 我可以在图片框上打印图片。但这不是我的需要。我只是想从文件中获取图像流并将流转换为文本并将其存储到某个字符串变量中,我想再次使用字符串变量并将其转换为流以在图片框上打印图像。

这是我的代码。(Vb Express 2008)

 Public Function ImageConversion(ByVal image As System.Drawing.Image) As String
        If image Is Nothing Then Return ""

        Dim memoryStream As System.IO.MemoryStream = New System.IO.MemoryStream
        image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Gif)

        Dim value As String = ""


        For intCnt As Integer = 0 To memoryStream.ToArray.Length - 1
            value = value & memoryStream.ToArray(intCnt) & "  "
        Next

        Dim strAsBytes() As Byte = New System.Text.UTF8Encoding().GetBytes(value)
        Dim ms As New System.IO.MemoryStream(strAsBytes)


        PictureBox1.Image = image.FromStream(ms)

        Return value
    End Function

1 个答案:

答案 0 :(得分:0)

这不会像你发布它的方式那样起作用(至少是重新创建图像的部分)。 见:

Public Function ImageConversion(ByVal image As System.Drawing.Image) As String
    If image Is Nothing Then Return ""

    Dim memoryStream As System.IO.MemoryStream = New System.IO.MemoryStream
    image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Gif)

    Dim value As String = ""

    Dim content As Byte() = memoryStream.ToArray()
    ' instead of repeatingly call memoryStream.ToArray by using
    ' memoryStream.ToArray(intCnt)
    For intCnt As Integer = 0 To content.Length - 1
        value = value & content(intCnt) & "  "
    Next
    value = value.TrimEnd()

    Return value
End Function

要使用创建的字符串重新创建图像,您不能像使用的那样使用Encoding.GetBytes(),因为您将得到一个表示字符串的bytearray。例如“123 32 123”你不会得到一个带有元素123,32,123的字节数组

Public Function ImageConversion(ByVal stringRepOfImage As String) As System.Drawing.Image
    Dim stringBytes As String() = stringRepOfImage.Split(New String() {" "}, StringSplitOptions.RemoveEmptyEntries)
    Dim bytes As New List(Of Byte)
    For intCount = 0 To stringBytes.Length - 1
        Dim b As Byte
        If Byte.TryParse(stringBytes(intCount), b) Then
            bytes.Add(b)
        Else
            Throw new FormatException("Not a byte value")
        End If
    Next
    Dim ms As New System.IO.MemoryStream(bytes.ToArray)
    Return Image.FromStream(ms)
End Function

参考:Byte.TryParse