2013-03-29 52 views
22

Tôi muốn hiển thị hình thu nhỏ cho video được liệt kê trên trang web của mình, tôi muốn tìm nạp một khung hình từ video (từ một thời điểm cụ thể) và hiển thị chúng dưới dạng hình thu nhỏ.Lấy hình thu nhỏ của tệp video trong C#

Tôi đã thử số này http://ramcrishna.blogspot.com/2008/09/playing-videos-like-youtube-and.html nhưng không hoạt động.

Có thể sử dụng .NET C# không?

+1

thể trùng lặp của http: // stackoverflow.com/questions/155314/how-do-i-get-a-video-thumbnail-in-net –

+1

Xác định "không hoạt động". Giải pháp đó không phù hợp với bạn? – David

Trả lời

12

Bạn có thể lập trình thực thi FFmpeg để tạo tệp hình ảnh thu nhỏ. Sau đó, mở tệp hình ảnh để sử dụng nó theo cách bạn muốn.

Dưới đây là một số mẫu mã:

public static Bitmap GetThumbnail(string video, string thumbnail) 
{ 
    var cmd = "ffmpeg -itsoffset -1 -i " + '"' + video + '"' + " -vcodec mjpeg -vframes 1 -an -f rawvideo -s 320x240 " + '"' + thumbnail + '"'; 

    var startInfo = new ProcessStartInfo 
    { 
     WindowStyle = ProcessWindowStyle.Hidden, 
     FileName = "cmd.exe", 
     Arguments = "/C " + cmd 
    }; 

    var process = new Process 
    { 
     StartInfo = startInfo 
    }; 

    process.Start(); 
    process.WaitForExit(5000); 

    return LoadImage(thumbnail); 
} 

static Bitmap LoadImage(string path) 
{ 
    var ms = new MemoryStream(File.ReadAllBytes(path)); 
    return (Bitmap)Image.FromStream(ms); 
} 
+2

Tại sao «WaitForExit (5000) '? –

+0

@PaRiMaLRaJ Bạn có thử đoạn mã này không? Bạn phải truyền thông tin gì vào 'thumbnail'? Tôi thậm chí đã tạo một tệp có phần mở rộng .bmp và đã chuyển (C: \ Users \ Public \ Videos \ Sample Videos \ test1 .bmp) vào hình thu nhỏ nhưng nó cho tôi một lỗi trên dòng cuối cùng của mã = ​​"tham số không hợp lệ". Bạn co thể giup tôi được không. Cảm ơn trong Advance – CodeEngine

+0

Chương trình này sẽ chạy cho một ứng dụng được triển khai trên máy chủ/Máy ảo từ xa. Tôi đang lập kế hoạch tạo hình thu nhỏ cho video mà người dùng tải lên trên trang web của tôi. Các bitmap nên được tạo ra trên bay. Vì thao tác này sẽ chạy trên máy chủ, phương thức này có hoạt động không? Điều này hoạt động hoàn hảo trên máy địa phương của tôi mặc dù. – aditya

46

