Convert Binary Image Data Received from Web Service to Byte []

in windows store app project i have this method

private async void getUSerImage()
    {
        try
        {

            using (var httpClient = new HttpClient { BaseAddress = Constants.baseAddress })
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", App.Current.Resources["token"] as string);

                using (var response = await httpClient.GetAsync("user/image"))
                {
                    string responseData = await response.Content.ReadAsStringAsync();
                    byte[] bytes = Encoding.Unicode.GetBytes(responseData);

                    StorageFile sampleFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("userImage.jpg", CreationCollisionOption.ReplaceExisting);
                    await FileIO.WriteBytesAsync(sampleFile, bytes);
                    var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.Read);

                }
            }
        }
        catch (Exception e)
        {
            Debug.WriteLine(e.Message);
        }
    }

      

im trying to convert the binary data received to bytes and save it as a file this is what responseData contains something like this: enter image description here

the image is created but it is corrupt, I cannot open it. I guess it is

byte[] bytes = Encoding.Unicode.GetBytes(responseData);

      

does not work

The webservice documentation says that "Body contains binary image data" is there a better way to convert the binary data im receiving to bytes and save it to a file?

EDIT:

I finished this and it worked

Stream imageStream = await response.Content.ReadAsStreamAsync();
                    byte[] bytes = new byte[imageStream.Length];

                    imageStream.Read(bytes, 0, (int)imageStream.Length);


                    StorageFile sampleFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("userImage.jpg", CreationCollisionOption.ReplaceExisting);
                    await FileIO.WriteBytesAsync(sampleFile, bytes);
                    var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.Read);

      

+3


source to share


2 answers


You want to read the data in the stream first, not read it as a string:



Stream imageStream= await response.Content.GetStreamAsync(theURI);
var image = System.Drawing.Image.FromStream(imageStream);
image.Save(context.Response.OutputStream, ImageFormat.Jpeg);

      

+2


source


try it

context.Response.ContentType = "image/jpeg";

// Get the stream 

var image = System.Drawing.Image.FromStream(stream);
image.Save(context.Response.OutputStream, ImageFormat.Jpeg);

      



if you want to show the image instead of saving, you can use

$('img')[0].src = 'Home/getUSerImage' // what ever image url

      

0


source







All Articles