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 }