FFMpeg là một công cụ thích hợp có thể được sử dụng để trích xuất khung hình tại một số vị trí. Bạn có thể gọi ffmpeg.exe như đã đề cập ở trên hoặc chỉ sử dụng wrapper NET hiện có (như Video converter for .NET (nó hoàn toàn miễn phí) để có được thu nhỏ chỉ với một dòng mã:

var ffMpeg = new NReco.VideoConverter.FFMpegConverter(); 
ffMpeg.GetVideoThumbnail(pathToVideoFile, thumbJpegStream,5); 
+2

Cảm ơn bạn, giải pháp tốt nhất. –

+1

Tôi có thể sử dụng nó như thế nào? Tôi đã thêm "Install-Package NReco.Application.Web" qua nuget nhưng không thể sử dụng các dòng mã đó .. – gsiradze

+3

Bạn đã cài đặt gói sai. Một trong những quyền là "Install-Package NReco.VideoConverter" (NReco.Application.Web là về khuôn khổ NReco cho các ứng dụng ASP.NET). –

-1
[HttpPost] 
     [Route("UploadImages")] 
     public HttpResponseMessage Post() 
     { 
      HttpResponseMessage response = new HttpResponseMessage(); 
      var httpRequest = HttpContext.Current.Request; 
      if (httpRequest.Files.Count > 0) 
      { 
       var docfiles = new List<string>(); 
       foreach (string file in httpRequest.Files) 
       { 
        var postedFile = httpRequest.Files[file]; 
        var filePath1 = HttpContext.Current.Server.MapPath("~/ImgFolder/" + postedFile.FileName); 

        Stream strm = postedFile.InputStream; 

        CreateThumbnail(strm, postedFile.FileName); 

        Compressimage(strm, filePath1, postedFile.FileName); 


       } 
       response = Request.CreateResponse(HttpStatusCode.Created, docfiles); 
      } 
      else 
      { 
       response = Request.CreateResponse(HttpStatusCode.BadRequest); 
      } 
      return response; 
     } 
     public static void **CreateThumbnail**(Stream sourcePath, string filename) 
     { 
      Image image = Image.FromStream(sourcePath); 
      Image thumb = image.GetThumbnailImage(120, 120,() => false, IntPtr.Zero); 
      var filePath1 = HttpContext.Current.Server.MapPath("~/Thumbnail/" + filename); 

      thumb.Save(filePath1 + filename); 

     } 

     public static void Compressimage(Stream sourcePath, string targetPath, String filename) 
     { 


      try 
      { 
       using (var image = Image.FromStream(sourcePath)) 
       { 
        float maxHeight = 900.0f; 
        float maxWidth = 900.0f; 
        int newWidth; 
        int newHeight; 
        string extension; 
        Bitmap originalBMP = new Bitmap(sourcePath); 
        int originalWidth = originalBMP.Width; 
        int originalHeight = originalBMP.Height; 

        if (originalWidth > maxWidth || originalHeight > maxHeight) 
        { 

         // To preserve the aspect ratio 
         float ratioX = (float)maxWidth/(float)originalWidth; 
         float ratioY = (float)maxHeight/(float)originalHeight; 
         float ratio = Math.Min(ratioX, ratioY); 
         newWidth = (int)(originalWidth * ratio); 
         newHeight = (int)(originalHeight * ratio); 
        } 
        else 
        { 
         newWidth = (int)originalWidth; 
         newHeight = (int)originalHeight; 

        } 
        Bitmap bitMAP1 = new Bitmap(originalBMP, newWidth, newHeight); 
        Graphics imgGraph = Graphics.FromImage(bitMAP1); 
        extension = Path.GetExtension(targetPath); 
        if (extension == ".png" || extension == ".gif") 
        { 
         imgGraph.SmoothingMode = SmoothingMode.AntiAlias; 
         imgGraph.InterpolationMode = InterpolationMode.HighQualityBicubic; 
         imgGraph.DrawImage(originalBMP, 0, 0, newWidth, newHeight); 


         bitMAP1.Save(targetPath, image.RawFormat); 

         bitMAP1.Dispose(); 
         imgGraph.Dispose(); 
         originalBMP.Dispose(); 
        } 
        else if (extension == ".jpg") 
        { 

         imgGraph.SmoothingMode = SmoothingMode.AntiAlias; 
         imgGraph.InterpolationMode = InterpolationMode.HighQualityBicubic; 
         imgGraph.DrawImage(originalBMP, 0, 0, newWidth, newHeight); 
         ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg); 
         Encoder myEncoder = Encoder.Quality; 
         EncoderParameters myEncoderParameters = new EncoderParameters(1); 
         EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L); 
         myEncoderParameters.Param[0] = myEncoderParameter; 
         bitMAP1.Save(targetPath, jpgEncoder, myEncoderParameters); 

         bitMAP1.Dispose(); 
         imgGraph.Dispose(); 
         originalBMP.Dispose(); 

        } 


       } 

      } 
      catch (Exception) 
      { 
       throw; 

      } 
     } 


     public static ImageCodecInfo GetEncoder(ImageFormat format) 
     { 

      ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders(); 

      foreach (ImageCodecInfo codec in codecs) 
      { 
       if (codec.FormatID == format.Guid) 
       { 
        return codec; 
       } 
      } 
      return null; 
     } 
+1

Đây là hình thu nhỏ của Hình ảnh sử dụng webapi. –

+1

Mặc dù đoạn mã này có thể giải quyết được câu hỏi, [bao gồm giải thích] (// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) thực sự giúp cải thiện chất lượng bài đăng của bạn. Hãy nhớ rằng bạn đang trả lời câu hỏi cho người đọc trong tương lai và những người đó có thể không biết lý do cho đề xuất mã của bạn. Ngoài ra, hãy cố gắng không gắn mã của bạn với các nhận xét giải thích vì điều này làm giảm khả năng đọc của cả mã và giải thích! – FrankerZ

+0

Đây không phải là câu trả lời. OP muốn có hình thu nhỏ của ** video **. – mbomb007

Các vấn đề liên quan