1

Hey all I have the following VB.net code that I need converted to C#:

 Dim tClient As WebClient = New WebClient Dim imgLink As String = "\\the\path\photos\" + userID + ".jpg" Dim tImage As Bitmap = Bitmap.FromStream(New MemoryStream(tClient.DownloadData(imgLink))) Dim mImage As String = ImageToBase64(tImage, System.Drawing.Imaging.ImageFormat.Jpeg) 

That works just fine in VB but when I try to convert it to C#:

WebClient tClient = new WebClient(); string mImage = @"\\the\path\photos\" + userID + ".jpg"; Bitmap tImage = Bitmap.FromStream[new MemoryStream[tClient.DownloadData(mImage)]]; mImage = ImageToBase64(tImage, System.Drawing.Imaging.ImageFormat.Jpeg); 

It has an error on tClient.DownloadData(imagePath) saying:

Error 7 Cannot implicitly convert type 'byte[]' to 'int'

What's the proper way to define this in C#?

2 Answers 2

3

There's a few issues:

  • You've mixed up the array operator bracket [ with function call ( bracket in Bitmap.FromStream and MemoryStream constructor
  • You're downloading entire file at once, only to load it into a stream - that defeats the purpose of streaming
  • Bitmap.FromStream actually comes from it's superclass, Image, and returns an Image (you have no guarantee the file will be an actual bitmap, not some other format - if you're sure of it, you'll have to cast it to Bitmap)

Try this:

WebClient tClient = new WebClient(); string mImage = @"\\the\path\photos\" + userID + ".jpg"; Bitmap tImage = (Bitmap)Bitmap.FromStream(tClient.OpenRead(mImage)); mImage = ImageToBase64(tImage, System.Drawing.Imaging.ImageFormat.Jpeg); 

WebClient.OpenRead returns a stream you can pass straight to construct an image (without pulling all the data to a byte array)

Sign up to request clarification or add additional context in comments.

1 Comment

Nice! That did the trick. Thanks for the help and also welcome to Stackoverflow! :o)
1

Don't use square bracket. But use bracket and declare a new Bitmap

WebClient tClient = new WebClient(); string mImage = @"\\the\path\photos\" + userID + ".jpg"; Bitmap tImage = new Bitmap(Bitmap.FromStream(new MemoryStream(tClient.DownloadData(mImage)))); 

And note that to convert the image to base 64 requires your byte[], which you might as well take from the tClient.DownloadData(mImage)

mImage = Convert.ToBase64String(tClient.DownloadData(mImage)); 

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.