我有一个代码,我想从图像中获取一个流,并将内存流转换为字符串数组并存储在一个变量中。但我的问题是,我也希望从字符串变量中获取图像,并在图片框上进行绘制。
如果我像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发布于 2014-01-19 14:15:54
这不会像你发布的方式那样工作(至少是重新创建图片的一部分)。见此:
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(),因为您将得到一个表示字符串的字节数组。例如,"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
https://stackoverflow.com/questions/21216095
复制相似问题