fox
fox

Reputation: 45

Why does File size differ after using WebClient UploadData?

What I have works regarding uploading an Image file to a ftp site by converting it to Byte() The image-file is valid and can be opened and displayed by a picture-viewer. But strangely the file size is different after uploading it.

Do you know why and how to get around this.

Please note: For testing purposes I use a local file, therefore I realized about that. Later it is meant to transfer screenshot image-data. Thats the reason why I don't use UploadFile Method.

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Dim ByteImage As Byte() = ImageToByteArray(GetImage("C:\Users\Andi\Desktop\en_FbqiUtfBuB.png"), System.Drawing.Imaging.ImageFormat.Png)

    ' Post image to upload handler
    Using myWebClient As New WebClient()
        myWebClient.Credentials = New Net.NetworkCredential("myUser", "mySecret")
        Dim response() As Byte = myWebClient.UploadData("ftp://0815.test-my-website.de/htdocs/_dl/__Test-Upload.png", ByteImage)
    End Using
End Sub

Private Function GetImage(ByVal filePath As String) As System.Drawing.Image
    Dim l_WebClient As New WebClient()
    Dim l_imageBytes() As Byte = l_WebClient.DownloadData(filePath)
    Dim l_stream As New System.IO.MemoryStream(l_imageBytes)
    Return Image.FromStream(l_stream)
End Function

Private Function ImageToByteArray(ByVal image As System.Drawing.Image,
     ByVal format As System.Drawing.Imaging.ImageFormat) As Byte()
    Using ms As New System.IO.MemoryStream()
        ' Convert Image to byte()
        image.Save(ms, format)
        Dim imageBytes() As Byte = ms.ToArray()
        Return imageBytes
    End Using
End Function

That works pretty well except that the file written through the Byte array is not the same as the original.

Upvotes: 1

Views: 86

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89489

You're decoding and re-encoding the image. Just read the file with File.ReadAllBytes(string)

Dim ByteImage As Byte() = System.IO.File.ReadAllBytes("C:\Users\Andi\Desktop\en_FbqiUtfBuB.png")

Upvotes: 4

Related Questions