简体   繁体   English

通过套接字流 C# 在 PictureBox 上变得凌乱/裁剪

[英]Getting messy/croped on PictureBox by Socket Streaming C#

I am trying to get the printScreen from another device using socket.我正在尝试使用套接字从另一个设备获取 printScreen。

My sending device (windowsce 6.0) code is我的发送设备(windowsce 6.0)代码是

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace ServerComputer
{
    class Program
    {
        static Socket sendsocket;

        enum RasterOperation : uint { SRC_COPY = 0x00CC0020 }

        [DllImport("coredll.dll")]
        static extern int BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, RasterOperation rasterOperation);

        [DllImport("coredll.dll")]
        private static extern IntPtr GetDC(IntPtr hwnd);

        [DllImport("coredll.dll")]
        private static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc);

        public static void Main(string[] args)
        {
            Console.Out.WriteLine("Gildo Lindo Fon");
            try
            {
                sendsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //The instantiation of socket, IP for 192.168.1.106, 10001 for Port 
                IPEndPoint ipendpiont = new IPEndPoint(IPAddress.Parse("192.168.0.24"), 81);
                sendsocket.Connect(ipendpiont);
                //Establishment of end point
                Console.Out.WriteLine("starting thread");
                Thread th = new Thread(sendImageThread);
                //th.IsBackground = true;
                th.Start();
            }
            catch (Exception ee)
            {
                Console.Out.WriteLine(ee.Message);
                return;
            }
        }
        private static Bitmap GetScreen()
        {
            Rectangle bounds = Screen.PrimaryScreen.Bounds;
            IntPtr hdc = GetDC(IntPtr.Zero);
            Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format16bppRgb565);
            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                IntPtr dstHdc = graphics.GetHdc();
                BitBlt(dstHdc, 0, 0, bounds.Width, bounds.Height, hdc, 0, 0,RasterOperation.SRC_COPY);
                graphics.ReleaseHdc(dstHdc);
            }

            ReleaseDC(IntPtr.Zero, hdc);

            return bitmap;
        }

        private static void sendImageThread()
        {
            Console.Out.WriteLine("SENDING");
            while (true)
            {
                try
                {
                    MemoryStream ms = new MemoryStream();
                    Bitmap bitmapScreen = GetScreen();
                    bitmapScreen.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);   //Here I use the BMP format
                    bitmapScreen.Save(".\\printimg.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                    byte[] b = ms.ToArray();
                    sendsocket.Send(b);
                    ms.Close();
                }
                catch (Exception ee)
                {
                    Console.Out.WriteLine(ee.Message);
                    break;
                }
                Thread.Sleep(1000);
            }
        }
    }
}

My receiver code is like this:我的接收器代码是这样的:

using System.Net;
using System.Net.Sockets;


namespace httpScreenClient;

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    Socket hostSocket = null!;
    Thread thread = null!;
    string localIP = string.Empty;
    string computrHostName = string.Empty;
    int dataSize = 0;
    byte[] imageBytes = new byte[800 * 650 * 16*10]; //Picture of great 16 bpp RGB 565

    private void mainForm_Load(object sender, EventArgs e)
    {
        computrHostName = Dns.GetHostName();
        IPHostEntry hostname = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in hostname.AddressList)
        {
            if (ip.AddressFamily.ToString() == "InterNetwork")
            {
                localIP = ip.ToString();
            }
        }
        this.Text = this.Text + " | " + localIP;
    }

    private void liveScreen_Click(object sender, EventArgs e)
    {
        connectSocket();
    }

    private void connectSocket()
    {
        Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint hostIpEndPoint = new IPEndPoint(IPAddress.Parse("192.168.0.24"), 81);
        //Connection node
        receiveSocket.Bind(hostIpEndPoint);
        receiveSocket.Listen(10);
        //MessageBox.Show("start");
        hostSocket = receiveSocket.Accept();
        thread = new Thread(new ThreadStart(trreadimage))
        {
            IsBackground = true
        };
        thread.Start();
    }
    private void trreadimage()
    {
        while (true) {
            string imageName = "stremScreen.JPG";
            try
            {
                dataSize = hostSocket.Receive(imageBytes);
                if (dataSize > 0)
                {
                    MemoryStream ms = new MemoryStream(imageBytes);
                    Image img = Image.FromStream(ms);
                    img.Save(imageName, System.Drawing.Imaging.ImageFormat.Jpeg);
                    videoBox.Image = img;
                    ms.Close();
                }

            }
            catch (Exception ee)
            {
                //messagebox.show("foi aqui - " + ee.message);
                break;
            }
            Thread.Sleep(1500);
        }
        trreadimage();
    }
}

I checked the screenprinted saved on the sending side and is alright, but what I getting on the receiver side is very messy, as there was some wrongs crops one over the other...我检查了发送端保存的丝网印刷,一切正常,但是我在接收端得到的东西非常混乱,因为一个接一个地出现了一些错误......

丝网印刷图像

Streamed image received:收到的流式图像:

收到图片框表单上的图像

Do you guys have any suggest about what could be going on?你们对可能发生的事情有什么建议吗? actually I was getting the Image.FromStream() error too ( https://social.msdn.microsoft.com/Forums/en-US/820fe38b-3fb6-4490-9608-10c4133e4a50/imagefromstreamms-parameter-is-not-valid?forum=aspdotnetwebpages ) on the receiver side, that's why I left the catch {} part of the code empty... I didn't get to solve this error.实际上我也收到了 Image.FromStream() 错误( https://social.msdn.microsoft.com/Forums/en-US/820fe38b-3fb6-4490-9608-10c4133e4a50/imagefromstreamms-parameter-is-not-valid ?forum=aspdotnetwebpages )在接收方,这就是为什么我将代码的 catch {} 部分留空......我没有解决这个错误。

After some tries I got the solution by compressing the byte array before sending with经过一些尝试,我通过在发送之前压缩字节数组得到了解决方案

private static byte[] Compress(byte[] data)
        {
            MemoryStream output = new MemoryStream();
            using (DeflateStream dstream = new DeflateStream(output, CompressionMode.Compress))
            {
                dstream.Write(data, 0, data.Length);
            }
            return output.ToArray();
        }

And decompressing it on the other side with:并在另一边解压它:

private static byte[] Decompress(byte[] data)
{
    MemoryStream input = new MemoryStream(data);
    MemoryStream output = new MemoryStream();
    using (DeflateStream dstream = new DeflateStream(input, CompressionMode.Decompress))
    {
        dstream.CopyTo(output);
    }
    return output.ToArray();
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM