hololens2拍照截图上传时提示目前系统资源占用较高,cpu使用率100%

using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

public class TakePhotoManager : MonoBehaviour
{
    public static TakePhotoManager instance;
    private void Awake()
    {
        instance = this;
    }

    public UnityEngine.Windows.WebCam.PhotoCapture photoCaptureObj = null;
    List<byte> imageBufferList = new List<byte>();
    UnityEngine.Windows.WebCam.CameraParameters cameraParameters;
    Texture2D targetTexture;
    UnityAction uaa;
   // Image ShowImage;

    //拍摄图片
    public void TakePhoto(UnityAction ua)
    {

#if UNITY_EDITOR || UNITY_WSA
        string path = Application.persistentDataPath + "/" + Global.currentProjectId + ".jpg";
        uaa = ua;
        if (File.Exists(path))
        {

            print("文件存在 不用再截图");
        }
        else
        {
            print("图片不存在! 截图");
            UnityEngine.Windows.WebCam.PhotoCapture.CreateAsync(false, OnPhotoCaptureCreated);   //false表示只拍摄摄像头
        }
       
#else
 
#endif
    }

    void OnPhotoCaptureCreated(UnityEngine.Windows.WebCam.PhotoCapture captureObject)
    {
        photoCaptureObj = captureObject;

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

        captureObject.StartPhotoModeAsync(cameraParameters, OnPhotoModeStarted);
    }


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

    void OnCaptturePhotoToMemory(UnityEngine.Windows.WebCam.PhotoCapture.PhotoCaptureResult result, UnityEngine.Windows.WebCam.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));
            //不能在这个地方直接将targetTexture上传到远程的服务器,Hololens会提示{"code":4032,"msg":"目前系统资源占用较高,cpu使用率100%"}
            SavePhoto("linShi666");  //先将图片保存到本地
            photoCaptureObj.StopPhotoModeAsync(OnStoppedPhotoMode); //保存完图片后,释放拍照占用的资源
        }

    }



    void OnStoppedPhotoMode(UnityEngine.Windows.WebCam.PhotoCapture.PhotoCaptureResult result)
    {
        photoCaptureObj.Dispose();
        photoCaptureObj = null;

        if (uaa != null)
        {
            uaa.Invoke(); //拍照回调
        }
    }


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


    //-----------------------------------------------保存图片-----------------------------------
  private  void SavePhoto(string picName)
    {
        print("SavePhoto");
        SavenPic(targetTexture, picName);
    }
    private  void SavenPic(Texture2D tex, string picName)
    {
        print("SavenPic");
        try
        {
            string path = Application.persistentDataPath + "/" + picName + ".jpg";
            print("path :" + path);
            File.WriteAllBytes(path, tex.EncodeToJPG());
            print("保存成功!" + path);

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

        }
    }




    //------------------------------------------显示图片---------------------------------
    public void ShowPhoto(Image ri,string projectId)
    {
        StartCoroutine(LoadPic(ri, projectId));
    }

    private IEnumerator LoadPic(Image ri,string projectId)
    {
            string path = ProjectManage.instance.projectDic[projectId].coverUrl;
            WWW www = new WWW(path);
            yield return www;

            //获取Texture
            Texture2D dynaPic = www.texture;
            ri.sprite = Sprite.Create(dynaPic, new Rect(0, 0, dynaPic.width, dynaPic.height), new Vector2(0.5f, 0.5f));   
    }




}


 void saveJieShu()
    {
        string path = Application.persistentDataPath + "/" + "linShi666" + ".jpg";
        Texture2D tx = new Texture2D(100, 100);
        tx.LoadImage(getImageByte(path));
        //截图成功后 上传本地图片信息到服务器
        HttpSvc.Instance.UpLoadPic(tx, "https://ttt", ResImageSucceed);
    }
 public void ResImageSucceed(string str)
    {
        if (String.IsNullOrEmpty(str))
        {
            return;
        }
        ResTokenData res = JsonConvert.DeserializeObject<ResTokenData>(str);
        if (res.code == 200)
        {
          //res.data 表示图片的服务器地址
        }
        else
        {
            return;
        }
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值