Question

public static string GetAvatar()
{
    logger.Info("Start--GetAvatar");//aatif
   // string headerText = "Bearer " + token;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://api.mxit.com/user/public/avatar/id");
    //request.Method = method;
    //request.Headers.Add(HttpRequestHeader.Authorization, headerText);
    //if (contentType != null)
    //{
    //    request.ContentType = contentType;
    //}

    string method = "GET";
    if (method == "GET")
    {
        try
        {
            WebResponse response = request.GetResponse(); // Byte Stream
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            string JsonGET = responseFromServer.ToString();

           // Avatar res = JsonConvert.DeserializeObject<Avatar>(JsonGET);
            reader.Close();
            dataStream.Close();
            response.Close();
            logger.Info("End--GetAvatar");//aatif
            return JsonGET;
        }

        catch (Exception ex)
        {

            logger.Error("CacheData.GetAvatar():" + ex.StackTrace);   /// Aatif 

        }
    }
    logger.Info("End--GetAvatar"); ///aatif
    return null;
}



 string avatar = MURLEngine.GetAvatar();

Showing Image in front end:

  <span id="ProfileImage">
                <img src="data:image/png;base64,@Model.avatarimage" />

            </span>

How do i show the byte stream image on the front end? I am unable to do so right now.

Was it helpful?

Solution

You're close. Convert to base64.

(The other answers don't directly relate to your need for a WebRequest.)

public static string GetAvatar()
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://api.mxit.com/user/public/avatar/vini.katyal");

    WebResponse response = request.GetResponse();
    Stream responseStream = response.GetResponseStream();
    MemoryStream ms = new MemoryStream();

    responseStream.CopyTo(ms);

    byte[] buffer = ms.ToArray();

    string result = Convert.ToBase64String(buffer);

    response.Close();
    responseStream.Close();

    return result;
}

OTHER TIPS

I suggest you create a GET method in your controller which accepts an id of your row or something. Based on that just fetch the byte array and send it back to the as an contentresult. Here is an example for that:

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Image(int id)
{
    byte[] byteArray = _imageRepository.GetImage(id);
    return new FileContentResult(byteArray, "image/jpeg");
}

In the view you can call this controller method in following way:

<img src="Image/1234" alt="Image 1234"/>

Try to use Convert class methods. You can make use of Convert.ToBase64String method to convert a byte array to base64 string representation of the image.

Example from MSDN:

try {
      inFile = new System.IO.FileStream(inputFileName,
                                System.IO.FileMode.Open,
                                System.IO.FileAccess.Read);
      binaryData = new Byte[inFile.Length];
      long bytesRead = inFile.Read(binaryData, 0,
                           (int)inFile.Length);
      inFile.Close();
   }
   catch (System.Exception exp) {
      // Error creating stream or reading from it.
      System.Console.WriteLine("{0}", exp.Message);
      return;
   }

   // Convert the binary input into Base64 UUEncoded output. 
   string base64String;
   try {
       base64String = 
         System.Convert.ToBase64String(binaryData, 
                                0,
                                binaryData.Length);
   }
   catch (System.ArgumentNullException) {
      System.Console.WriteLine("Binary data array is null.");
      return;
   }

Here is another example that I found.

I solved the issue:

            WebResponse response = request.GetResponse();


            byte[] b = null;
            using (Stream stream = response.GetResponseStream())
            using (MemoryStream ms = new MemoryStream())
            {
                int count = 0;
                do
                {
                    byte[] buf = new byte[1024];
                    count = stream.Read(buf, 0, 1024);
                    ms.Write(buf, 0, count);
                } while (stream.CanRead && count > 0);
                b = ms.ToArray();
            }


            return Convert.ToBase64String(b);

I firstly convert the response to Stream and then to Byte array then to the base64 string

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top