Convert image to text file
Hello everybody.
Im busy making a program but it needs to send an image over a connection. Anyways, it is only possible to sends pieces of strings at the moment. And therefore I want to convert the images I want to send into strings or whatever that can be written in a textbox.
Ive been trying stuff with streamreader / write but that didnt work so far.
Thanks in advance.
Any help would be appreciated.
Re: Convert image to text file
If you can get the bytes that represent the image into a Byte array, you can use System.Convert.ToBase64String() to convert the bytes into a string. On the other end, you can use System.Convert.FromBase64String() to decode the string back to bytes. You could also write your own bytes->string encoding technique if you don't like base64 encoding.
I can't tell you how to get the bytes out of the image because you haven't specified whether it's a file on the hard drive or something in memory like the .NET Image class.
Re: Convert image to text file
To continue with what Sitten said, one you get the image bytes back into a byte array, you create a memorystream from the byte array and use that to get your image (image.fromstream method)
Re: Convert image to text file
Here's a small example assuming Image.FromFile. You should be able to change it up easily if you've already got a stream though.
Code:
Imports System.Drawing.Imaging
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles MyBase.Load
Dim img As Image = Image.FromFile("C:\Temp\cupofcoffee.jpg")
Dim str = ImageToBase64(img, ImageFormat.Jpeg)
Dim imgFromString = Base64ToImage(str)
PictureBox1.Image = imgFromString
End Sub
Public Function ImageToBase64(ByVal img As Image,
ByVal fmt As System.Drawing.Imaging.ImageFormat) As String
Using ms As New IO.MemoryStream()
img.Save(ms, fmt)
Dim b = ms.ToArray()
Return Convert.ToBase64String(b)
End Using
End Function
Public Function Base64ToImage(ByVal s As String) As Image
Dim b = Convert.FromBase64String(s)
Using ms As New IO.MemoryStream(b, 0, b.Length)
ms.Write(b, 0, b.Length)
Return Image.FromStream(ms, True)
End Using
End Function
End Class
Re: Convert image to text file
I love you guys you guys are soo awesome, actually the image can be Anywhere, I chose wherever I want it to be, But thank you guys so much this was soo useful.
Im currently busy make a multi-user chat client which works 100% smooth but I wanted to add the option of sharing an image. And this isnt possible because my client only support strings to be send at the moment,