简体   繁体   English

在Windows通用应用程序C中流式传输图像

[英]streaming images in windows universal apps c#

The classes i used in c# to stream videos over the net in c# are not accepted in windows universal apps. Windows通用应用程序不接受我在C#中用于在C#中通过网络流式传输视频的类。 So please can someone tell me how to create bitmap convert it to byte[] send it over socket and convert it back to bit map. 因此,请有人告诉我如何创建位图将其转换为byte []通过套接字发送并将其转换回位图。 First of all c# in universal apps is not even recognizing the variable type bitmap. 首先,通用应用程序中的c#甚至无法识别变量类型位图。 it does n't even recognize name space system.drawing. 它甚至不识别名称空间system.drawing。 thanks 谢谢

  1. Base64 to Bitmap Base64到位图

     string base64string=""; var fileStream = Base64ToStream(base64string); var memStream = new MemoryStream(); await fileStream.CopyToAsync(memStream); memStream.Position = 0; var bitmap = new BitmapImage(); bitmap.SetSource(memStream.AsRandomAccessStream()); lstBitImages.Insert(0, new PhotoModel(bitmap, "00", objPhoto.PhotoName, objPhoto.PhotoBase64, objPhoto.PhotoType, objPhoto.PhotoLink, ".jpg", "Visible", "Collapsed")); displayphotolst.Add(objPhoto); PhotoList.ItemsSource = lstBitImages; 

Base64ToStream(base64string); Base64ToStream(base64string);

 public Stream Base64ToStream(string base64String)
        {
            byte[] imageBytes = Convert.FromBase64String(base64String);
            MemoryStream stream2 = new MemoryStream(imageBytes);
            return stream2;
        }

Image full path to bitmap 位图的图像完整路径

objModel.PhotoId = "0";
                        var fullPath = string.Format(@"{0}\{1}", destinationFolder.Path, guid + "_" + file.Name);
                        string base64Image = string.Empty;
                        await Task.Run(() =>
                        {
                            Task.Yield();
                            var photo = File.ReadAllBytes(fullPath);
                            base64Image = Convert.ToBase64String(photo);
                            objModel.PhotoBase64 = base64Image;
                        });
                        var fileStream = Base64ToStream(base64Image);
                        var memStream = new MemoryStream();
                        await fileStream.CopyToAsync(memStream);
                        memStream.Position = 0;
                        var bitmap = new BitmapImage();
                        bitmap.SetSource(memStream.AsRandomAccessStream());

