Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Stream to byte[] array always returns 0 length in windows phone 8 C#

I have a Stream received from a PhotoResult of photoChooserTask_Completed(object sender, PhotoResult e) event handler.

The e.ChosenPhoto itself a Stream so I assign it to Stream stream. And I converted it to byte[] array using the method below:

    public static byte[] ReadImageFile2(Stream mystream)
    {
        // The mystream.length is still full here.
        byte[] imageData = null;
        using (BinaryReader br = new BinaryReader(mystream))
        {
            imageData = br.ReadBytes(Convert.ToInt32(mystream.Length));
        }
        // But imageData.length is 0
        return imageData;
    }

I don't know what is wrong with the BinaryReader, it returns imageData with just 0 length. Tried to cast type as br.ReadBytes((int)mystream.Length) but still doesn't work.

Also tried all of the answers in Creating a byte array from a stream but still not working. Maybe my e.ChosenPhoto cannot be used as a normal Stream.

Thank you.

like image 905
Tran Hoai Nam Avatar asked Apr 19 '15 11:04

Tran Hoai Nam


People also ask

What is used to convert stream of bytes to object?

The readObject method is called by Java, when a stream of byte is deserialized to Java object. This time, output will be updated based on the current year. Conclusively serialization is the process of converting an object into stream of bytes. The converted byte stream can be used for multiple purposes.

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

What is the correct way to convert a byte into long object?

The BigInteger class has a longValue() method to convert a byte array to a long value: long value = new BigInteger(bytes). longValue(); Java.


1 Answers

According to the docs, you may have to set the position of the stream to 0 before reading it:

using (BinaryReader br = new BinaryReader(mystream))
{
    mystream.Position = 0;
    imageData = br.ReadBytes(Convert.ToInt32(mystream.Length));
}
like image 52
Grant Winney Avatar answered Sep 26 '22 01:09

Grant Winney