Save the picture when the game is running, and use the picture by intervisibility

We all know that when we dynamically load UI images, we use the method of settlement.load. However, there is a problem in this method, that is, when the game is running, the files saved by screenshots cannot be used and can only be loaded dynamically when the game is restarted. So how can we use screenshots anytime, anywhere? The answer is to read the file using a byte stream.

Let's first write a method to dynamically save pictures.

The code is as follows:

public void SpriteSave(Texture2D screenShot,string Path)
        string formatType = ".png";
        string path = Path;
        // Finally, the texture data is converted into a png image file  
        byte[] bytes = screenShot.EncodeToPNG();
        //  Screenshot save picture
        if (path != null)
            string filename = path + formatType;
            System.IO.File.WriteAllBytes(filename, bytes);


Just pass in the image sprite and pathname (including name) parameters.

Next, let's read this picture

The code is as follows:

                    //Open file stream
                    FileStream fs = new FileStream(path+"/"+name+".png", FileMode.Open, FileAccess.Read);
                    fs.Seek(0, SeekOrigin.Begin);
                    byte[] bytes = new byte[fs.Length];
                    fs.Read(bytes, 0, (int)fs.Length);
                    fs = null;

                    //Transfer files to image Wizard
                    Texture2D t = new Texture2D(1, 1);
                    Sprite sprite = SpriteCreat(t);

Next, you can't use the image sprite directly. You need to change it to sprite type to use it directly

 /// <summary>
    ///Image conversion UI use
    /// </summary>
    /// <param name="texture2D"></param>
    /// <param name="Width"></param>
    /// <param name="Height"></param>
    /// <returns></returns>
    public Sprite SpriteCreat(Texture2D texture2D)
        Sprite sprite = Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height),;
        return sprite;

So the picture can be used directly

                    GameObject Prefab = Instantiate(ImageObj) as GameObject;
                    Sprite image = Prefab.transform.GetChild(0).GetComponent<Image>().sprite = sprite;

OK, the key code is here.

Added by JackSevelle on Sun, 24 Nov 2019 23:20:45 +0200