Following the documentation ex. 按照文档ex。 https://docs.microsoft.com/en-us/windows/uwp/networking/sockets https://docs.microsoft.com/zh-cn/windows/uwp/networking/sockets

    MediaCapture mediaCapture;
    string serviceNameForConnect = "22112";
    string hostNameForConnect = "localhost";
    NetworkAdapter adapter = null;
    StreamSocket clientSocket = null;

    private async void StartListener_Click(object sender, RoutedEventArgs e)
    {
        StreamSocketListener listener = new StreamSocketListener();

        listener.ConnectionReceived += OnConnection;

        await listener.BindServiceNameAsync(serviceNameForConnect);
    }

    private async void ConnectSocket_Click(object sender, RoutedEventArgs e)
    {
        HostName hostName;

        mediaCapture = new MediaCapture();

        await mediaCapture.InitializeAsync();

        try
        {
            hostName = new HostName(hostNameForConnect);
        }
        catch (ArgumentException ex)
        {
            return;
        }

        clientSocket = new StreamSocket();

        try
        {
            await clientSocket.ConnectAsync(hostName, serviceNameForConnect);
        }
        catch (Exception exception)
        {
            // If this is an unknown status it means that the error is fatal and retry will likely fail.
            if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
            {
                throw;
            }
        }
    }

    private async void Send_Click(object sender, RoutedEventArgs e)
    {
        object outValue;
        // Create a DataWriter if we did not create one yet. Otherwise use one that is already cached.
        DataWriter writer;

        if (!CoreApplication.Properties.TryGetValue("clientDataWriter", out outValue))
        {
            writer = new DataWriter(clientSocket.OutputStream);

            CoreApplication.Properties.Add("clientDataWriter", writer);
        }
        else
        {
            writer = (DataWriter)outValue;
        }

        while (true)
        {
            var memoryStream = new InMemoryRandomAccessStream();

            await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), memoryStream);

            await Task.Delay(TimeSpan.FromMilliseconds(18.288)); //60 fps

            memoryStream.Seek(0);

            writer.WriteUInt32((uint)memoryStream.Size);

            writer.WriteBuffer(await memoryStream.ReadAsync(new byte[memoryStream.Size].AsBuffer(), (uint)memoryStream.Size, InputStreamOptions.None));

            // Write the locally buffered data to the network.
            try
            {
                await writer.StoreAsync();
            }
            catch (Exception exception)
            {
                // If this is an unknown status it means that the error if fatal and retry will likely fail.
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }
            }
        }
    }

    private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
    {
        await Task.WhenAll(DownloadVideos(args));
    }

    public async Task DownloadVideos(StreamSocketListenerConnectionReceivedEventArgs args)
    {
        DataReader reader = new DataReader(args.Socket.InputStream);

        try
        {
            while (true)
            {
                // Read first 4 bytes (length of the subsequent string).
                uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));

                if (sizeFieldCount != sizeof(uint))
                {
                    // The underlying socket was closed before we were able to read the whole data.
                    return;
                }                    
                uint stringLength = reader.ReadUInt32();

                uint actualStringLength = await reader.LoadAsync(stringLength);

                if (stringLength != actualStringLength)
                {
                    // The underlying socket was closed before we were able to read the whole data.
                    return;
                }

                NotifyUserFromAsyncThread(reader.ReadBuffer(actualStringLength));
            }
        }
        catch (Exception exception)
        {
            // If this is an unknown status it means that the error is fatal and retry will likely fail.
            if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
            {
                throw;
            }
        }
    }

    private void NotifyUserFromAsyncThread(IBuffer buffer)
    {
        var ignore = Dispatcher.RunAsync(
            CoreDispatcherPriority.Normal, () =>
            {
                Stream stream = buffer.AsStream();

                byte[] imageBytes = new byte[stream.Length];

                stream.ReadAsync(imageBytes, 0, imageBytes.Length);

                InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream();

                ms.AsStreamForWrite().Write(imageBytes, 0, imageBytes.Length);

                ms.Seek(0);

                var image = new BitmapImage();

                image.SetSource(ms);

                ImageSource src = image;

                imageElement.Source = src;
            });
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用C#在通用Windows应用程序中未检测到键盘布局更改 - Keyboard layout change not detected in universal windows apps with C# 通用Windows平台(UWP)应用程序的C#服务器/客户端应用程序 - C# Server / Client Application for Universal Windows Platform (UWP) apps 压缩或压缩文件-Windows Phone通用应用程序-C# - Compress or Zip a File - Windows Phone Universal Apps - C# 如何在C#Windows Universal Apps中将字符串附加到文本文件中 - How to append a string into a text file in C# Windows Universal Apps C# - 在通用应用程序中获取 mac 地址 - C# - Get mac address in Universal Apps 在Windows 10通用应用程序中保存FolderPicker位置以供下次使用c# - Save FolderPicker location for next time in windows 10 universal apps c# 如何使用Windows Universal Apps(C#,XAML)存储数据/使用数据库 - How to store data / use databases with Windows Universal Apps (C#, XAML) 如何将修改后的属性绑定到控件Windows Universal Apps(XAML / C#) - How to bind a modified property to a control Windows Universal Apps (XAML/C#) 如何在C#(通用Windows应用)中以编程方式获取视频时长/时长? - How to get video length / duration programatically in C# (Universal windows apps)? 在通用Windows应用程序中显示便携式灰度图(PGM)图像(c#,XAML) - Displaying Portable Graymap (PGM) images in Universal Windows App (c#, XAML)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM