首页 文章

从Silverlight到WCF的映像文件

提问于
浏览
1

我正在尝试使用WCF服务将照片从Silverlight客户端上传到服务器 .

客户端调用的方法是void UpdatePicture(Stream image);客户端的这个方法,显示为UpdatePicture(byte []数组),所以我创建了一个转换器(输入流是来自OpenFileDialog.File.OpenRead()的FileStream)

private byte[] StreamToByteArray(Stream stream)
    {
        byte[] array = new byte[stream.Length];
        stream.Read(array, 0, array.Length);
        return array;
    }

转换器似乎运行良好 .

在WCF方面,我必须将流保存到文件中 . 我用这个:

public void UpdatePicture(Stream image)
    {
        if (SelectedUser == null)
            return;
        if (File.Exists(image_path + SelectedUser.sAMAccountName + ".jpg"))
        {
            File.Delete(image_path + SelectedUser.sAMAccountName + ".jpg");
        }

        using (FileStream file = File.Create(image_path + SelectedUser.sAMAccountName + ".jpg"))
        {
            DataManagement.CopyStream(image, file);
        }
    }

要将Stream复制到FileStream,我使用:

public static void CopyStream(Stream input, Stream output)
    {
        byte[] buffer = new byte[8 * 1024];
        int len;
        while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write(buffer, 0, len);
        }
    }

文件按预期创建,大小合适,但PhotoViewer不显示任何其他程序的图像 .

有人知道为什么吗?任何帮助将非常感激:)

编辑:

有点奇怪:

我创建了一个WCF方法GetWCFBytes(byte [] array),它返回参数而不做任何事情 . 如果使用StreamToByteArray将流作为字节数组传递给此方法,并通过带有MemoryStream的BitmapImage将结果设置为Image,则会显示空白图像 .

如果我接受OpenFileDialog的流,将其转换为字节数组,从该数组创建一个新的MemoryStream,并用它设置我的BitmapImage:图像没问题 .

WCF是否对流和字节数组使用了一些魔法?

2 回答

  • 1

    我找到了答案,它确实与WCF无关!

    问题是我在我的ViewModel中的确认按钮上转换了我的OpenFileDialog结果 . 我不知道为什么但如果我在调用openfiledialog的方法中进行转换,则字节数组不会被破坏并且一切正常 .

    谢谢 .

  • 0

    你的 CopyStream 方法确保继续读取输入流,直到它没有得到更多 . 您的 StreamToByteArray 方法不会在客户端上转换整个流,而不仅仅是前面的0个字节后跟零?

    private byte[] StreamToByteArray(Stream stream)
    {
        byte[] array = new byte[stream.Length];
        int index = 0, length = 0;
        while ((length = stream.Read(array, index, array.Length - index)) > 0)
        {
            index += length;
        }
    
        return array;
    }
    

相关问题