Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Converting Image from WebCam to Texture2D fails!

Discussion in 'Windows' started by nsmith1024, Feb 6, 2019.

  1. nsmith1024

    nsmith1024

    Joined:
    Mar 18, 2014
    Posts:
    870
    Hello,

    Im sending an image from webcam to another unity user over the network using TCP/IP socket. The image should be displayed on a cube.

    So i have to convert the received Image to a texture2D, but its not working.

    After i deserialized the object received from the network, i output the type to the log, which says its type of the received object is "System.Drawing.Bitmap", but when i try to cast that object to an image it gave a runtime error that the cast is invalid.

    Anybody knows how to do it, and how to convert the image to a texture2d and set it on the cube?

    Here is my code.

    Code (CSharp):
    1.        
    2.  
    3.     public TcpClient client= new TcpClient();
    4.     NetworkStream mainStream;
    5.     BinaryFormatter bf = new BinaryFormatter();
    6.  
    7.      ....
    8.        
    9.        client.Connect("loopback", port);
    10.        if (client.Connected) {
    11.             mainStream = client.GetStream();
    12.              object obj = bf.Deserialize(mainStream);
    13.              Debug.Log("obj type=" + obj.GetType());  <<---- log outputs the type as "System.Drawing.Bitmap"
    14.  
    15.              Image image=(Image)obj;   <<<------ runtime error that cast failed here
    16.  
    17.              int w = (int)image.sprite.rect.width;
    18.              int h = (int)image.sprite.rect.height;
    19.  
    20.             Texture2D tex = new Texture2D(w, h, TextureFormat.DXT1, false);
    21.              tex = image.sprite.texture;
    22.              gameObject.GetComponent<Renderer>().material.mainTexture = tex;
    23.       }
    24.