Hololens拍照,录像,保存到本地,读取图片和视频

工程地址:

https://download.csdn.net/download/shanguuncle/10548611

可到群文件下载

1.拍照

 拍照API https://docs.unity3d.com/Manual/windowsholographic-photocapture.html

可以在编辑器模式下拍照

PhotoCapture.CreateAsync(false, OnPhotoCaptureCreated);

第一个参数布尔值是否拍摄全息画面,如果只拍摄摄像头就false,拍摄全息就true

   

    public PhotoCapture photoCaptureObj = null;
    List<byte> imageBufferList = new List<byte>();
    CameraParameters cameraParameters;

 public void TakePhoto()
    {
        ShowImage.gameObject.SetActive(true);
#if UNITY_EDITOR || UNITY_WSA
        PhotoCapture.CreateAsync(false, OnPhotoCaptureCreated);
#else

#endif
    }

  void OnPhotoCaptureCreated(PhotoCapture captureObject)
    {
        photoCaptureObj = captureObject;

        Resolution  cameraResolution = PhotoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height).First();
        cameraParameters = new CameraParameters();
        cameraParameters.hologramOpacity = 0.0f;
        cameraParameters.cameraResolutionHeight = cameraResolution.height;
        cameraParameters.cameraResolutionWidth = cameraResolution.width;
        cameraParameters.pixelFormat = CapturePixelFormat.BGRA32;

        captureObject.StartPhotoModeAsync(cameraParameters, OnPhotoModeStarted);
    }


    private void OnPhotoModeStarted(PhotoCapture.PhotoCaptureResult result)
    {
        if (result.success)
        {
            photoCaptureObj.TakePhotoAsync(OnCaptturePhotoToMemory);
            Debug.Log("拍照成功");
        }
        else
        {
            //重新拍照
            // PhotoCapture.CreateAsync(false, OnPhotoCaptureCreated);
            Debug.Log("重新拍照");
        }
    }

    void OnCaptturePhotoToMemory(PhotoCapture.PhotoCaptureResult result, PhotoCaptureFrame photoCaptureFrame)
    {
        if (result.success)
        {
            //照片显示
            photoCaptureFrame.CopyRawImageDataIntoBuffer(imageBufferList);
            imageBufferList = FlipVertical(imageBufferList, cameraParameters.cameraResolutionWidth, cameraParameters.cameraResolutionHeight, 4);
            targetTexture = CreateTexture(imageBufferList, cameraParameters.cameraResolutionWidth, cameraParameters.cameraResolutionHeight);
            ShowImage.sprite = Sprite.Create(targetTexture, new Rect(0, 0, targetTexture.width, targetTexture.height), new Vector2(0.5f, 0.5f));
        }
        photoCaptureObj.StopPhotoModeAsync(OnStoppedPhotoMode);
    }

    void OnStoppedPhotoMode(PhotoCapture.PhotoCaptureResult result)
    {
        photoCaptureObj.Dispose();
        photoCaptureObj = null;
    }


    private Texture2D CreateTexture(List<byte> rawData, int width, int height)
    {
        Texture2D tex = new Texture2D(width, height, TextureFormat.BGRA32, false);
        tex.LoadRawTextureData(rawData.ToArray());
        tex.Apply();
        return tex;
    }
    /// <summary>
    /// 照片上下反转
    /// </summary>
    /// <param name="src"></param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    /// <param name="stride"></param>
    /// <returns></returns>
    private List<byte> FlipVertical(List<byte> src, int width, int height, int stride)
    {
        byte[] dst = new byte[src.Count];
        for (int y = 0; y < height; ++y)
        {
            for (int x = 0; x < width; ++x)
            {
                int invY = (height - 1) - y;
                int pxel = (y * width + x) * stride;
                int invPxel = (invY * width + x) * stride;
                for (int i = 0; i < stride; ++i)
                {
                    dst[invPxel + i] = src[pxel + i];
                }
            }
        }
        return new List<byte>(dst);
    }

保存图片到本地

  public void SavePhoto()
    {
        //Texture2D tex = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, true);
        //tex.Apply();
        SavenPic(targetTexture,"test");
        VideoImage.gameObject.SetActive(false);
        ShowImage.gameObject.SetActive(false);
    }
    public void SavenPic(Texture2D tex, string filename)
    {
        try
        {
            string path = Application.persistentDataPath + "/" + filename + ".jpg";
            File.WriteAllBytes(path, tex.EncodeToJPG());
            ShowImage.sprite = null;
            print("保存成功!" + path);

        }
        catch (System.Exception e)
        {
            print("保存失败!" + e.Message);

        }

    }

 读取图片

  public void ShowPhoto() 
    {
        VideoImage.gameObject.SetActive(false);
        ShowImage.gameObject.SetActive(true);
        StartCoroutine(LoadPic("test"));
    }

    private IEnumerator LoadPic(string picname)
    {
        string path = Application.persistentDataPath + "/" + picname + ".jpg" ;
        if (File.Exists(path))
        {
            WWW www = new WWW("file:///" + path);
            yield return www;

            //获取Texture
            Texture2D dynaPic = www.texture;
            ShowImage.sprite = Sprite.Create(dynaPic, new Rect(0, 0, dynaPic.width, dynaPic.height), new Vector2(0.5f, 0.5f));
            print("读取成功");
        }
        else
        {
            print("图片不存在!");
        }
    }

