private static Item GenerateCacheObjectThumbnail(Color background, String pathToFile) { Item ans = new Item(); int targetWidth = 128, targetHeight = 128; Image temp = null; /// Generate the thumbnail depending on the type of file if (pathToFile != null) { string fileGotten = AtRuntime.Settings.GetFile(pathToFile); if (Constants.AllowedExtensionsImages.Any(fileGotten.ToUpperInvariant().EndsWith)) { using (FileStream fs = new FileStream(fileGotten, FileMode.Open, FileAccess.Read)) { using (Image image = Image.FromStream(fs, true, false)) { //temp = GenerateThumbnailPhoto(pathToFile); temp = ScaleImage(image, 128, 128); GetExifFromImage(pathToFile, image).ContinueWith(t => Console.WriteLine(t.Exception), TaskContinuationOptions.OnlyOnFaulted); } } } else { using (MemoryStream memStream = new MemoryStream()) { FFMpegConverter ffmpeg = new FFMpegConverter(); ffmpeg.GetVideoThumbnail(pathToFile, memStream); using (Image image = Image.FromStream(memStream, true, false)) { temp = ScaleImage(image, 128, 128); } } } } Image target = new Bitmap(1, 1); (target as Bitmap).SetPixel(0, 0, background); target = new Bitmap(target, targetWidth, targetHeight); using (Graphics g = Graphics.FromImage(target)) { g.Clear(background); int x = (targetWidth - temp.Width) / 2; int y = (targetHeight - temp.Height) / 2; g.DrawImage(temp, x, y); } ans.Thumbnail = target; return ans; }
private void btnGetFrames_Click(object sender, EventArgs e) { string inputPath = tbVideo.Text; string outputPath = tboutdir.Text; try { if (inputPath != null && outputPath != null) { float duration = GetVideoDuration(inputPath); FFMpegConverter ffmegc = new FFMpegConverter(); float frameTime = 0.3f; int counter = 1; while (frameTime <= duration) { string img = Path.Combine(outputPath, string.Format("frame{0}.jpg", counter)); ffmegc.GetVideoThumbnail(inputPath, img, frameTime); counter++; frameTime += 0.3f; Image pic = resizeImage(new Bitmap(img), new Size(293, 163)); picBox.Image = new Bitmap(pic); } } } catch (FFMpegException ex) { MessageBox.Show(ex.ToString()); } }
public ActionResult upload(Model_demo obj) { HttpPostedFileBase file = Request.Files["file1"]; demo tb = new demo(); var filename = Path.GetFileName(file.FileName); if (file.FileName != null) { string keyName = filename; int fileExtPos = keyName.LastIndexOf("."); if (fileExtPos >= 0) { keyName = keyName.Substring(0, fileExtPos); } var path = Path.Combine(Server.MapPath("~/fileupload"), filename); file.SaveAs(path); string thumbnailJPEGpath = Server.MapPath("~/fileupload/" + keyName + ".jpg"); FFMpegConverter ffmpeg = new FFMpegConverter(); ffmpeg.GetVideoThumbnail(path, thumbnailJPEGpath, 2); var path2 = Path.Combine(Server.MapPath("~/fileupload"), keyName + ".jpg"); S3Class s3obj = new S3Class(); string str2 = s3obj.putObject("all.input.video.streaming", path, file.FileName.Replace(' ', '_')); string str = s3obj.putObject("transcoder.thumbnail.video.streaming", path2, keyName + ".jpg"); tb.name = str; } db.demos.InsertOnSubmit(tb); db.SubmitChanges(); return(View()); }
/// <summary> /// ایجاد تصویر بندانگشتی از ویدیو /// </summary> /// <param name="filePath"></param> /// <returns></returns> public async Task GenerateThumbnailAsync(string filePath) { var ffMpegConverter = new FFMpegConverter(); var outputFile = Path.Combine(HttpContext.Current.Server.MapPath(FileConst.VideosWebPath), Path.GetFileNameWithoutExtension(filePath) + "_thumb.jpg"); ffMpegConverter.GetVideoThumbnail(filePath, outputFile); }
/// <summary> /// Returns thumbnail for episode. Also takes care of caching. /// </summary> /// <param name="id">TVDb id of Series</param> /// <param name="epId">TVDb id of Episode</param> /// <returns>BitmapImage with thumbnail or null in case of errors</returns> public static async Task <BitmapImage> GetEpisodeThumbnail(int id, int epId) { return(await Task.Run(async() => { Episode ep = GetEpisode(id, epId, true); if (!String.IsNullOrEmpty(ep.thumbnail) && File.Exists(ep.thumbnail)) { return await LoadImage(ep.thumbnail); } else if (!String.IsNullOrEmpty(ep.filename)) { string file = db + id + "\\Thumbnails\\" + Path.GetFileName(ep.filename); WebClient wc = new WebClient(); Directory.CreateDirectory(Path.GetDirectoryName(file)); wc.DownloadFile("https://www.thetvdb.com/banners/" + ep.filename, file); ep.thumbnail = file; EditEpisode(id, epId, ep); return await LoadImage(ep.thumbnail); } else if (ep.files.Where(x => x.Type == Episode.ScannedFile.FileType.Video).Count() > 0) { string file = ep.files.Where(x => x.Type == Episode.ScannedFile.FileType.Video).ToList()[0].NewName; var ffmpeg = new FFMpegConverter(); ffmpeg.FFMpegToolPath = Environment.GetFolderPath(SpecialFolder.ApplicationData); string path = db + id + "\\Thumbnails\\" + ep.id + ".jpg"; try { ffmpeg.GetVideoThumbnail(file, path, 10); ep.thumbnail = path; EditEpisode(id, epId, ep); return await LoadImage(ep.thumbnail); } catch (FFMpegException) { } } return null; })); }
private VideoFileInfoSample GetVideo(Episode.ScannedFile file) { FFMpegConverter ffmpeg = new FFMpegConverter(); FFProbe probe = new FFProbe(); ffmpeg.FFMpegToolPath = probe.ToolPath = Environment.GetFolderPath(SpecialFolder.ApplicationData); var info = probe.GetMediaInfo(file.NewName); var videotag = info.Streams.Where(x => x.CodecType == "video").FirstOrDefault(); var audiotag = info.Streams.Where(x => x.CodecType == "audio").FirstOrDefault(); Stream str = new MemoryStream(); ffmpeg.GetVideoThumbnail(file.NewName, str, 10); Bitmap bmp = new Bitmap(str); return(Dispatcher.Invoke(() => { VideoFileInfoSample sample = sample = new VideoFileInfoSample(); sample.ScannedFile = file; sample.Preview.Source = bmp.ToBitmapImage(); sample.TopText.Text = videotag.Width + "x" + videotag.Height; sample.Codec.Text = videotag.CodecName; var lang = videotag.Tags.Where(x => x.Key == "language" || x.Key == "Language" || x.Key == "lang" || x.Key == "Lang").FirstOrDefault(); sample.Language.Text = !String.IsNullOrEmpty(lang.Value) ? lang.Value : "-"; sample.Fps.Text = videotag.FrameRate.ToString("##.##") + "FPS"; sample.Pixel.Text = videotag.PixelFormat; sample.Created.Text = File.GetCreationTime(file.NewName).ToString("HH:mm:ss, dd. MM. yyyy"); sample.AudioCodec.Text = audiotag.CodecName; return sample; })); }
public static Movie Make(string path) { var converter = new FFMpegConverter(); var image = new MemoryStream(); converter.GetVideoThumbnail(path, image); image.Position = 0; return(new Movie(path, Smaller(image))); }
/// <summary> /// Extracts a thumbnail image from the video file /// </summary> public Image LoadThumb(string videoUri, float?frameTime = null) { var extract = new FFMpegConverter(); using (var stream = new MemoryStream()) { extract.GetVideoThumbnail(videoUri, stream, frameTime); return(Image.FromStream(stream)); } }
private static Item GenerateCacheObjectThumbnail(Color background, String pathToFile) { Item ans = new Item(); int targetWidth = 128, targetHeight = 128; Image temp = null; /// Generate the thumbnail depending on the type of file if (pathToFile != null) { string fileGotten = AtRuntime.Settings.GetFile(pathToFile); if (Constants.AllowedExtensionsImages.Any(fileGotten.ToUpperInvariant().EndsWith)) { using (FileStream fs = new FileStream(fileGotten, FileMode.Open, FileAccess.Read)) { using (Image image = Image.FromStream(fs, true, false)) { //temp = GenerateThumbnailPhoto(pathToFile); temp = ScaleImage(image, 128, 128); GetExifFromImage(pathToFile, image).ContinueWith(t => Console.WriteLine(t.Exception), TaskContinuationOptions.OnlyOnFaulted); } } } else { using (MemoryStream memStream = new MemoryStream()) { FFMpegConverter ffmpeg = new FFMpegConverter(); ffmpeg.GetVideoThumbnail(pathToFile, memStream); using (Image image = Image.FromStream(memStream, true, false)) { temp = ScaleImage(image, 128, 128); } } } } Image target = new Bitmap(1, 1); (target as Bitmap).SetPixel(0, 0, background); target = new Bitmap(target, targetWidth, targetHeight); using (Graphics g = Graphics.FromImage(target)) { g.Clear(background); int x = (targetWidth - temp.Width) / 2; int y = (targetHeight - temp.Height) / 2; g.DrawImage(temp, x, y); } ans.Thumbnail = target; return(ans); }
public IHttpActionResult UploadVideo() { var files = HttpContext.Current.Request.Files; if (files.Count == 0) { return(Response(new { Success = false, Message = "No file uploaded" })); } var file = files[0]; //and it's name var fileName = file.FileName; //file extension and it's type var fileExtension = Path.GetExtension(fileName); if (!string.IsNullOrEmpty(fileExtension)) { fileExtension = fileExtension.ToLowerInvariant(); } var contentType = file.ContentType; if (string.IsNullOrEmpty(contentType)) { contentType = VideoUtility.GetContentType(fileExtension); } if (contentType == string.Empty) { return(Response(new { Success = false, Message = "Invalid file type" })); } var tickString = DateTime.Now.Ticks.ToString(); var savePath = ControllerUtil.MobSocialPluginsFolder + "Uploads/" + tickString + fileExtension; file.SaveAs(HostingEnvironment.MapPath(savePath)); //wanna generate the thumbnails for videos...ffmpeg is our friend var ffmpeg = new FFMpegConverter(); var thumbnailFilePath = ControllerUtil.MobSocialPluginsFolder + "Uploads/" + tickString + ".thumb.jpg"; ffmpeg.GetVideoThumbnail(HostingEnvironment.MapPath(savePath), HostingEnvironment.MapPath(thumbnailFilePath)); //save the picture now return(Json(new { Success = true, VideoUrl = savePath.Replace("~", ""), ThumbnailUrl = thumbnailFilePath.Replace("~", ""), MimeType = file.ContentType })); }
/// <summary> /// Gets the preview of selected list item /// </summary> private void getPreview() { if (listBoxPaths.SelectedItem != null) { FFMpegConverter fFMpeg = new FFMpegConverter(); System.IO.Stream stream = new System.IO.MemoryStream(); fFMpeg.GetVideoThumbnail((string)listBoxPaths.SelectedItem, stream, frameNumber); Image img = Image.FromStream(stream); img = ResizeImage(img, pictureBox1.Width, pictureBox1.Height); pictureBox1.Image = img; } }
/// <summary> /// creat video frame for async methods /// </summary> /// <param name="originalVideoBytes">byte aaray whith original file</param> /// <returns>frame</returns> public static byte[] GetCompresedVideoFrameAsync(this byte[] originalVideoBytes, HttpContext context) { string originalVideoPath = $"{context.Server.MapPath("~/App_Data/")}{Guid.NewGuid()}.mp4"; string compresedVideoFramePath = $"{context.Server.MapPath("~/App_Data/")}{Guid.NewGuid()}.jpg"; File.WriteAllBytes(originalVideoPath, originalVideoBytes); var ffmpegconverter = new FFMpegConverter(); ffmpegconverter.GetVideoThumbnail(originalVideoPath, compresedVideoFramePath, 3); var result = File.ReadAllBytes(compresedVideoFramePath); File.Delete(originalVideoPath); File.Delete(compresedVideoFramePath); return(result); }
private static void GetThumbnailVideo(string videoPath, string videoName) { var videoFramesFolder = "VideoFrames"; var rName = Guid.NewGuid() + ".png"; string firstFrameFolderPhysical = Path.Combine(Directory.GetCurrentDirectory(), videoFramesFolder); if (Directory.Exists(firstFrameFolderPhysical)) { Directory.Delete(firstFrameFolderPhysical, true); } Directory.CreateDirectory(firstFrameFolderPhysical); //string firstFrameFolderWeb = SiteConfigurationSetting.GetConfiguration("WebPath") + // SiteConfigurationSetting.GetConfiguration("UserTempProjectPath") + "/" + videoFramesFolder + "/" + currentUserId + "/" + objTempModel.Id + "/" + cardFolderName + "/"; var ffMpeg = new FFMpegConverter(); //copy file to local folder and get thumbnail var rFolderName = videoName.Replace(".mp4", ""); var webApiRoot = Path.Combine(Directory.GetCurrentDirectory(), rFolderName); if (Directory.Exists(webApiRoot)) { Directory.Delete(webApiRoot, true); } Directory.CreateDirectory(webApiRoot); //var destvideoPhysical = webApiRoot + "\\" + videoFileName; //File.Copy(item, destvideoPhysical, true); var thumbnailPath = webApiRoot + "\\" + rName; ffMpeg.GetVideoThumbnail(videoPath, thumbnailPath); //resize Bitmap img = (Bitmap)Bitmap.FromFile(thumbnailPath); var image_p = ResizeImage(img, Convert.ToInt32(1200), Convert.ToInt32(900)); image_p.Save(firstFrameFolderPhysical + "\\" + rName); image_p.Dispose(); img.Dispose(); //copy to gmacdn //File.Copy(thumbnailPath, firstFrameFolderPhysical + "\\" + rName); //firstFrameFolderWeb = firstFrameFolderWeb + "/" + rName; //delete Temp folder //Directory.Delete(webApiRoot, true); }
private byte[] MakeThumbnail(byte[] video) { var temp = Path.GetTempFileName(); try { File.WriteAllBytes(temp, video); var converter = new FFMpegConverter(); var stream = new MemoryStream(); converter.GetVideoThumbnail(temp, stream); return(stream.ToArray()); } finally { File.Delete(temp); } }
/// <summary> /// Get thumbnail of object supplied /// </summary> /// <param name="source"></param> /// <param name="thumbnail"></param> /// <returns></returns> public static async Task <string> GetThumbnail(string source, string thumbnail) { try { _ffmpeg.GetVideoThumbnail(source, thumbnail); return(thumbnail); } catch (Exception ex) { ex.HelpLink = "It can be due to incorrect file path."; ex.Data.Add("Location : ", "Exception occured while fetching thumbnail."); ex.Data.Add("Applpication Tier : ", "1. QAConnect"); ex.Data.Add("Class : ", "File Handler"); ex.Data.Add("Method : ", "GetThumbnail"); ex.Data.Add("Input Parameters : ", string.Format("source: {0},thumbnail: {1}", source, thumbnail)); Logs.Error("Error fetching thumbnail.", ex); return(null); } }
/// <summary> /// Generates thumbnail for video file. /// </summary> /// <param name="videoFilePath"></param> /// <returns>Base64 string with thumbnail.</returns> private string GetVideoThumbnail(string videoFilePath) { using (var outputStream = new MemoryStream()) { var ffMpeg = new FFMpegConverter(); try { ffMpeg.GetVideoThumbnail(videoFilePath, outputStream); } catch (FFMpegException ex) { throw new InvalidFileContentException("File is not a video.", ex); } ResizeImage(outputStream, outputStream, ThumbnailImageWidth, ThumbnailImageHeight); return(Convert.ToBase64String(outputStream.ToArray())); } }
public ActionResult upload(Model_video obj) { HttpPostedFileBase file = Request.Files["file1"]; tbl_video tb = new tbl_video(); if (file.FileName != "") { var filename = Path.GetFileName(file.FileName); string keyName = filename; int fileExtPos = keyName.LastIndexOf("."); if (fileExtPos >= 0) { keyName = keyName.Substring(0, fileExtPos); } var path = Path.Combine(Server.MapPath("~/fileupload"), filename); file.SaveAs(path); string thumbnailJPEGpath = Server.MapPath("~/fileupload/" + keyName + ".jpg"); FFMpegConverter ffmpeg = new FFMpegConverter(); ffmpeg.GetVideoThumbnail(path, thumbnailJPEGpath, 4); var path2 = Path.Combine(Server.MapPath("~/fileupload"), keyName + ".jpg"); S3Class s3obj = new S3Class(); string str2 = s3obj.putObject("transcoder.input.video.streaming", path, file.FileName.Replace(' ', '_')); string str = s3obj.putObject("transcoder.thumbnail.video.streaming", path2, keyName + ".jpg"); tb.video_thumb = str; tb.video_path = str2; } tb.login_id = obj.login_id; tb.cat_id = obj.cat_id; tb.sub_cat_id = obj.sub_cat_id; tb.video_name = obj.video_name; tb.video_des = obj.video_des; tb.video_date = DateTime.Today; tb.video_paid = false; db.tbl_videos.InsertOnSubmit(tb); db.SubmitChanges(); return(RedirectToAction("Index")); }
private static void ProcessVideo(string blobName) { string blobConnectionString = ConfigurationManager.AppSettings["BlobConnectionString"]; CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(blobConnectionString); CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient(); CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("media"); CloudBlob cloudBlob = cloudBlobContainer.GetBlobReference(blobName); string tempInputFileName = Path.Combine(Path.GetTempPath(), blobName); string tempOutputFileName = Path.Combine(Path.GetTempPath(), blobName.Replace(".mp4", ".jpg")); Directory.CreateDirectory(Path.GetDirectoryName(tempOutputFileName)); cloudBlob.DownloadToFile(tempInputFileName, FileMode.Create); var ffMpeg = new FFMpegConverter(); ffMpeg.GetVideoThumbnail(tempInputFileName, tempOutputFileName); CloudBlockBlob convertedBlob = cloudBlobContainer.GetBlockBlobReference(blobName.Replace(".mp4", ".jpg")); convertedBlob.Properties.ContentType = "image/jpeg"; foreach (KeyValuePair <string, string> metadata in cloudBlob.Metadata) { convertedBlob.Metadata.Add(metadata.Key, metadata.Value); } convertedBlob.UploadFromFile(tempOutputFileName); }
private void loadVideo(string fileName) { if (FaceSearchList.Count > 0) { FaceSearchList.Clear(); FaceSearchImageList.Images.Clear(); listView1.Clear(); } string username = Environment.UserName; string framePath = @"C:\Users\" + username + @"\Desktop\Frames"; if (!Directory.Exists(framePath)) { Directory.CreateDirectory(framePath); } FFMpegConverter ffmpeg = new FFMpegConverter(); TFaceRecord fr = new TFaceRecord(); for (int i = 0; i < Duration(fileName); i++) { string fn = framePath + @"\" + i + ".jpeg"; ffmpeg.GetVideoThumbnail(fileName.ToString(), fn, i); fr.ImageFileName = fn; fr.FacePosition = new FSDK.TFacePosition(); fr.FacialFeatures = new FSDK.TPoint[2]; fr.Template = new byte[FSDK.TemplateSize]; fr.image = new FSDK.CImage(fn); fr.FacePosition = fr.image.DetectFace(); if (0 == fr.FacePosition.w) { if (fileName.Length <= 1) { } } else { fr.faceImage = fr.image.CopyRect((int)(fr.FacePosition.xc - Math.Round(fr.FacePosition.w * 0.5)), (int)(fr.FacePosition.yc - Math.Round(fr.FacePosition.w * 0.5)), (int)(fr.FacePosition.xc + Math.Round(fr.FacePosition.w * 0.5)), (int)(fr.FacePosition.yc + Math.Round(fr.FacePosition.w * 0.5))); try { fr.FacialFeatures = fr.image.DetectEyesInRegion(ref fr.FacePosition); } catch (Exception ex2) { MessageBox.Show(ex2.Message, "Error detecting eyes."); } try { fr.Template = fr.image.GetFaceTemplateInRegion(ref fr.FacePosition); // get template with higher precision } catch (Exception ex2) { MessageBox.Show(ex2.Message, "Error retrieving face template."); } FaceSearchList.Add(fr); FaceSearchImageList.Images.Add(fr.faceImage.ToCLRImage()); listView1.Items.Add((FaceSearchImageList.Images.Count - 1).ToString(), fn.Split('\\')[fn.Split('\\').Length - 1], FaceSearchImageList.Images.Count - 1); using (Image img = fr.image.ToCLRImage()) { pictureBox1.Image = img; pictureBox1.Refresh(); } listView1.Refresh(); } } pictureBox1.Image = null; }
private void returnDirContents(HttpListenerContext context, string dirPath) { try { context.Response.ContentType = "text/html"; context.Response.ContentEncoding = Encoding.UTF8; using (var sw = new StreamWriter(context.Response.OutputStream)) { sw.WriteLine("<html>"); sw.WriteLine("<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><meta name=\"viewport\" content=\"width = device - width\" /></head>"); sw.WriteLine("<body style=\"" + main_body + "\">"); sw.WriteLine("<form method=\"post\" style=\"" + main_form + "\"><input style=\"" + main_logout + "\" type=\"submit\" value=\"Logout\" /></form> "); sw.WriteLine("<div style=\"" + main_div + "\"><a style=\"" + main_div_a + "\" href=\"" + perffff + "\">Home</a><br></br></div>"); var dirs = Directory.GetDirectories(dirPath); foreach (var d in dirs) { var link = ""; var ss = Path.GetFileName(d); var imgdata = ""; var tag = ""; if (UURRLL[UURRLL.Count() - 1] != '/') { UURRLL += "/"; } link = UURRLL + ss; try { SHFILEINFO shinfo = new SHFILEINFO(); //Call function with the path to the folder you want the icon for SHGetFileInfo( d, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_LARGEICON); imgdata = "data:image/jpg;base64," + Convert.ToBase64String(ImageToByte2((Icon.FromHandle(shinfo.hIcon)).ToBitmap())); tag = "<a style=\"" + main_folder_a + "\" href=\"" + link + "\">" + "<div style=\"" + main_folder_div + "\"><img style=\"height:32px;width:32px;\" src='" + imgdata + "' /> " + ss + "</div></a>"; } catch (Exception) { Bitmap folderi = new Bitmap(easyNMP.Properties.Resources.folder); imgdata = "data:image/jpg;base64," + Convert.ToBase64String(ImageToByte2(folderi)); tag = "<a style=\"" + main_folder_a + "\" href=\"" + link + "\">" + "<div style=\"" + main_folder_div + "\"><img style=\"height:32px;width:32px;\" src='" + imgdata + "' /> " + ss + "</div></a>"; } sw.WriteLine(tag); } sw.WriteLine("<br></br><br></br>"); var files = Directory.GetFiles(dirPath); foreach (var f in files) { var link = ""; var ss = Path.GetFileName(f); if (UURRLL[UURRLL.Count() - 1] != '/') { UURRLL += "/"; } var imgdata = ""; link = UURRLL + ss; string tag = ""; try { if (isimage(Path.GetExtension(f))) { Image image = Image.FromFile(f); Image thumb = image.GetThumbnailImage(250, 200, () => false, IntPtr.Zero); imgdata = "data:image/jpg;base64," + Convert.ToBase64String(ImageToByte2(thumb)); tag = "<a style=\"" + main_image_a + "\" href=\"" + link + "\">" + "<div style=\"" + main_image_div + "\"><img style=\"" + main_image_img + "\" src='" + imgdata + "' />" + ss + "</div></a>"; } else if (isvideo(Path.GetExtension(f))) { var ffMpeg = new FFMpegConverter(); Stream ns = new MemoryStream(); ffMpeg.GetVideoThumbnail(f, ns, 8); imgdata = "data:image/jpg;base64," + Convert.ToBase64String(ImageToByte2(Bitmap.FromStream(ns).GetThumbnailImage(100, 100, null, new IntPtr()))); tag = "<a style=\"" + main_video_a + "\" href=\"" + link + "\">" + "<div style=\"" + main_video_div + "\"><img style=\"" + main_video_img + "\" src='" + imgdata + "' />" + ss + "</div></a>"; } else if (issound(Path.GetExtension(f))) { Bitmap folderi = new Bitmap(easyNMP.Properties.Resources.audio); imgdata = "data:image/jpg;base64," + Convert.ToBase64String(ImageToByte2(folderi)); tag = "<a style=\"" + main_audio_a + "\" href=\"" + link + "\">" + "<div style=\"" + main_audio_div + "\"><img style=\"" + main_audio_img + "\" src='" + imgdata + "' /> " + ss + "</div></a>"; } else { imgdata = "data:image/jpg;base64," + Convert.ToBase64String(ImageToByte2((Icon.ExtractAssociatedIcon(f)).ToBitmap())); tag = "<a style=\"" + main_file_a + "\" href=\"" + link + "\">" + "<div style=\"" + main_file_div + ";\"><img src='" + imgdata + "' />" + ss + "</div></a>"; } } catch (Exception) { Bitmap filei = new Bitmap(easyNMP.Properties.Resources.file); imgdata = "data:image/jpg;base64," + Convert.ToBase64String(ImageToByte2(filei)); tag = "<a style=\"" + main_other_a + "\" href=\"" + link + "\">" + "<div style=\"" + main_other_div + ";\"><img style=\"" + main_other_img + "\" src='" + imgdata + "' />" + ss + "</div></a>"; } sw.WriteLine(tag); } sw.WriteLine("</body></html>"); } context.Response.OutputStream.Close(); } catch (Exception) { } }
public static Dictionary <String, String> Upload(HttpRequestMessage Request, String SavePath, bool createThumb = false) { Dictionary <String, String> result = new Dictionary <String, String>(); String fileName; Guid id; Directory.CreateDirectory(SavePath); var streamProvider = new MultipartFormDataStreamProvider(SavePath); Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(p => { foreach (MultipartFileData fileData in streamProvider.FileData) { if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName)) { continue; } //if (new FileInfo(fileData.LocalFileName).Length > ServerSettings.MAX_SIZE_UPLOAD) //{ // File.Delete(fileData.LocalFileName); // continue; //} fileName = fileData.Headers.ContentDisposition.FileName; if (fileName.StartsWith("\"") && fileName.EndsWith("\"")) { fileName = fileName.Trim('"'); } if (fileName.Contains(@"/") || fileName.Contains(@"\")) { fileName = Path.GetFileName(fileName); } id = Guid.NewGuid(); AttachmentStore.Map(id, fileName); result.Add(fileName, id.ToString()); File.Move(fileData.LocalFileName, Path.Combine(SavePath, id.ToString())); if (createThumb) { if (VideoExtensions.Contains(Path.GetExtension(fileName), StringComparer.OrdinalIgnoreCase)) { var ffProbe = new FFProbe(); var videoInfo = ffProbe.GetMediaInfo(Path.Combine(SavePath, id.ToString())); FFMpegConverter converter = new FFMpegConverter(); converter.GetVideoThumbnail(Path.Combine(SavePath, id.ToString()), Path.Combine(SavePath, id.ToString() + "_thumb.jpg"), (float)videoInfo.Duration.TotalSeconds / 2); } if (ImageExtensions.Contains(Path.GetExtension(fileName), StringComparer.OrdinalIgnoreCase)) { Image image = Image.FromFile(Path.Combine(SavePath, id.ToString())); int w = image.Width, h = image.Height; if (image.Height > 300) { h = 300; w = image.Width * 300 / image.Height; } else if (image.Width > 500) { w = 500; h = image.Height * 500 / image.Width; } image.GetThumbnailImage(w, h, null, IntPtr.Zero).Save(Path.Combine(SavePath, id.ToString() + "_thumb.jpg")); image.Dispose(); } } } }).Wait(); return(result); }
public IHttpActionResult UploadVideo() { var files = HttpContext.Current.Request.Files; if (files.Count == 0) return Response(new { Success = false, Message = "No file uploaded" }); var file = files[0]; //and it's name var fileName = file.FileName; //file extension and it's type var fileExtension = Path.GetExtension(fileName); if (!string.IsNullOrEmpty(fileExtension)) fileExtension = fileExtension.ToLowerInvariant(); var contentType = file.ContentType; if (string.IsNullOrEmpty(contentType)) { contentType = VideoUtility.GetContentType(fileExtension); } if (contentType == string.Empty) { return Response(new { Success = false, Message = "Invalid file type" }); } var tickString = DateTime.Now.Ticks.ToString(); var savePath = Path.Combine(_mediaSettings.VideoSavePath, tickString + fileExtension); file.SaveAs(HostingEnvironment.MapPath(savePath)); //TODO: Create a standard controller for handling uploads //wanna generate the thumbnails for videos...ffmpeg is our friend var ffmpeg = new FFMpegConverter(); var thumbnailFilePath = Path.Combine(_mediaSettings.PictureSavePath) + tickString + ".thumb.jpg"; ffmpeg.GetVideoThumbnail(HostingEnvironment.MapPath(savePath), HostingEnvironment.MapPath(thumbnailFilePath)); //save the picture now return Json(new { Success = true, VideoUrl = savePath.Replace("~", ""), ThumbnailUrl = thumbnailFilePath.Replace("~", ""), MimeType = file.ContentType }); }
static void Main(string[] args) { var f = new FFMpegConverter(); // Get thumbnail at a specified time in seconds Console.WriteLine("Generating image..."); f.GetVideoThumbnail(@"C:\Users\npasumarthy\Downloads\Test.mp4", @"C:\Users\npasumarthy\Downloads\TestThumbnail.jpg", 3); //Extract Audio from Video Console.WriteLine("Extracting Audio..."); f.ConvertMedia(@"C:\Users\npasumarthy\Downloads\Test.mp4", @"C:\Users\npasumarthy\Downloads\Test2.mp3", "mp3"); // OCR the image // OcrFromUrl(); Console.WriteLine("OCR..."); String filename = @"C:\Users\npasumarthy\Downloads\TestThumbnail.jpg"; //filename = @"C:\Users\npasumarthy\Downloads\Demo.jpg"; //filename = @"C:\Users\npasumarthy\Downloads\Demo2.jpg"; var textFromImage = OcrFromFile(filename); Console.WriteLine(textFromImage); // Clean the Text retuned from OCR Console.WriteLine("Cleaning the OCR result"); var cleanedText = textFromImage.Replace(@"\n", ""); // Save the audio file and OCR file as response to client Console.WriteLine("OCR to Audio..."); String audioUrl = TextToSpeech(textFromImage); Console.WriteLine("\n\n" + audioUrl + "\n\n"); Process.Start("wmplayer.exe", audioUrl); }
private void VideoButtonConvert_Click(object sender, EventArgs e) { var fileCount = (from v in _vFiles where v.IsUsing == true select v).Count(); if (_vFiles.Count == 0 || fileCount == 0) { MessageBox.Show("Select at least one video file to start the convert process.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } DialogResult result = MessageBox.Show("Do you want to start the video converting process.", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.No) { return; } var parent = Task.Factory.StartNew (() => { var child = Task.Factory.StartNew(() => { this.Cursor = Cursors.WaitCursor; this.ButtonStatus(false); this.KillProcess(); try { FFMpegConverter converter = new FFMpegConverter(); converter.ConvertProgress += Convert_Progess; converter.LogReceived += Convert_Log; VideoProgressBarOverall.Maximum = fileCount; int counter = 0; float?frameTime = 30; string imageFilePath = string.Empty; string videoFilePath = string.Empty; string parameter = string.Empty; List <VideoFiles> files = (from v in _vFiles where v.IsUsing == true select v).ToList(); foreach (var item in files) { counter += 1; VideoProgressBarOverall.Value = counter; VideoProgressBarOverall.Refresh(); converter.FFMpegProcessPriority = ProcessPriorityClass.Normal; imageFilePath = string.Concat(_destination, _destination.Length == 3 ? string.Empty : @"\", counter.ToString(), ".jpeg"); videoFilePath = string.Concat(_destination, _destination.Length == 3 ? string.Empty : @"\", Path.GetFileNameWithoutExtension(item.FilePath), _extensions[item.Index].FileExtension); converter.GetVideoThumbnail(item.FilePath, imageFilePath, frameTime); using (FileStream imageStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read)) { pictureBoxThumbnail.BackgroundImageLayout = ImageLayout.Stretch; Image thumbnail = null; try { thumbnail = Image.FromStream(imageStream); } catch (Exception) { thumbnail = null; } imageStream.Flush(); imageStream.Close(); pictureBoxThumbnail.BackgroundImage = thumbnail; } switch (this.GetVideoFormat(_extensions[item.Index].FileExtension)) { case "swf": parameter = string.Format(" -qscale:v 1 -b:a 192k -crf {0} -q:a 0 -preset medium -threads 4 -ar 44100 -strict experimental -ab 192k ", _quality); break; case "webm": parameter = string.Format(" -b:v 1000M -crf {0} -c:v libvpx-vp9 -preset medium -c:a libvorbis -strict experimental -ab 128k ", _quality); break; case "mpeg": parameter = string.Format(" -b:v 2500 -b:a 192k -crf {0} -c:v mpeg2video -preset medium -c:a libmp3lame -threads 4 -ar 44100 -strict experimental -ab 192k ", _quality); break; //case "rm": // parameter = string.Format(" -b:v 2500 -b:a 192k -crf {0} -c:v libx264 -preset medium -c:a libfaac -threads 4 -ar 44100 -strict experimental -ab 192k ", _quality); // break; default: parameter = string.Format(" -b:v 2500 -b:a 128k -crf {0} -c:v libx264 -preset medium -c:a aac -threads 4 -ar 44100 -strict experimental -ab 128k ", _quality); break; } ConvertSettings setting = new ConvertSettings() { AppendSilentAudioStream = false, CustomOutputArgs = parameter }; converter.ConvertMedia(item.FilePath, this.GetVideoFormat(new FileInfo(item.FilePath).Extension), videoFilePath, this.GetVideoFormat(_extensions[item.Index].FileExtension), setting); } MessageBox.Show("Video file(s) converted successfully.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); Process.Start(_destination); } catch (FFMpegException fx) { MessageBox.Show(fx.Message, "Error - " + this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error - " + this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } this.KillProcess(); this.ButtonStatus(true); this.Reset(); this.Cursor = Cursors.Default; }); }, TaskCreationOptions.LongRunning ); }
public async Task <ActionResult> Upload(CreatePostViewModel viewModel) { var success = false; if (ModelState.IsValid) { var countOfAttachments = 0; var contentTypeArray = new string[] { "video/mp4" //"video/avi", //"application/x-mpegURL", //"video/MP2T", //"video/3gpp", //"video/quicktime", //"video/x-msvideo", //"video/x-ms-wmv" }; //create new post entity var post = new Post { PlateNumber = viewModel.PlateNumber, Description = HttpUtility.HtmlDecode(viewModel.Description), UserID = User.Identity.GetUserId(), DateUploaded = viewModel.DateUploaded, BranchID = CurrentUser.BranchID }; // I removed the foreach loop // and use this instead since the posted file will always be one // and for performance reason var item = viewModel.Attachments.FirstOrDefault(); //check if the item is null //or else throw an error if (item != null) { //check if the content type is an MP4 if (!contentTypeArray.Contains(item.ContentType)) { ModelState.AddModelError("", "video file must be an mp4 format"); return(Json(new { success = success, message = "Video file must be an mp4 format" })); } //increment the count of attachment countOfAttachments++; //get the fileName extension var videoExt = Path.GetExtension(item.FileName); //get the fileName var videoFileName = Path.GetFileName(item.FileName); //set the video path var videoPath = Server.MapPath("~/Uploads/Videos"); //set the thumbnail path var thumbnailPath = Server.MapPath("~/Uploads/Thumbnails"); //create new entity for each attachment var attachment = new PostAttachment(); attachment.PostAttachmentID = Guid.NewGuid().ToString(); attachment.FileName = attachment.PostAttachmentID + videoExt; attachment.MIMEType = item.ContentType; attachment.FileSize = item.ContentLength; attachment.FileUrl = Path.Combine(videoPath, attachment.FileName); attachment.DateCreated = viewModel.DateUploaded; attachment.AttachmentNo = $"Attachment {countOfAttachments.ToString()}"; attachment.ThumbnailFileName = attachment.PostAttachmentID + ".jpeg"; attachment.ThumbnailUrl = Path.Combine(thumbnailPath, attachment.ThumbnailFileName); //concatenate the path and the filename var videoToSaveBeforeConvertingPath = Path.Combine(videoPath, videoFileName); //save the video using (var fileStream = System.IO.File.Create(videoToSaveBeforeConvertingPath)) { var stream = item.InputStream; stream.CopyTo(fileStream); } //for conversion var ffMpeg = new FFMpegConverter(); //Set the path of the exe of FFMpeg ffMpeg.FFMpegToolPath = videoPath; //create a file instance var file = new FileInfo(videoToSaveBeforeConvertingPath); //check if the file exists after saving the video if (file.Exists) { //codec for mp4 var convertSettings = new ConvertSettings { AudioCodec = "aac", VideoCodec = "h264" }; //set the resolution convertSettings.SetVideoFrameSize(1280, 720); //convert the saved file //attachment.FileUrl is the new output filename ffMpeg.ConvertMedia(videoToSaveBeforeConvertingPath, Format.mp4, attachment.FileUrl, Format.mp4, convertSettings); //get the thumbnail of the video for ffMpeg.GetVideoThumbnail(attachment.FileUrl, attachment.ThumbnailUrl); //Once the conversion is successful delete the original file file.Delete(); //add the attachment to post entity post.Attachments.Add(attachment); } } //find the first attachment var attached = post.Attachments.FirstOrDefault(); //if the attachment is not null save it else throw an error if (attached != null) { //add the post entity and save _uow.Posts.Add(post); await _uow.SaveChangesAsync(); //fetch the end-users who have approval access var claims = await _uow.UserClaims.GetAllByClaimTypeAndValueAsync("Approval", "CanApproveVideo"); if (claims.Count > 0) { StringBuilder recipients = new StringBuilder(); //loop through and create a semicolon separated values //to be used in sending email notification to the supervisors claims.ForEach(claim => { recipients.Append(claim.User.Email) .Append(";"); }); //get the url of the posted video //to be included in the email var url = Request.Url.Scheme + "://" + Request.Url.Authority + Url.Action("post", new { year = post.DateUploaded.Year, month = post.DateUploaded.Month, postID = post.PostID, plateNo = post.PlateNumber }); //send email try { await _mgr.CustomSendEmailAsync( User.Identity.GetUserId(), "New posted video", EmailTemplate.GetTemplate( CurrentUser, "Supervisors", "I have posted a new video. Please see the details for approval.", url), recipients.ToString()); } catch (SmtpException ex) { _uow.AppLogs.Add(new AppLog { Message = ex.Message, Type = ex.GetType().Name, Url = Request.Url.ToString(), Source = (ex.InnerException != null) ? ex.InnerException.Message : string.Empty, UserName = User.Identity.Name, LogDate = DateTime.UtcNow }); await _uow.SaveChangesAsync(); success = true; return(Json(new { success = success, message = "Uploaded successfully" })); } } success = true; return(Json(new { success = success, message = "Uploaded successfully" })); } ModelState.AddModelError("", "Attached has not been succesfully uploaded"); } return(Json(new { success = success, message = "Something went wrong. Please try again" })); }
public FileDto SaveProfilePicture(HttpPostedFileBase file, string userId) { var agent = _dbContext.Users.Find(userId); if (agent == null) { throw new ArgumentNullException(nameof(agent)); } var uploadRelativePath = PathHelper.GetUploadRelativePath(userId); var fullFileName = HttpContext.Current.Server.MapPath(Path.Combine(uploadRelativePath, file.FileName)); var uploadThumbRelativePath = PathHelper.GetUploadThumbRelativePath(userId); var fullThumbName = HttpContext.Current.Server.MapPath(Path.Combine(uploadThumbRelativePath, file.FileName)); if (agent.Avatar != null) { DeleteAvatarByUserId(userId); } file.SaveAs(fullFileName); var wt24File = new Wt24File { Name = file.FileName, Mime = file.ContentType, Extension = Path.GetExtension(fullFileName), ContentLengthInBytes = file.ContentLength, RelativePath = Path.Combine(uploadRelativePath, file.FileName), Filetype = FileTypesHelper.FindTypeByExtension(fullFileName), }; if (FileTypesHelper.ImageExtensions.Any(c => c.ToLower() == Path.GetExtension(file.FileName).ToLower())) { var source = File.ReadAllBytes(fullFileName); using (var inStream = new MemoryStream(source)) { using (var imageFactory = new ImageFactory(preserveExifData: true)) { imageFactory.Load(inStream).Watermark(new TextLayer() { DropShadow = true, FontFamily = FontFamily.GenericSansSerif, Text = "wohnungstausch24", Style = FontStyle.Bold, FontColor = Color.Black, Opacity = 48, FontSize = 48 }) .Format(new JpegFormat()) .Save(fullFileName) .Resize(new ResizeLayer(new Size(240, 240), ResizeMode.Max)) .Save(fullThumbName); } } wt24File.Name = file.FileName; wt24File.ContentLengthInBytes = file.ContentLength; wt24File.Filetype = FileTypesHelper.FindTypeByExtension(fullFileName); wt24File.Mime = FileTypesHelper.GetMimeFromFile(fullFileName); wt24File.Extension = Path.GetExtension(fullFileName); wt24File.ThumbnailPath = Path.Combine(uploadThumbRelativePath, file.FileName); wt24File.RelativePath = Path.Combine(uploadRelativePath, file.FileName); } else if (FileTypesHelper.VideoExtensions.Any(c => c == Path.GetExtension(file.FileName))) { var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullFileName); var outputFormat = NReco.VideoConverter.Format.webm; var thumbName = fileNameWithoutExtension + ".jpg"; var newVideoFileName = outputFormat + "_" + FrameSize.hd720 + "_" + fileNameWithoutExtension + "." + outputFormat; var fullVideoThumbName = HttpContext.Current.Server.MapPath(Path.Combine(uploadThumbRelativePath, thumbName)); var convertedVideoRelativePath = Path.Combine(uploadRelativePath, newVideoFileName); var convertedVideoFullPath = HttpContext.Current.Server.MapPath(convertedVideoRelativePath); var ffMpeg = new FFMpegConverter(); var settings = new ConvertSettings { VideoFrameSize = FrameSize.hd480 }; FFMpegInput[] input = { new FFMpegInput(fullFileName) }; ffMpeg.ConvertMedia(input, convertedVideoFullPath, outputFormat, settings); ffMpeg.GetVideoThumbnail(convertedVideoFullPath, fullVideoThumbName); File.Delete(fullFileName); var fileInfo = new FileInfo(convertedVideoFullPath); wt24File.Filetype = FileTypesHelper.FindTypeByExtension(convertedVideoFullPath); wt24File.Mime = FileTypesHelper.GetMimeFromFile(convertedVideoFullPath); wt24File.Extension = Path.GetExtension(convertedVideoFullPath); wt24File.ContentLengthInBytes = (int)fileInfo.Length; wt24File.ThumbnailPath = Path.Combine(uploadThumbRelativePath, thumbName); wt24File.RelativePath = convertedVideoRelativePath; wt24File.Name = newVideoFileName; } agent.Avatar = wt24File; _dbContext.SaveChanges(); return(new FileDto { Name = wt24File.Name, Id = wt24File.Id, Length = wt24File.ContentLengthInBytes, FileUrl = wt24File.RelativePath, ThumbnailUrl = wt24File.ThumbnailPath, Filetype = FileTypesHelper.FindTypeByExtension(fullFileName), Extension = wt24File.Extension }); }
/// <summary> Загрузка изображения из середины видео по пути к файлу. </summary> public static BitmapImage LoadBitMapFromVideo(string path, int vidWidth, float vidPos) { BitmapImage coverImage = new BitmapImage(); if (string.IsNullOrWhiteSpace(path)) { return(coverImage); } FileInfo fi = new FileInfo(path); if (!fi.Exists) { return(coverImage); } using (MemoryStream memory = new MemoryStream()) { try { FFMpegConverter ffMpeg = new FFMpegConverter(); if (App.FoundFFMpegLibs) { ffMpeg.FFMpegToolPath = Properties.Settings.Default.FFMpegBinPath; } var imgWidth = Properties.Settings.Default.CoverMaxSize; if (vidWidth < imgWidth) { imgWidth = vidWidth; // формируем кавер размером с видео для экономии } ffMpeg.GetVideoThumbnail(path, memory, vidPos); memory.Position = 0; try { coverImage = new BitmapImage(); coverImage.BeginInit(); coverImage.StreamSource = memory; coverImage.CacheOption = BitmapCacheOption.OnLoad; coverImage.DecodePixelWidth = imgWidth; coverImage.EndInit(); coverImage.StreamSource = null; } catch (NotSupportedException ex2) { Console.WriteLine(ex2); coverImage = new BitmapImage(); } memory.Close(); memory.Dispose(); ffMpeg.Stop(); } catch (FFMpegException ex) { Console.WriteLine(ex); } catch (IOException ex3) { Console.WriteLine(ex3); } catch (ThreadAbortException ex4) { Console.WriteLine(ex4); } catch (Exception ex5) { Console.WriteLine(ex5); } } coverImage.Freeze(); // замораживаем только после избавления от стрима, иначе GC уже не может его ликвидировать return(coverImage); }
private static int CompressVideo(Cleanup.ResourceHandler pResourceHandler, string pFilePath, string pFilePathOut, int pAffinity) { ///////////////////////////// CREATE ARGUMENTS AND START COMPRESSING PROCESS ///////////////////////////// string arguments = ""; arguments += "-i " + pFilePath + " "; arguments += pFilePathOut; var process = new Process { StartInfo = new ProcessStartInfo { FileName = Settings.CompressionSettings.COMPRESSION_PROCESS_NAME, Arguments = arguments } }; try { process.Start(); process.ProcessorAffinity = (System.IntPtr)pAffinity; process.WaitForExit(); } catch (Exception e) { string err = e.ToString(); Console.WriteLine("Failed process image: " + err); return(-1); } ///////////////////////////// THIS IS THE SAME CODE I'VE GOT, IT CREATES THUMBNAIL ///////////////////////////// string compressedFolder = Path.GetDirectoryName(pFilePath); string compressed = pFilePathOut; var ffMpegConverter = new FFMpegConverter(); string fileNameNoExt = Path.GetFileNameWithoutExtension(pFilePath); string outputFolder = Path.GetDirectoryName(pFilePathOut); string tempfile = Path.Combine(outputFolder, "temp.jpeg"); string thumbnail = Path.Combine(outputFolder, fileNameNoExt + "_thumbnail.jpeg"); ffMpegConverter.GetVideoThumbnail(pFilePathOut, tempfile); int width = 120; int resWidth = 72; int resHeight = 72; var imgInput = new System.Drawing.Bitmap(tempfile); // Initialize from Settings. width = ImageHelper.GetImageType(imgInput.Width * imgInput.Height); resWidth = Settings.ThumbnailSettings.RESOLUTION_WIDTH; resHeight = Settings.ThumbnailSettings.RESOLUTION_HEIGHT; double y = imgInput.Height; double x = imgInput.Width; var imgOutput = new System.Drawing.Bitmap(width, (int)(y * width / x)); imgOutput.SetResolution(resWidth, resHeight); // Set DPI of image (xDpi, yDpi) System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(imgOutput); graphics.Clear(System.Drawing.Color.White); graphics.DrawImage(imgInput, new System.Drawing.Rectangle(0, 0, width, (int)(y * width / x)), new System.Drawing.Rectangle(0, 0, (int)x, (int)y), System.Drawing.GraphicsUnit.Pixel); // Alright, overwriting doesn't work, so save as temp file then resize and remove temp file. imgOutput.Save(thumbnail, System.Drawing.Imaging.ImageFormat.Jpeg); imgInput.Dispose(); File.Delete(tempfile); return(0); }
public void WriteVideoThumbnailPicture(string videoFilePath, string imageFilePath, PictureSize size, float? frameTime) { var ffmpeg = new FFMpegConverter(); ffmpeg.GetVideoThumbnail(videoFilePath, imageFilePath, frameTime); }
public void WriteVideoThumbnailPicture(string videoFilePath, string imageFilePath, PictureSize size, float?frameTime) { var ffmpeg = new FFMpegConverter(); ffmpeg.GetVideoThumbnail(videoFilePath, imageFilePath, frameTime); }
private void GetScrin() { Progress(1); ProgressVisibl(true); this.files_a_scrinTableAdapter.Fill(this.anime_ArchiveDataSet.files_a_scrin); DataTable dt = files_a_scrinTableAdapter.GetData(); int count = dt.Rows.Count * 15 + 3; int p = 0; for (int j = 0; j < dt.Rows.Count; j++) { try { FFMpegConverter ffMpeg = new FFMpegConverter(); MediaInfoLib.MediaInfo mi = new MediaInfoLib.MediaInfo(); MediaInfoDotNet.MediaFile m = new MediaFile(dt.Rows[j]["Path_s"].ToString()); List<Image> images = new List<Image>(); TimeSpan ts = TimeSpan.FromMilliseconds(m.duration); int col = 15; int period = Convert.ToInt32(ts.TotalSeconds) / col; int w = 0, h = 0, column = 3; for (int i = 1; i <= col; i++) { p++; Progress((p * 100) / count); MemoryStream ms = new MemoryStream(); Image image; ffMpeg.GetVideoThumbnail(dt.Rows[j]["Path_s"].ToString(), ms, i * period); if (ms.Length == 0) continue; image = Image.FromStream(ms); w = image.Width; h = image.Height; //pictureBox1.Image = image; images.Add(image); } Image mm = Draw(images, w, h, column); mm = ResizeImg(mm, 30); MemoryStream mem = new MemoryStream(); mm.Save(mem, System.Drawing.Imaging.ImageFormat.Bmp); files_a_scrinTableAdapter.Update(ReadBytesFromImage(mem), Convert.ToInt32(dt.Rows[j]["kod_files"])); } catch (Exception ex) { continue; } } Progress(100); ProgressVisibl(false); }
private void button2_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { FFMpegConverter ffMpeg = new FFMpegConverter(); MediaInfoLib.MediaInfo mi = new MediaInfoLib.MediaInfo(); MediaInfoDotNet.MediaFile m = new MediaFile(openFileDialog1.FileName); List<Image> images = new List<Image>(); TimeSpan ts = TimeSpan.FromMilliseconds(m.duration); int col = 15; int period = Convert.ToInt32(ts.TotalSeconds) / col; int w=0, h=0, column = 3; for (int i = 1; i <= col; i++) { MemoryStream ms = new MemoryStream(); Image image; ffMpeg.GetVideoThumbnail(openFileDialog1.FileName, ms, i * period); image = Image.FromStream(ms); w = image.Width; h = image.Height; //pictureBox1.Image = image; images.Add(image); } Image mm = Draw(images, w, h, column); mm = ResizeImg(mm, 28); pictureBox1.Image = mm; } }