Unity调用摄像头拍照及保存图片

发表于2018-10-17
评论0 1.31w浏览
可能大家在使用Unity开发项目的时候,会碰到这样一个需求,就是去调用摄像头拍照或者保存图片,其中摄像头拍照方式也有多种,这里就给大家简单介绍下。

代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
public class CameraTest : MonoBehaviour
{
    //摄像头图像类,继承自texture
    WebCamTexture tex;
    public Image WebCam;
    public MeshRenderer ma;
    public Button saveImage;
    public RawImage bgimage_02;
   // public RawImage bgimage_03;
    int i;
    void Start()
    {
        //开启协程,获取摄像头图像数据
        StartCoroutine(OpenCamera());
        saveImage.onClick.AddListener(SaveImage);
    }
    // Update is called once per frame
    void Update()
    {
    }
    IEnumerator OpenCamera()
    {
        //等待用户允许访问
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
        //如果用户允许访问,开始获取图像        
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            //先获取设备
            WebCamDevice[] device = WebCamTexture.devices;
            string deviceName = device[0].name;
            //然后获取图像
            tex = new WebCamTexture(deviceName);
            //将获取的图像赋值
            ma.material.mainTexture = tex;
            //开始实施获取
            tex.Play();
        }
    }
    private void SaveImage()
    {
        //在上一段代码中加入该方法
        Save(tex);
        i += 1;
    }
    public  void Save(WebCamTexture t)
    {
        Texture2D t2d = new Texture2D(t.width, t.height, TextureFormat.ARGB32, true);
        //将WebCamTexture 的像素保存到texture2D中
        t2d.SetPixels(t.GetPixels());
        //t2d.ReadPixels(new Rect(200,200,200,200),0,0,false);
        t2d.Apply();
        //编码
        byte[] imageTytes = t2d.EncodeToJPG();
        //if (i % 2 == 1)
        //{
        //   bgimage_02.texture= t2d;
        //}
        //else
        //{
        //    bgimage_03.texture = t2d;
        //}
          bgimage_02.texture= t2d;
        //存储
        File.WriteAllBytes(Application.streamingAssetsPath + "/my/" + Time.time + ".jpg", imageTytes);
    }
    void StopCamera()
    {
        //等待用户允许访问
        //Application.RequestUserAuthorization(UserAuthorization.WebCam);
        //如果用户允许访问,开始获取图像        
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            //先获取设备
            WebCamDevice[] device = WebCamTexture.devices;
            string deviceName = device[0].name;
            //然后获取图像
          //  tex = new WebCamTexture(deviceName);
          //  //将获取的图像赋值
           // ma.material.mainTexture = tex;
            //开始实施获取
            tex.Stop();
        }
    }
    //返回按钮
    public void Back()
    {
       StopCamera();
        UnityEngine.SceneManagement.SceneManager.LoadScene(0);
    }
}

把它挂到一个有renderer的物体上,
上面已经有调用摄像头并可以保存图片。

保存图片有多种方式 :
using UnityEngine;
using System.Collections;
using System.IO;
using UnityEngine.UI;
public class FrameAnimation : MonoBehaviour
{
    public Texture2D image;
    public int w;
    public int h;
    public float nextTime = 0.0f;
    public float rate = 0.3f;
    int i = 0;
    public static string imageName;
    public RawImage raw;
    // Use this for initialization
    void Start()
    {
        w = Screen.width;
        h = Screen.height;
        image = new Texture2D(w, h);
    }
    // Update is called once per frame
    void Update()
    {
        //if (Input.GetMouseButton(0) && Time.time > nextTime)
        //{
        //    nextTime = Time.time + rate;
        //    i++;
        //    StartCoroutine(SaveImage(i));
        //}
    }
    public void Btn_SavrImage()
    {
        ////拍照保存
        //i++;
        //StartCoroutine(SaveImage(i));
        UnityEngine.SceneManagement.SceneManager.LoadScene(2);
    }
    IEnumerator SaveImage(int i)
    {
        yield return new WaitForEndOfFrame();
        image.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0, false);//read pixels from screen to texture
        image.Apply();
        byte[] bytes = image.EncodeToPNG();
        string date = System.DateTime.Now.ToString("dd-MM-yy");
        imageName = i + date + ".png";
        File.WriteAllBytes(Application.streamingAssetsPath + "/" +imageName, bytes);
        ReadImage();
        Debug.Log("write a pic"+imageName);
        yield return null;
    }
    public void ReadImage()
    {
        string  textureName = Application.streamingAssetsPath + imageName;
        //raw.name = textureName;
        raw.texture = image;
       // UnityEngine.SceneManagement.SceneManager.LoadScene(0);
    }
} 
注意:image.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0, false);
我遇到一个问题截图超过1024,768的时候有时候会报错,这个问题因为后期不用了没有再继续深究。来自:https://blog.csdn.net/liang_704959721/article/details/80880422

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引