Unity 獲得視頻的某一幀,生成縮略圖


Unity 並無直接獲取視頻某一幀圖像的API,所以想要生成縮略圖就要自己寫方法了,

圖片和視頻都可以用這種方式生成縮略圖,另,轉載請標明出處,謝謝。

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 using UnityEngine.Video;
 5 using System.IO;
 6 
 7 
 8 public class NewBehaviourScript : MonoBehaviour {
 9 
10     VideoPlayer vp;
11     Texture2D videoFrameTexture;
12     RenderTexture renderTexture;
13     void Start()
14     {
15         videoFrameTexture = new Texture2D(2, 2);
16         vp = GetComponent<VideoPlayer>();
17         vp.playOnAwake = false;
18         vp.waitForFirstFrame = true;
19 
20         vp.sendFrameReadyEvents = true;
21         vp.frameReady += OnNewFrame;
22         vp.Play();
23 
24 
25     }
26     int framesValue=0;//獲得視頻第幾幀的圖片
27     void OnNewFrame(VideoPlayer source, long frameIdx)
28     {
29         framesValue++;
30         if (framesValue==100) {
31             renderTexture = source.texture as RenderTexture;
32             if (videoFrameTexture.width != renderTexture.width || videoFrameTexture.height != renderTexture.height) {
33                 videoFrameTexture.Resize (renderTexture.width, renderTexture.height);
34             }
35             RenderTexture.active = renderTexture;
36             videoFrameTexture.ReadPixels (new Rect (0, 0, renderTexture.width, renderTexture.height), 0, 0);
37             videoFrameTexture.Apply ();
38             RenderTexture.active = null;
39             vp.frameReady -= OnNewFrame;
40             vp.sendFrameReadyEvents = false;
41         }
42     }
43         
44     void OnDisable()
45     {
46         if (!File.Exists(Application.persistentDataPath+"/temp.jpg")) {
47             ScaleTexture (videoFrameTexture, 800, 400, (Application.persistentDataPath+"/temp.jpg"));
48         }
49     }
50     //生成縮略圖
51     void ScaleTexture(Texture2D source, int targetWidth, int targetHeight,string savePath)
52     {
53         
54         Texture2D result = new Texture2D(targetWidth, targetHeight,TextureFormat.ARGB32, false);
55 
56         for (int i = 0; i < result.height; ++i)
57         {
58             for (int j = 0; j < result.width; ++j)
59             {
60                 Color newColor = source.GetPixelBilinear((float)j / (float)result.width, (float)i / (float)result.height);
61                 result.SetPixel(j, i, newColor);
62             }
63         }
64         result.Apply();
65         File.WriteAllBytes(savePath, result.EncodeToJPG());
66     }
67 
68 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM