如何在C#中将视频转换为字节数组? [英] How to convert Video to byte Array in C#?

查看:106
本文介绍了如何在C#中将视频转换为字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用c#.net Compact Framework 3.5,我想将视频文件转换为字节数组,以便可以将其上传到服务器上.

I am using c# .net compact framework 3.5 and I want to convert a video file to byte array so that I may upload it on the server.

我以类似的方式进行图像上传,获得了成功的结果.

In the similar manner I am doing the image uploading which is getting the success result.

HttpWebRequest request; 
request.ContentType = "image/jpeg";
request.ContentLength = byteArray.Length;
request.Method = "PUT";

imageToByteArray(img).CopyTo(byteArray, 0);
using (Stream requestStream = request.GetRequestStream())
{
  requestStream.Write(byteArray, 0, (int)Fs.Length);
  requestStream.Flush();
  requestStream.Close();
}


public byte[] imageToByteArray(Image imageIn)
{
  MemoryStream ms = new MemoryStream();
  imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
  return ms.ToArray();
}

如何对视频文件执行此操作?

How to do this for the video files?

推荐答案

您应该一次将流复制一个块,而不是将整个文件读入数组.否则,由于视频文件可能会变得很大,因此可能会使用非常大的内存.

You should copy the stream one block at a time instead of reading the entire file into an array. Otherwise, you'll use a potentially very large amount of memory as video files can grow quite big.

例如:

HttpWebRequest request; 
request.Method = "PUT";

using(Stream requestStream = request.GetRequestStream())
using(Stream video = File.OpenRead("Path")) {
    byte[] buffer = new byte[4096];

    while(true) {
        int bytesRead = video.Read(buffer, 0, buffer.Length);

        if (bytesRead == 0) break;
        requestStream.Write(buffer, 0, bytesRead);
    }
}

这篇关于如何在C#中将视频转换为字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