Sending Image via UDP

walterf25

Expert
Licensed User
Longtime User
Hello everyone, i need some help figuring out how to receive an image via UDP, i have an application written in visual Basic 2008 running in my computer, i'm actually trying to send a picture and i'm trying to receive on my android phone.

this is the code i have to send the picture from my computer

B4X:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
      
        trasmiUdpHost.Connect(GLOIP, GLOINTPORT)
      
        Dim strReturnData As String
        Dim path As String = "C:\Users\florew1\Pictures\Reyes Creek pictures\Reyes Creek pictures 008.jpg"

        Dim sr As FileStream = New FileStream(path, FileMode.Open, FileAccess.Read)
        Dim bytes() As Byte = New Byte((sr.Length) - 1) {}
        Dim numBytesToRead As Integer = CType(sr.Length, Integer)
        Dim numBytesRead As Integer = 0

        While (numBytesToRead > 0)

            ' Read may return anything from 0 to numBytesToRead.
            Dim n As Integer = sr.Read(bytes, numBytesRead, _
                numBytesToRead)
            ' Break when the end of the file is reached.
            strReturnData = System.Text.Encoding.Unicode.GetString(bytes)   'I know this part i need to change so that it send the bytes instead of a string
            pRet = trasmiUdpHost.Send(bytes, bytes.Length) 'this is the part that sends the bytes read from the picture and it sends it via UDP
            If (n = 0) Then 
                Exit While
            End If
            numBytesRead = (numBytesRead + n)
            numBytesToRead = (numBytesToRead - n)

        End While
        numBytesToRead = bytes.Length

    End Sub

what i need is a way to receive the bytes on my phone and reconstruct the image somehow, i can send a text file but i only receive a portion of the text not all of it, i'm using the
B4X:
Sub UDP_PacketArrived (Packet As UDPPacket)
sub can anyone point me in the right direction please?

thanks,
Walter
 
Last edited:

poseidon

Member
Licensed User
Longtime User
re

here is a similar code I wrote for socket.​

you have to EncodeToBase54 (desktop)
B4X:
http://www.devx.com/vb2themax/Tip/19493

then (android) decode it with
B4X:
Dim helper As StringUtils

helper.DecodeBase64(vbnet_encodebase64_string) 'as result to get bytes

so until now at mob you have the image real bytes to a byte[]

then use something like:
B4X:
Sub GetBitmapFromByteArray(picBuffer() As Byte ) As Bitmap
   Try 
      Dim InputStream1 As InputStream
      InputStream1.InitializeFromBytesArray(picBuffer, 0, picBuffer.Length)

      Dim Bitmap1 As Bitmap
      Bitmap1.Initialize2(InputStream1)

      InputStream1.Close
      
      Return Bitmap1
   Catch 
      Return Null 
   End Try 
End Sub

to convert to bitmap.

final 1line code to show it
B4X:
image.bitmap=GetBitmapFromByteArray(helper.DecodeBase64(vbnet_encodebase64_string))


---------

socket basic example

B4X:
Sub Process_Globals
    Dim AStreams As AsyncStreams
    Dim Socket1 As Socket
End Sub

Sub Activity_Create(FirstTime As Boolean)
   Activity.LoadLayout("main")
End Sub

Sub Button1_Click
    Socket1.Initialize("Socket1")
    Socket1.Connect("10.0.0.136" , 50459, 20000)
End Sub

Sub Socket1_Connected (Successful As Boolean)
    If Successful = False Then
        Msgbox(LastException.Message, "Error connecting")
        Return
    End If
      
       AStreams.Initialize(Socket1.InputStream, Socket1.OutputStream, "AStreams")
   
   'Command to server   
   Dim buffer() As Byte
   Dim ff As String 
   ff="getImage=5"
        buffer = ff.GetBytes("UTF8")
        AStreams.Write(buffer) '--Send
End Sub 

Sub AStreams_NewData (Buffer() As Byte)
    'at your situation you should hold the bytes to a var until receive completed
    'imagine, server can send a picture that is 5mb ah? so this event will be fired multiple times.

    'convert incoming data to string
    Dim msg As String
    msg = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
    ToastMessageShow(msg, False)
End Sub


if no need to send a command to desktop you have to use ServerSocket as explained here by Erel
B4X:
http://www.b4x.com/forum/basic4android-getting-started-tutorials/7669-asyncstreams-tutorial.html#post43578
 
Last edited:
Upvote 0

walterf25

