Thought
Thought

Reputation: 5846

Converting binary image data received from a webservice to a byte[]

in a 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 the responseData contains something like this: enter image description here

the image gets created but its corrupt , i can't open it i assume this

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

does't work

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

EDIT:

i ended up doing 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);

Upvotes: 3

Views: 4118

Answers (2)

Alex
Alex

Reputation: 21766

You want to read the data into a stream first rather than reading 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);

Upvotes: 2

Gayan
Gayan

Reputation: 2871

Try this

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 could use

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

Upvotes: 0

Related Questions