none
C# Stream.Copyto相关问题 RRS feed

  • 问题

  • 我获取一个图片流,然后想赋值给BitmapImage变量用于绑定。

    发现用以下代码,直接赋值是无效的

    MemoryStream ms = new MemoryStream();
    Stream responseStream = GetSteamResponse(url);
    responseStream.CopyTo(ms);
    BitmapImage image = new BitmapImage();
    image.BeginInit();
    image.StreamSource = ms;
    image.EndInit();
    return image;

    需要先把流转成字节数组,然后再用这个数组new一个新的MemeryStream赋值才能成功

    MemoryStream ms = new MemoryStream();
    Stream responseStream = GetSteamResponse(url);
    responseStream.CopyTo(ms);
    byte[] bytes = ms.GetBuffer();
    ms.Close();
    BitmapImage image = new BitmapImage();
    image.BeginInit();
    image.StreamSource = new MemoryStream(bytes);
    image.EndInit();
    return image;

    copyto的流和new出来的有什么区别,为什么会造成这种情况?


    2018年4月24日 5:03

全部回复

  • 你好,

    可以直接赋值的,不过需要把memory.Position 设为0, 下面的代码,你可以参考一下。

    using (MemoryStream memory = new MemoryStream())
                {
                    Stream stream = GetSteamResponse(url);
                    stream.CopyTo(memory);
                    BitmapImage bitmapimage = new BitmapImage();
                    stream.Close();
                    memory.Position = 0;
                    bitmapimage.BeginInit();
                    bitmapimage.CacheOption = BitmapCacheOption.OnLoad;
                    bitmapimage.StreamSource = memory;
                    bitmapimage.EndInit();
                    return bitmapimage;
     }

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • 已建议为答案 Lee Liu 2018年4月24日 7:47
    2018年4月24日 7:42
    版主