Expert
Licensed User
Longtime User
Hi there Poseidon, first of all thank you very much for your reply, i think this is exactly what i've been looking for, however i'm stuck on something, if you see my code where i'm trying to send the data via UDP, i'm loading the image into a byte array
B4X:
Dim sr As FileStream = New FileStream(path, FileMode.Open, FileAccess.Read)
        Dim bytes() As Byte = New Byte((sr.Length) - 1) {}
        pRet = trasmiUdpHost.Send(sendata, sendata.Length)  'this send the bytes ok if i do it like this.

and the function encodebase64 asks for a string, i'm a little confused here, if the image data is being loaded into a byte array, the encodebase64 function will not work because it asks for a string

B4X:
Private Function EncodeBase64(ByVal input As String) As String
Dim strBytes() As Byte = System.Text.Encoding.UTF8.GetBytes(input)
Return System.Convert.ToBase64String(strBytes)
End Function

how can i deal with this, i guess i'm missing the whole concept, i apologize before hand if this seems like a stupid question.

:sign0085:
 
Last edited:
Upvote 0

walterf25

Expert
Licensed User
Longtime User
Ok, I think i may have figured out the problem on the desktop side, now when i try to decode the received packets i get this error, does anyone know why this is?

B4X:
Sub UDP_PacketArrived (Packet As UDPPacket)
 Dim msg As String

Dim helper As StringUtils
Dim helper1 As String 
msg = BytesToString(Packet.data, Packet.Offset, Packet.Length, "UTF8")
helper1 = helper.DecodeBase64(msg)  ' i get the error here

Compiling code. 0.02
Compiling layouts code. 0.01
Generating R file. 0.00
Compiling generated Java code. Error
B4A line: 250
helper1 = helper.DecodeBase64(msg)
javac 1.6.0_29
src\com\dandre\dev\main.java:882: cannot find symbol
symbol : method NumberToString(byte[])
location: class anywheresoftware.b4a.BA
_helper1 = BA.NumberToString(_helper.DecodeBase64(_msg));Debug.locals.put("helper1", _helper1);
^
1 error

this is the error

thanks everyone!!!!

walter
 
Upvote 0

walterf25

Expert
Licensed User
Longtime User
Help i'm so close

Ok, i've figured out most of the issues, now i'm getting a bitmap should first be initialized error in the GetBitmapFromByteArray function

B4X:
Sub GetBitmapFromByteArray(picBuffer() As Byte ) As Bitmap
 Dim Bitmap1 As Bitmap
    Try 
   
        Dim InputStream1 As InputStream
        InputStream1.InitializeFromBytesArray(picBuffer, 0, picBuffer.Length)

       
        Bitmap1.Initialize2(InputStream1)   'it is being initialized here

        InputStream1.Close
        
        Return Bitmap1
    Catch 
        Return Null 
    End Try 
End Sub

any ideas? I'm not sure why it gives me this error.

:sign0085:
 
Upvote 0

walterf25

Expert
Licensed User
Longtime User
Yes

Hi there, yes i figured out how to do this, but it's ben a while i need to go back and look at the code, I will search for it this weekend and will post how I managed to do it.

Cheers,
Walter
 
Upvote 0

oymyakon

Member
Licensed User
Longtime User
Hi,

sorry to bother did you manage to take a look,

I have managed to succeed doing what i want to do in Visual Studio, I now want to send my packets to the device but just cant seem to win!
 
Upvote 0

realblue

Member
Licensed User
Longtime User
Hi everybody,

I just stuck at the same position; image variable gives me the same error.

But after I debugged the problem I found out that actually bytes that I received were all zeroes. So the problem vas on the desktop side.

I dug a lot of solutions and finally below worked for me:

First I converted my image to byte array :

Private Function ImageToByte(ByVal img As Image) As Byte()
Dim imgStream As IO.MemoryStream = New IO.MemoryStream()
img.Save(imgStream, System.Drawing.Imaging.ImageFormat.Jpeg)
imgStream.Close()
Dim byteArray As Byte() = imgStream.ToArray()
imgStream.Dispose()
Return byteArray
End Function

Then I send those bytes to the device.

Hope this will be any help for you.

Happy programming.
 
Upvote 0

NeoTechni

Well-Known Member
Licensed User
Longtime User
B4X:
Sub GetBitmapFromByteArray(picBuffer() As Byte ) As Bitmap
  Try
      Dim InputStream1 As InputStream, Bitmap1 As Bitmap
      InputStream1.InitializeFromBytesArray(picBuffer, 0, picBuffer.Length)
      Bitmap1.Initialize2(InputStream1)
      InputStream1.Close
      Return Bitmap1
  Catch
      Return Null
  End Try
End Sub

Is there a Basic4Android version of GetByteArrayFromBitmap?
 
Upvote 0
Top