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#?

StealthRT
  • 10,108
  • 40
  • 183
  • 342

2 Answers2

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)

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));
Community
  • 1
  • 1
Ian
  • 30,182
  • 19
  • 69
  • 107
  • @StealthRT also, check this out tho convert the image to base 64: http://stackoverflow.com/questions/10889764/how-to-convert-bitmap-to-a-base64-string http://stackoverflow.com/questions/17874733/converting-image-to-base64 – Ian Feb 22 '16 at 16:01