2.录像

录像API https://docs.unity3d.com/Manual/windowsholographic-videocapture.html

编辑器模式下不可用,只有在Hololens上能使用

   VideoCapture m_VideoCapture = null;
    bool isRecording;
    public void StopVideo()
    {
        if (isRecording)
        {
            isRecording = false;
            print("停止录像...");
            if(Application.platform==RuntimePlatform.WSAPlayerX86)
            m_VideoCapture.StopRecordingAsync(OnStoppedRecordingVideo);   
        }
    }
    public void TakeVideo()
    {
        VideoImage.gameObject.SetActive(false);
        ShowImage.gameObject.SetActive(false);

        if (!isRecording)
        {
           
            isRecording = true;
            print("开始录像...");
            if (Application.platform == RuntimePlatform.WSAPlayerX86)
            VideoCapture.CreateAsync(false, StartVideoCapture);
        }
    }
 void StartVideoCapture(VideoCapture videoCapture)
    {

        if (videoCapture != null)
        {
            m_VideoCapture = videoCapture;
            Debug.Log("Created VideoCapture Instance!");

            Resolution cameraResolution = VideoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height).First();
            float cameraFramerate = VideoCapture.GetSupportedFrameRatesForResolution(cameraResolution).OrderByDescending((fps) => fps).First();
            Debug.Log("刷新率:" + cameraFramerate);

            CameraParameters cameraParameters = new CameraParameters();
            cameraParameters.hologramOpacity = 0.0f;
            cameraParameters.frameRate = cameraFramerate;
            cameraParameters.cameraResolutionWidth = cameraResolution.width;
            cameraParameters.cameraResolutionHeight = cameraResolution.height;
            cameraParameters.pixelFormat = CapturePixelFormat.BGRA32;

            m_VideoCapture.StartVideoModeAsync(cameraParameters,
                VideoCapture.AudioState.ApplicationAndMicAudio,
                OnStartedVideoCaptureMode);
        }
        else
        {
            Debug.LogError("Failed to create VideoCapture Instance!");
        }
    }

    void OnStartedVideoCaptureMode(VideoCapture.VideoCaptureResult result)
    {
        Debug.Log("开始录像模式!");
        //string timeStamp = Time.time.ToString().Replace(".", "").Replace(":", "");
        //string filename = string.Format("TestVideo_{0}.mp4", timeStamp);
        string filename = "TestVideo.mp4";
        string filepath = Path.Combine(Application.persistentDataPath, filename);
        filepath = filepath.Replace("/", @"\");
        m_VideoCapture.StartRecordingAsync(filepath, OnStartedRecordingVideo);
        print("videopath:"+ filepath);
    }

    void OnStoppedVideoCaptureMode(VideoCapture.VideoCaptureResult result)
    {
        m_VideoCapture.Dispose();
        m_VideoCapture = null;
        Debug.Log("停止录像模式!");
    }

    void OnStartedRecordingVideo(VideoCapture.VideoCaptureResult result)
    {
        Debug.Log("开始录像!");
    }

    void OnStoppedRecordingVideo(VideoCapture.VideoCaptureResult result)
    {
        Debug.Log("停止录像!");
        m_VideoCapture.StopVideoModeAsync(OnStoppedVideoCaptureMode);
    }

播放录制的视频

扫描二维码关注公众号,回复: 2233449 查看本文章
 public void PlayVideo()
    {
        if (File.Exists(Application.persistentDataPath + "/TestVideo.mp4"))
        {
            VideoImage.gameObject.SetActive(true);
            ShowImage.gameObject.SetActive(false);

            print("播放视频...");
            VideoImage.url = "file:///" + Application.persistentDataPath + "/TestVideo.mp4";
            VideoImage.Play();    
        }
        else
        {
            print("视频不存在!");
        }
    }

3.打包勾选权限

打包需勾选摄像头和麦克风权限

Player settings->Capabilities

Hololens运行截图

猜你喜欢

转载自blog.csdn.net/ShanGuUncle/article/details/81096477