錄屏的視頻截取某一幀生成圖片

using System.Collections;
  using System.Collections.Generic;
  using UnityEngine;
  using UnityEngine.Video;
  using System.IO;
using UnityEngine.UI;
  
  public class LoadTuPian : MonoBehaviour
{
    VideoPlayer vp;
    Texture2D videoFrameTexture;
    RenderTexture renderTexture;
    public GameObject gameObjectl;
    void Start()
    {
        videoFrameTexture = new Texture2D(2, 2);
        vp = GetComponent<VideoPlayer>();
        vp.playOnAwake = false;
        vp.waitForFirstFrame = true;

        vp.sendFrameReadyEvents = true;
        vp.frameReady += OnNewFrame;
        vp.Play();


    }
    int framesValue = 0;//獲得視頻第幾幀的圖片
    void OnNewFrame(VideoPlayer source, long frameIdx)
    {
        framesValue++;
        if (framesValue==1) {
            renderTexture = source.texture as RenderTexture;
            if (videoFrameTexture.width != renderTexture.width || videoFrameTexture.height != renderTexture.height) {
                videoFrameTexture.Resize(renderTexture.width, renderTexture.height);
            }
            RenderTexture.active = renderTexture;
            videoFrameTexture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
            videoFrameTexture.Apply();
            gameObjectl.GetComponent<Image>().material.mainTexture = videoFrameTexture;
            RenderTexture.active = null;
            vp.frameReady -= OnNewFrame;
            vp.sendFrameReadyEvents = false;
        }
    }
        
    void OnDisable()
    {
      //  if (!File.Exists(Application.streamingAssetsPath+"/temp.jpg")) {
      //      ScaleTexture(videoFrameTexture, 800, 400, (Application.streamingAssetsPath+"/temp+.jpg"));
      //  }
    }
    //生成縮略圖
   // void ScaleTexture(Texture2D source, int targetWidth, int targetHeight, string savePath)
   // {
   //     
   //     Texture2D result = new Texture2D(targetWidth, targetHeight, TextureFormat.ARGB32, false);
   //
   //     for (int i = 0; i<result.height; ++i)
   //     {
   //         for (int j = 0; j<result.width; ++j)
   //         {
   //             Color newColor = source.GetPixelBilinear((float)j / (float)result.width, (float)i / (float)result.height);
   //             result.SetPixel(j, i, newColor);
   //         }
   //     }
   //     result.Apply();
   //     File.WriteAllBytes(savePath, result.EncodeToJPG());
   // }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章