Unity in VR scene screenshot, and use Unirx to upload, download function

Source: Internet
Author: User
Tags current time datetime unity network

We first want to go to Unity official website Download Unirx plug-in,,, what this plug-in is to do with it,,, here let's briefly say: In general, Unity network operation needs to use to WWW and co-process (Coroutine), but, Using the coroutine is not a good idea for asynchronous operations for the following reasons:


1. The co-process cannot return any value because its return type must be IEnumerator.

2, the association can not catch the exception, because the yield return declaration does not support the try-catch structure. 、

At this point we unirx the power of the plug-in is shown: Unirx integration and observable, you can write asynchronous code in thread, and use Unirx orchestration, which is the best way to control asynchronous flow. More benefits and uses,, we are not here to describe each,,, interested in the words can be self-baidu ...


Let's implement the screenshot function .... Screenshot of the picture we have the current time to name the interception

 Texture2d Capturecamera (camera camera, rect rect) {//Build a Rendertexture object Rendertexture rt = New Re
        Ndertexture ((int) rect.width, (int) rect.height, 1);
        Temporarily set the relevant camera targettexture for RT, and manually render the relevant camera camera.targettexture = RT; Camera.

        Render ();  
        Activates the RT and reads the pixels from it.
        rendertexture.active = RT;
        Texture2d screenshot = new texture2d ((int) rect.width, (int) rect.height, textureformat.rgb24, false);

        Screenshot.readpixels (rect, 0, 0);//Note: This time, it is read from the rendertexture.active Pixel screenshot.apply ();
        Resets the relevant parameters to use the camera to continue to display camera.targettexture = null on the screen;  
        Ps:camera2.targetTexture = null; Rendertexture.active = null;
        jc:added to avoid errors Gameobject.destroy (RT);

        Finally, these texture data into a PNG image file byte[] bytes = Screenshot.encodetopng ();
        Get system time System.DateTime now = new System.DateTime ();
        now = System.DateTime.Now; String picName = string. Format ("Image{0}{1}{2}{3}.png", now. Day, now. Hour, now. Minute, now.
        Second);

        Currentscreencapturename = Picname; string filename = #if Unity_editor | |
Unity_standalone Application.streamingassetspath + "/" + picname;
#elif unity_android "/sdcard/dcim/camera/" +picname;

        #endif currentalbumpath = filename;
        System.IO.File.WriteAllBytes (filename, bytes); Debug.Log (String.

Format ("Screenshot of a picture: {0}", filename);
#if unity_editor UnityEditor.AssetDatabase.Refresh ();

        #endif texture = screenshot;
    Return screenshot; }

Screenshot of the photo we use Unirx upload to the server:
public void Oncliclupload () {//Create a screen-sized texture, RGB24 format//int width = screen.width;
        int height = screen.height;   var tex = texture; Texture texture//reads the contents of the screen into the texture//tex after you have taken the screenshot above.
        Readpixels (New Rect (0, 0, width, height), 0, 0); Tex.

        Apply (); Encode the texture into png byte[] bytes = Tex.
        Encodetopng ();

        Destroy (Tex);
        Debug.Log ("--------------------------------oncliclupload--------------------------");      Wwwform formevent = new Wwwform (); Define table Header Formevent.addfield ("Imgname", currentscreencapturename);
        Add and the server contract good format formevent.addfield ("Access_token", Globalconstdata.usertoken);

        Formevent.addbinarydata ("img", Bytes, currentscreencapturename, "image/png");

        var parallel = Observable.whenall (Observablewww.post ("127.0.0.1", formevent)); Parallel. Catchignore ((wwwerrorexception ex) = {Debug.Log ("===error:" + ex. RawerRormessage); }). Subscribe (xs = {Debug.Log ("--------------Finished uploading screenshot----------------------" + XS
            [0]); Xs[0].
            Contains ("content");
            Josnmsg JM = jsonutility.fromjson<josnmsg> (Xs[0]);
        Tempname = jm.content;
    }); }

This uploads the function to write well ... Below we use the WWW format to carry on the picture download ...
IEnumerator downloadimage (string url, image image)
    {
        string[] imgname = URL. Split ('/');
        www www = new www (URL);
        yield return www;
        if (Www.isDone)
        {
            texture2d tex2d = www.texture;
            Save picture to cache path  
            byte[] bytes = tex2d. Encodetopng ();
            System.IO.File.WriteAllBytes (path + "/" + Imgname[imgname. Length-1], bytes);
           Destroyimmediate (Image.sprite.texture, false);
            Sprite m_sprite = Sprite.create (tex2d, New Rect (0, 0, Tex2d.width, tex2d.height), new Vector2 (0, 0));
            Image.sprite = M_sprite;
        }
        

        Www.Dispose ();
    }

Well, this chapter is written here, welcome to join QQ Group: 280993838. or follow my public number:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.