Unity -获得视频的某一帧,生成缩略图

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Video;
using System.IO;


public class NewBehaviourScript : MonoBehaviour {

    VideoPlayer vp;
    Texture2D videoFrameTexture;
    RenderTexture renderTexture;
    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==100) {
            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 ();
            RenderTexture.active = null;
            vp.frameReady -= OnNewFrame;
            vp.sendFrameReadyEvents = false;
        }
    }
        
    void OnDisable()
    {
        if (!File.Exists(Application.persistentDataPath+"/temp.jpg")) {
            ScaleTexture (videoFrameTexture, 800, 400, (Application.persistentDataPath+"/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());
    }

}

Unity 并无直接获取视频某一帧图像的API,所以想要生成缩略图就要自己写方法的

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值