Unity Android保存摄像头(Vuforia AR)拍照,载入UGUI image组件
发表于2018-07-30
为考虑pc/android/ios兼容性,另外也避免访问系统相册不同系统不一致的麻烦,我们采用application.persistentDataPath 来进行图像读写访问。
步骤一、保存图像
cameraTexture = new Texture2D(Screen.width, Screen.height, TextureFormat.ARGB32, false); UnityEngine.Rect rect = new UnityEngine.Rect (0, 0, cameraTexture.width, cameraTexture.height); cameraTexture.ReadPixels (rect, 0, 0, true); cameraTexture.Apply (); //把图片数据转换为byte数组 byte[] byt = cameraTexture.EncodeToPNG(); //然后保存为图片 System.DateTime now = System.DateTime.Now; string timeStr = now.Year.ToString()+now.Month.ToString()+now.Day.ToString()+ now.Hour.ToString() + now.Minute.ToString() + now.Second.ToString(); File.WriteAllBytes(Application.persistentDataPath + "/CutImage.png", byt);
步骤二、读取图像
有两种方法,一种是SystemIO,一种是www方式,这里采用了SystemIO方式,
string filePath = Application.persistentDataPath + "/CutImage.png"; //创建文件读取流 FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); fileStream.Seek(0, SeekOrigin.Begin); //创建文件长度缓冲区 byte[] bytes = new byte[fileStream.Length]; //读取文件 fileStream.Read(bytes, 0, (int)fileStream.Length); //释放文件读取流 fileStream.Close(); fileStream.Dispose(); fileStream = null;
步骤三、将图像转成Texture2D,然后转成Sprite贴到Image组件上
//创建Texture int width=800; int height=640; Texture2D texture = new Texture2D(width, height); texture.LoadImage(bytes); Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f)); Background.sprite = sprite;
收工,在PC,Android都确认通过。
来自:https://blog.csdn.net/zhh_panan/article/details/52445082