ali_oss.go 1.7 KB
package oss

import (
	"encoding/json"
	"fmt"
	"image"
	_ "image/jpeg"
	"net/http"
	"strings"
	"time"
)

type FileInfo struct {
	FileSize struct {
		Value string
	}
	Format struct {
		Value string
	}
	ImageHeight struct {
		Value string
	}
	ImageWidth struct {
		Value string
	}
}

func GetImageInfo(url string) (info FileInfo, err error) {
	//ok := strings.HasPrefix(url, "https://timeless-world.oss-cn-shenzhen.aliyuncs.com")
	ok := strings.HasPrefix(url, "http")
	if !ok {
		return
	}
	ok = strings.Contains(url, "aliyuncs")
	if !ok {
		return
	}
	apiUrl := url + `?x-oss-process=image/info`
	req, err := http.NewRequest(http.MethodGet, apiUrl, nil)
	if err != nil {
		return info, err
	}
	httpclient := http.Client{
		Timeout: 30 * time.Second,
	}
	resp, err := httpclient.Do(req)
	if err != nil {
		return info, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return
	}
	jDecoder := json.NewDecoder(resp.Body)
	err = jDecoder.Decode(&info)
	if err != nil {
		return info, err
	}
	return info, nil
}

// 获取视频封面图
func GetVideoCover(videoUrl string) (coverUrl string, w int, h int, err error) {
	ok := strings.HasPrefix(videoUrl, "http")
	if !ok {
		return
	}
	ok = strings.Contains(videoUrl, "aliyuncs")
	if !ok {
		return
	}
	videoUrl = videoUrl + "?x-oss-process=video/snapshot,t_100,f_jpg,m_fast"
	res, err := http.Get(videoUrl)
	if err != nil || res.StatusCode != http.StatusOK {
		return videoUrl, 600, 600, fmt.Errorf("获取图片失败:%s", err)
	}
	defer res.Body.Close()
	m, _, err := image.Decode(res.Body)
	if err != nil {
		return videoUrl, 600, 600, fmt.Errorf("获取图片失败:%s", err)
	}
	return videoUrl, m.Bounds().Dx(), m.Bounds().Dy(), nil
}