视频截帧功能可以从视频流中截取指定时刻的单帧画面,并按指定大小缩放成图片。本文介绍如何通过 TOS Java SDK 进行视频截帧。
以下代码展示如何截取第 300ms 的视频帧,并将截取后的图片下载到本地。
import com.volcengine.tos.TOSV2; import com.volcengine.tos.TOSV2ClientBuilder; import com.volcengine.tos.TosClientException; import com.volcengine.tos.TosServerException; import com.volcengine.tos.model.object.GetObjectV2Input; import com.volcengine.tos.model.object.GetObjectV2Output; import java.io.FileOutputStream; import java.io.IOException; public class VideoSnapshotExample { public static void main(String[] args) { String endpoint = "your endpoint"; String region = "your region"; String accessKey = System.getenv("TOS_ACCESS_KEY"); String secretKey = System.getenv("TOS_SECRET_KEY"); String bucketName = "bucket-example"; // 需要确保下载的数据已存在 String objectKey = "video.mp4"; String filePath = "temp.jpg"; String style = "video/snapshot,t_300"; //视频截帧,截取第 300ms 的视频帧 TOSV2 tos = new TOSV2ClientBuilder().build(region, endpoint, accessKey, secretKey); try { GetObjectV2Input input = new GetObjectV2Input().setBucket(bucketName).setKey(objectKey).setProcess(style); // 以下代码展示如何将截帧的图片数据下载到本地。 try (FileOutputStream fileOutputStream = new FileOutputStream(filePath); GetObjectV2Output output = tos.getObject(input)) { byte[] buffer = new byte[1024]; int length; while ((length = output.getContent().read(buffer)) != -1) { fileOutputStream.write(buffer, 0, length); } System.out.println("video process succeed, object's metadata is " + output.getGetObjectBasicOutput()); } catch (IOException e) { System.out.println("write data to file failed"); e.printStackTrace(); } } catch (TosClientException e) { // 操作失败,捕获客户端异常,一般情况是请求参数错误,此时请求并未发送。 System.out.println("video process failed"); System.out.println("Message: " + e.getMessage()); if (e.getCause() != null) { e.getCause().printStackTrace(); } } catch (TosServerException e) { // 操作失败,捕获服务端异常,可以获取到从服务端返回的详细错误信息。 System.out.println("video process failed"); System.out.println("StatusCode: " + e.getStatusCode()); System.out.println("Code: " + e.getCode()); System.out.println("Message: " + e.getMessage()); System.out.println("RequestID: " + e.getRequestID()); } catch (Throwable t) { // 作为兜底捕获其他异常,一般不会执行到这里。 System.out.println("video process failed"); System.out.println("unexpected exception, message: " + t.getMessage()); } } }
关于视频截帧的详细介绍,请参见视频截帧。