このような同様の質問がさまざまなフォーラムで行われていることは知っていますが、与えられた解決策のどれも私にはうまくいきませんでした。私は基本的に、同じネットワーク上の2台のコンピューター間でTCPを介してファイル(イメージ)を送信しようとしています。私は画像をバイト配列に変換し、次に文字列を送信する前に文字列に変換しようとしています。反対側では、文字列を受け取り、バイト配列に変換してから、画像に変換し直しました。ただし、受信側では文字列が空であるため、それをバイト配列に変換するとエラーが発生します。
送信側のコードは次のとおりです。
Private Sub startSending()
Dim ScreenShot As Image = sc.CaptureScreen
Dim path As String = My.Computer.FileSystem.SpecialDirectories.CurrentUserApplicationData + "\redsquirimgtest"
sc.CaptureScreenToFile(path, System.Drawing.Imaging.ImageFormat.Jpeg)
MsgBox("printscreen saved")
Dim abyt() As Byte = ConvertImageFiletoBytes(path)
MsgBox("image converted to byte array")
Dim str As String = byteArrToString(abyt)
MsgBox(str)
client.Connect("192.168.1.10", 55000)
Dim Writer As New StreamWriter(client.GetStream())
Writer.Write(str)
Writer.Flush()
MsgBox("sent")
Form2.PictureBox1.Image = ScreenShot
Form2.Show()
MsgBox("done")
End Sub
Public Function ConvertImageFiletoBytes(ByVal ImageFilePath As String) As Byte()
Dim _tempByte() As Byte = Nothing
If String.IsNullOrEmpty(ImageFilePath) = True Then
Throw New ArgumentNullException("Image File Name Cannot be Null or Empty", "ImageFilePath")
Return Nothing
End If
Try
Dim _fileInfo As New IO.FileInfo(ImageFilePath)
Dim _NumBytes As Long = _fileInfo.Length
Dim _FStream As New IO.FileStream(ImageFilePath, IO.FileMode.Open, IO.FileAccess.Read)
Dim _BinaryReader As New IO.BinaryReader(_FStream)
_tempByte = _BinaryReader.ReadBytes(Convert.ToInt32(_NumBytes))
_fileInfo = Nothing
_NumBytes = 0
_FStream.Close()
_FStream.Dispose()
_BinaryReader.Close()
Return _tempByte
Catch ex As Exception
Return Nothing
End Try
End Function
Public Function byteArrToString(ByVal arr() As Byte) As String
Return System.Text.Encoding.Unicode.GetString(arr)
End Function
そして、受信側:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
' Check the TcpListner Pending Property
If TcpListener.Pending = True Then
Dim Message As String = ""
ConnectClient = TcpListener.AcceptTcpClient()
MsgBox("accepting")
Dim Reader As New StreamReader(ConnectClient.GetStream())
While Reader.Peek > -1
Message = Message + Reader.Read().ToString
End While
MsgBox(Message)
Dim abyt() As Byte = StrToByteArray(Message)
MsgBox("string converted to byte array")
Dim img As Image = ConvertBytesToImageFile(abyt)
MsgBox("byte array converted to image")
PictureBox1.Image = img
MsgBox("picture loaded in form")
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
TcpListener.Start()
End Sub
Public Function ConvertBytesToImageFile(ByVal ImageData As Byte()) As Image
Dim myImage As Image
Dim ms As System.IO.Stream = New System.IO.MemoryStream(ImageData)
myImage = System.Drawing.Image.FromStream(ms)
Return myImage
End Function
Public Shared Function StrToByteArray(str As String) As Byte()
Return System.Text.Encoding.Unicode.GetBytes(str)
End Function
あなたが与えることができるどんな助けにも前もって感謝します!