Unity 截屏,WWW加载图片,保存到本地

来源:互联网 发布:女生学java还是web前端 编辑:程序博客网 时间:2024/05/18 19:42
using UnityEngine;using System.Collections;using System.IO;public class NewBehaviourScript : MonoBehaviour {    private Texture2D tex;void Start () {        CaptureScreenshot2(new Rect(Screen.width * 0f, Screen.height * 0f, Screen.width * 1f, Screen.height * 1f));               StartCoroutine(GetImage());}// Update is called once per framevoid Update () {}    IEnumerator GetImage()    {        string dir = Application.persistentDataPath;        string filePath = dir + "hello" + ".png";        string url = "file://" + Application.dataPath + "/StreamingAssets/" + "1.jpg";        WWW www = new WWW(url);        yield return www;        tex = www.texture;        byte[] pngData = tex.EncodeToPNG();        File.WriteAllBytes(filePath, pngData);    }     public IEnumerator CaptureScreenshot()    {        yield return new WaitForEndOfFrame();        Rect rect = new Rect(Screen.width * 0f, Screen.height * 0f, Screen.width * 1f, Screen.height * 1f);        // 先创建一个的空纹理,大小可根据实现需要来设置          Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);        // 读取屏幕像素信息并存储为纹理数据,          screenShot.ReadPixels(rect, 0, 0);        screenShot.Apply();        // 然后将这些纹理数据,成一个png图片文件          byte[] bytes = screenShot.EncodeToJPG();        string filename = Application.persistentDataPath + "/Screenshot.jpg";        System.IO.File.WriteAllBytes(filename, bytes);    }}

0 0
原创粉丝点击