unity android保存摄像头(Vuforia AR)拍照,载入UGUI image组件

为考虑pc/android/ios兼容性,另外也避免访问系统相册不同系统不一致的麻烦,

我们采用 application.persistentDataPath 来进行图像读写访问。


步骤1. 保存图像

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); 


步骤2.读取图像

有两种方法,一种是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;


步骤3.将图像转成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都确认通过



  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值