none
关于将MemoryStream赋给BitmapImage的StreamSource RRS feed

  • 问题

  • 我先从FTP上获取一个图像的文件流,并写入内存中

    FtpWebResponse myResponse = (FtpWebResponse)reqFTP.GetResponse();
    Stream myFTP_Stream = myResponse.GetResponseStream();
    MemoryStream myMS = new MemoryStream((int)myFileSize);
    int myBufferSize = 2048;
    int myReadCount;
    byte[] myBuffer = new byte[myBufferSize];

    myReadCount = myFTP_Stream.Read(myBuffer, 0, myBufferSize);
    while (myReadCount > 0)
    {
        myMS.Write(myBuffer, 0, myReadCount);
        myReadCount = myFTP_Stream.Read(myBuffer, 0, myBufferSize);
    }

    return myMS;

    然后把myMS赋给BitmapImage的StreamSource

    BitmapImage myBI = new BitmapImage();
    myBI.BeginInit();
    myBI.StreamSource = myStream;
    myBI.EndInit();

    return new Image()
    {
        Stretch = Stretch.Uniform,
         Source = myBI2
    };//程序不会报错,但是Image显示不了图片

    但是如果把myMS保存为文件是没有问题的
    从保存的文件读取到内存中,再赋值给BitmapImage的StreamSource也是没有问题的

    BinaryReader myBR = new BinaryReader(File.Open(myLocalFullName, FileMode.Open));
    FileInfo myFI = new FileInfo(myLocalFullName);
    byte[] myBytes = myBR.ReadBytes((int)myFI.Length);
    myBR.Close();
    MemoryStream myMS2 = new MemoryStream(myBytes);

    BitmapImage myBI2 = new BitmapImage();
    myBI2.BeginInit();
    myBI2.StreamSource = myMS2;
    myBI2.EndInit();

    比较myMS和myMS2后发现居然是一样

    myMS2.Position = 0;
    myMS.Position = 0;
    int myCount1 = 4;

    byte[] myBuffer1 = new byte[myCount1];
    byte[] myBuffer2 = new byte[myCount1];

    bool myBool = true;
    int myReadCount1 = 1;
    int myReadCount2 = 1;
    while(myBool && (myReadCount1 > 0 && myReadCount2 > 0))
    {
        myReadCount1 = myMS2.Read(myBuffer1, 0, myCount1);
        myReadCount2 = myMS.Read(myBuffer2, 0, myCount1);
        for (int i = 0; i < myCount1; i++)
        {
            if (myBuffer1[i] != myBuffer2[i])
            {
                myBool = false;
                break;
            }
       }
    }
    //myBool结果为True

    请问,直接把内存里的数据赋给BitmapImage的StreamSource有什么问题吗?

    2017年9月18日 1:17

全部回复

  • 已解决,我SB了
    2017年9月18日 8:27
  • Hi superkuang,

    我很高兴知道你解决了 如果您可以通过分享你的解决方案标记为答案来关闭线程,将不胜感激。 如果面对类似的问题,这将有助于其他成员快速找到解决方案。

    Best Regards,

    Yohann Lu


    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.

    2017年9月19日 2:09
    版主