golang 摄像头截图命令版本

需要安装ffmpeg 使用ffmpeg命令进行画面生成对应的jpg图片

package common

import (
	"context"
	"errors"
	"fmt"
	"net"
	"net/url"
	"os/exec"
	"time"
)

func GetRtspImage(rtsp string) (string, error) {
	tmpFile := fmt.Sprintf("/tmp/%d.jpg", time.Now().Unix())
	var params []string

	params = append(params, "-rtsp_transport")
	params = append(params, "tcp")
	params = append(params, "-y")
	params = append(params, "-i")
	params = append(params, rtsp)
	params = append(params, "-vframes")
	params = append(params, "1")
	params = append(params, "-f")
	params = append(params, "image2")
	params = append(params, tmpFile)

	_, err := Command(time.Second*3, "ffmpeg", params...)
	if err != nil {
		return "", fmt.Errorf("commond err:%w", err)
	}

	return tmpFile, nil
}

// 执行命令并添加超时检测
func Command(timeout time.Duration, name string, arg ...string) (string, error) {
	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	cmd := exec.CommandContext(ctx, name, arg...)

	defer func() {
		cancel()
	}()

	// 当经过Timeout时间后,程序依然没有运行完,则会杀掉进程,ctx也会有err信息
	if out, err := cmd.Output(); err != nil {
		// 检测报错是否是因为超时引起的
		if ctx.Err() != nil && ctx.Err() == context.DeadlineExceeded {
			return "", errors.New("command timeout")
		}

		return string(out), err
	} else {
		return string(out), nil
	}
}

你可能感兴趣的:(GoLang,golang,ffmpeg)