Example #1
1
        /***********************************************************************************************
        * BackupAndUpdateSize / 2015-05-24 / Wethospu                                                 *
        *                                                                                             *
        * Downloads a backup of given media. Also updates media size file.                            *
        *                                                                                             *
        * url: Url to download.                                                                       *
        *                                                                                             *
        ***********************************************************************************************/
        public static void BackupAndUpdateSize(string url)
        {
            if (!Constants.DownloadData)
            return;
              // Use the last part of url as the file name.
              var split = url.Split('/');
              var fileName = split[split.Length - 1];
              fileName = fileName.Replace("\\", "").Replace("\"", "");
              fileName = Constants.BackupLocation + fileName;
              // Check whether to download the file.
              if (Path.GetExtension(fileName).Length == 0)
            return;
              // Check whether the file has already been downloaded and checked.
              if (downloadData.Contains(url))
            return;

              downloadData.Add(url);
              // Create directory if needed.
              var dirName = Path.GetDirectoryName(fileName);
              if (dirName != null)
            Directory.CreateDirectory(dirName);
              // Download the file if it doesn't exist.
              if (!File.Exists(fileName))
              {
            using (var client = new WebClient())
            {
              var row = Console.CursorTop;
              try
              {

            Console.Write("Downloading " + url);
            client.DownloadFile(url, fileName);
            Helper.ClearConsoleLine(row);
              }
              catch (WebException)
              {
            Helper.ClearConsoleLine(row);
            Helper.ShowWarningMessage("File \"" + url + "\" can't be downloaded.");
              }
            }
              }
              // If file exists, update its size data.
              if (!File.Exists(fileName))
            return;
              int width = 0;
              int height = 0;
              if (Path.GetExtension(fileName).Equals(".jpg") || Path.GetExtension(fileName).Equals(".png") || Path.GetExtension(fileName).Equals(".bmp"))
              {
            // Built-in system works for standard images.
            Image image = Image.FromFile(fileName);
            width = image.Width;
            height = image.Height;
            GenerateThumbs(fileName, Constants.ThumbWidth, Constants.ThumbHeight);
            GenerateThumbs(fileName, Constants.ThumbWidthSmall, Constants.ThumbHeightSmall);
              }
              if (Path.GetExtension(fileName).Equals(".gif"))
              {
            // Gif has to be checked manually.
            byte[] bytes = new byte[10];
            using (FileStream fs = File.OpenRead(fileName))
            {
              fs.Read(bytes, 0, 10); // type (3 bytes), version (3 bytes), width (2 bytes), height (2 bytes)
            }
            width = bytes[6] | bytes[7] << 8; // byte 6 and 7 contain the width but in network byte order so byte 7 has to be left-shifted 8 places and bit-masked to byte 6
            height = bytes[8] | bytes[9] << 8; // same for height
            GenerateThumbs(fileName, Constants.ThumbWidth, Constants.ThumbHeight);
            GenerateThumbs(fileName, Constants.ThumbWidthSmall, Constants.ThumbHeightSmall);
              }
              if (Path.GetExtension(fileName).Equals(".webm"))
              {
            var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
            var jpgFileName = Directory.GetCurrentDirectory() + "\\" + Path.GetDirectoryName(fileName) + "\\" +  Path.GetFileNameWithoutExtension(fileName) + ".jpg";
            ffMpeg.GetVideoThumbnail(Directory.GetCurrentDirectory() + "\\" + fileName, jpgFileName);
            Image image = Image.FromFile(jpgFileName);
            width = image.Width;
            height = image.Height;
            GenerateThumbs(jpgFileName, Constants.ThumbWidth, Constants.ThumbHeight);
            GenerateThumbs(jpgFileName, Constants.ThumbWidthSmall, Constants.ThumbHeightSmall);
              }
              if (Constants.MediaSizes.ContainsKey(url))
            Constants.MediaSizes[url] = new int[] { width, height };
              else
            Constants.MediaSizes.Add(url, new int[] { width, height });
        }
Example #2
1
 protected void publish_import_upload_OnFileUploaded(object sender, FileUploadedEventArgs e)
 {
     var id = CurrentResource.Id;
     var file = e.File;
     var tempId = HomoryContext.Value.GetId();
     var suffix = file.GetExtension().Replace(".", "").ToLower();
     var path = string.Format("../Common/资源/{0}/{1}/{2}.{3}", CurrentUser.Id.ToString().ToUpper(), ResourceType.ToString(),
         tempId.ToString().ToUpper(), ResourceType == ResourceType.视频 ? suffix == "flv" ? suffix : "mp4" : "pdf");
     var pathX = Server.MapPath(path);
     var source = string.Format("../Common/资源/{0}/{1}/{2}.{3}", CurrentUser.Id.ToString().ToUpper(), ResourceType.ToString(),
         tempId.ToString().ToUpper(), suffix);
     var sourceX = Server.MapPath(source);
     var cpic = path.Replace(".pdf", ".jpg").Replace(".flv", ".jpg").Replace(".mp4", ".jpg");
     var cpicX = pathX.Replace(".pdf", ".jpg").Replace(".flv", ".jpg").Replace(".mp4", ".jpg");
     var res = HomoryContext.Value.Resource.Single(o => o.Id == id);
     file.SaveAs(sourceX, true);
     switch (suffix)
     {
         case "doc":
         case "docx":
         case "txt":
         case "rtf":
             var docW = new Aspose.Words.Document(sourceX);
             docW.Save(pathX, Aspose.Words.SaveFormat.Pdf);
             docW.Save(cpicX, Aspose.Words.SaveFormat.Jpeg);
             res.Image = cpic;
             res.FileType = ResourceFileType.Word;
             res.Thumbnail = ((int)ResourceFileType.Word).ToString();
             break;
         case "ppt":
         case "pptx":
             var docP = new Aspose.Slides.Presentation(sourceX);
             docP.Save(pathX, Aspose.Slides.Export.SaveFormat.Pdf);
             var tcdocp = new Aspose.Pdf.Document(pathX);
             using (var imageStream = new FileStream(cpicX, FileMode.Create))
             {
                 var resolution = new Resolution(300);
                 var jpegDevice = new JpegDevice(resolution, 100);
                 jpegDevice.Process(tcdocp.Pages[1], imageStream);
                 imageStream.Close();
             }
             res.Image = cpic;
             res.FileType = ResourceFileType.Powerpoint;
             res.Thumbnail = ((int)ResourceFileType.Powerpoint).ToString();
             break;
         case "xls":
         case "xlsx":
             var docE = new Aspose.Cells.Workbook(sourceX);
             docE.Save(pathX, Aspose.Cells.SaveFormat.Pdf);
             var tcdoce = new Aspose.Pdf.Document(pathX);
             using (var imageStream = new FileStream(cpicX, FileMode.Create))
             {
                 var resolution = new Resolution(300);
                 var jpegDevice = new JpegDevice(resolution, 100);
                 jpegDevice.Process(tcdoce.Pages[1], imageStream);
                 imageStream.Close();
             }
             res.Image = cpic;
             res.FileType = ResourceFileType.Excel;
             res.Thumbnail = ((int)ResourceFileType.Excel).ToString();
             break;
         case "pdf":
             var tcdoc = new Aspose.Pdf.Document(pathX);
             using (var imageStream = new FileStream(cpicX, FileMode.Create))
             {
                 var resolution = new Resolution(300);
                 var jpegDevice = new JpegDevice(resolution, 100);
                 jpegDevice.Process(tcdoc.Pages[1], imageStream);
                 imageStream.Close();
             }
             res.Image = cpic;
             res.FileType = ResourceFileType.Pdf;
             res.Thumbnail = ((int)ResourceFileType.Pdf).ToString();
             break;
         case "avi":
         case "mpg":
         case "mpeg":
         case "flv":
         case "mp4":
         case "rm":
         case "rmvb":
         case "wmv":
             NReco.VideoConverter.FFMpegConverter c = new NReco.VideoConverter.FFMpegConverter();
             c.GetVideoThumbnail(sourceX, cpicX, 2F);
             //if (!sourceX.EndsWith("flv", StringComparison.OrdinalIgnoreCase))
             //{
             //    c.ConvertMedia(sourceX, pathX, NReco.VideoConverter.Format.flv);
             //}
             res.Image = cpic;
             res.FileType = ResourceFileType.Media;
             res.Thumbnail = ((int)ResourceFileType.Media).ToString();
             break;
     }
     res.SourceName = file.GetName();
     res.Title = file.GetNameWithoutExtension();
     res.Source = source;
     res.Preview = path;
     res.Converted = true;
     HomoryContext.Value.SaveChanges();
 }
Example #3
0
        void refresh()
        {
            //превью
            var ffMpeg = new NReco.VideoConverter.FFMpegConverter();

            //работа с файлами
            string[] files = Directory.GetFiles("wallpapers", "*.mp4");



            foreach (string paths in files)
            {
                PictureBox pictureBox = new PictureBox();
                pictureBox.Width  = 400;
                pictureBox.Height = 240;
                string path = Path.GetFileName(paths);
                string name = path.Substring(0, path.Length - 4);
                if (!File.Exists(@"cahed_preview\" + name + ".jpg"))
                {
                    ffMpeg.GetVideoThumbnail(paths, @"cahed_preview\" + name + ".jpg");
                }
                pictureBox.Name     = path;
                pictureBox.SizeMode = pictureBox1.SizeMode;
                pictureBox.Image    = Image.FromFile(@"cahed_preview\" + name + ".jpg");
                pictureBox.Text     = path;
                pictureBox.Click   += new System.EventHandler(this.pictureClick);
                this.flowLayoutPanel1.Controls.Add(pictureBox);
            }
        }
        public void RetrieveVideoTile(List <TechVideoVM> vm)
        {
            foreach (var item in vm)
            {
                var localfn = Server.MapPath(item.VPath);
                if (System.IO.File.Exists(localfn))
                {
                    var onlyname = System.IO.Path.GetFileNameWithoutExtension(localfn);

                    var mp4name = System.IO.Path.GetFileName(localfn);
                    var imgpath = localfn.Replace(mp4name, "") + onlyname + ".jpg";

                    if (System.IO.File.Exists(imgpath))
                    {
                        item.IPath = item.VPath.Replace(mp4name, "") + onlyname + ".jpg";
                    }
                    else
                    {
                        var ffMpeg2 = new NReco.VideoConverter.FFMpegConverter();
                        ffMpeg2.GetVideoThumbnail(localfn, imgpath);
                        item.IPath = item.VPath.Replace(mp4name, "") + onlyname + ".jpg";
                    }
                } //video file exist
            }     //foreach
        }
Example #5
0
        public static void CreateSingleThumbnail(string homepath, string setName, string topicName, string videoPath)
        {
            //Thumb folder (save location)
            string topicfolder = Path.Combine(homepath, setName, topicName, "Videos", "Thumbnails");
            var    ffMpeg      = new NReco.VideoConverter.FFMpegConverter();

            string oldImage = "";

            //If thumbnail doesn't exist, extract frame from video with a 'D' prefix
            if (!File.Exists(topicfolder + @"\" + Path.GetFileNameWithoutExtension(videoPath) + ".jpg"))
            {
                ffMpeg.GetVideoThumbnail(videoPath, topicfolder + @"\D" + Path.GetFileNameWithoutExtension(videoPath) + ".jpg", 5);
                oldImage = topicfolder + @"\D" + Path.GetFileNameWithoutExtension(videoPath) + ".jpg";
            }

            if (oldImage != "")
            {
                Bitmap newImage = new Bitmap(260, 130);
                using (Graphics gr = Graphics.FromImage(newImage))
                {
                    gr.SmoothingMode     = SmoothingMode.HighQuality;
                    gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    gr.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                    using (Image img = Image.FromFile(oldImage))
                    {
                        gr.DrawImage(img, new Rectangle(0, 0, 260, 130));
                    }
                }
                var newfilename = Path.Combine(topicfolder, Path.GetFileNameWithoutExtension(oldImage).Remove(0, 1) + ".jpg"); //Generate filename without .ext
                newImage.Save(@newfilename, ImageFormat.Jpeg);                                                                 //Save small thumbnail
                File.Delete(oldImage);
            }
        }
Example #6
0
        private List <string> disintegrateVideoToImages(string userRegistrationVideoLocation)
        {
            List <string> userRegImageLocations = new List <string>();

            if (String.IsNullOrWhiteSpace(userRegistrationVideoLocation) == false)
            {
                var    extractHelper = new NReco.VideoConverter.FFMpegConverter();
                Stream imageStream   = new MemoryStream()
                {
                    Position = 0
                };
                extractHelper.GetVideoThumbnail(userRegistrationVideoLocation, imageStream, 0);
                imageStream.Position = 0;
                uploadFileToStorage(imageStream, "userImage.jpg");
                //var userRegistrationImageLocation = "userImage_#.jpg";
                //var extractHelper = new NReco.VideoConverter.FFMpegConverter();
                //List<float> frameLocations = new List<float>() { 0.3f, 1.0F, 1.5f};
                //foreach (float frameLocation in frameLocations)
                //{
                //    using (Stream imageStream = new MemoryStream())
                //    {
                //        extractHelper.GetVideoThumbnail(userRegistrationVideoLocation, imageStream, frameLocation);
                //        imageStream.Position = 0;
                //        uploadFileToStorage(imageStream, userRegistrationImageLocation.Replace("#", frameLocations.IndexOf(frameLocation).ToString()));
                //    }
                //    userRegImageLocations.Add(string.Concat(storedFilePrefix, userRegistrationImageLocation.Replace("#", frameLocations.IndexOf(frameLocation).ToString())));
                //}
            }
            return(userRegImageLocations);
        }
Example #7
0
        private List <string> GetVideoFile()
        {
            var ret = new List <string>();

            try
            {
                foreach (string fl in Request.Files)
                {
                    if (fl != null && Request.Files[fl].ContentLength > 0)
                    {
                        var allvtype = "mp4,mp3,h264,wmv,wav,avi,flv,mov,mkv,webm,ogg";
                        var ext      = Path.GetExtension(Request.Files[fl].FileName).ToLower().Replace(".", "").Trim();
                        if (allvtype.Contains(ext))
                        {
                            string datestring = DateTime.Now.ToString("yyyyMMdd");
                            string imgdir     = Server.MapPath("~/userfiles") + "\\docs\\" + datestring + "\\";
                            if (!Directory.Exists(imgdir))
                            {
                                Directory.CreateDirectory(imgdir);
                            }

                            var fn = Path.GetFileName(Request.Files[fl].FileName)
                                     .Replace(" ", "_").Replace("#", "")
                                     .Replace("&", "").Replace("?", "").Replace("%", "").Replace("+", "");
                            fn = Path.GetFileNameWithoutExtension(fn) + "-" + DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetExtension(fn);
                            var onlyname = Path.GetFileNameWithoutExtension(fn);

                            var srcvfile = imgdir + fn;
                            //store file to local
                            Request.Files[fl].SaveAs(srcvfile);

                            var imgname = onlyname + ".jpg";
                            var imgpath = imgdir + imgname;
                            var ffMpeg  = new NReco.VideoConverter.FFMpegConverter();
                            ffMpeg.GetVideoThumbnail(srcvfile, imgpath);

                            var oggname = onlyname + ".ogg";
                            var oggpath = imgdir + oggname;
                            var ffMpeg1 = new NReco.VideoConverter.FFMpegConverter();
                            ffMpeg1.ConvertMedia(srcvfile, oggpath, NReco.VideoConverter.Format.ogg);

                            if (!ext.Contains("mp4"))
                            {
                                var mp4name = onlyname + ".mp4";
                                var mp4path = imgdir + mp4name;
                                var ffMpeg2 = new NReco.VideoConverter.FFMpegConverter();
                                ffMpeg2.ConvertMedia(srcvfile, mp4path, NReco.VideoConverter.Format.mp4);
                            }

                            var url = "/userfiles/docs/" + datestring + "/" + onlyname;
                            ret.Add(url);
                        } //end if ext
                    }     //file is not null
                }         //foreach
            }
            catch (Exception ex)
            { ret.Clear(); }

            return(ret);
        }
Example #8
0
        private void button1_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog()
            {
                Multiselect = true, ValidateNames = true, Filter = "WMV|*.wmv|WAV|*.wav|MP3*|*.mp3|MP4|*.mp4|MKV|*.mkv"
            })
            {
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    this.axWindowsMediaPlayer1.URL = ofd.FileName;
                    axWindowsMediaPlayer1.Ctlcontrols.stop();
                }

                button1.Hide();

                label2.Text = "Title: " + axWindowsMediaPlayer1.currentMedia.name; // name of video

                var player = new WindowsMediaPlayer();
                var clip   = player.newMedia(ofd.FileName);
                label3.Text = "Length: " + TimeSpan.FromSeconds(clip.duration).ToString(); // length of video

                var ffMpeg = new NReco.VideoConverter.FFMpegConverter();

                string namepicture = axWindowsMediaPlayer1.currentMedia.name + ".jpg";
                ffMpeg.GetVideoThumbnail(ofd.FileName, namepicture); // using FFMPEG to take first photo of video


                pictureBox1.Image = Image.FromFile(namepicture); // saving picture into pictureBox
            }
        }
Example #9
0
        static void Main(string[] args)
        {
            var ffMpeg = new NReco.VideoConverter.FFMpegConverter();

            ffMpeg.GetVideoThumbnail("input file path", "output_thumbnail_file.jpg");

            Console.Write("Thumbnail Created.");
        }
        public void GetThumbnail(ref Submission submission, string mimeType)
        {
            if (submission.Type == SubmissionTypes.Image || submission.Type == SubmissionTypes.Video)
            {
                var mime = mimeType.Split('/');

                var fileName = "images/posts/" + submission.AuthorId + "-" + submission.Date.ToBinary() + "." + mime[1];
                var imgName  = "images/posts/" + submission.AuthorId + "-" + submission.Date.ToBinary() + ".jpg";

                // Create folders if they don't exist already
                if (!Directory.Exists(GetServerPath("images")))
                {
                    Directory.CreateDirectory(GetServerPath("images"));
                }
                if (!Directory.Exists(GetServerPath("images/posts")))
                {
                    Directory.CreateDirectory(GetServerPath("images/posts"));
                }

                if (submission.IsHosted)
                {
                    using (var webClient = new WebClient())
                    {
                        webClient.DownloadFile(submission.Url, GetServerPath(fileName));
                        submission.Url = fileName;
                    }
                }

                submission.Img = submission.Url;

                try
                {
                    if (submission.Type == SubmissionTypes.Image && mime[1] == "gif")
                    {
                        submission.Img = imgName;

                        var path = submission.IsHosted ? GetServerPath(submission.Url) : submission.Url;
                        using (var img = System.Drawing.Image.FromFile(path))
                        {
                            var imgPath = GetServerPath(submission.Img);
                            img.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                        }
                    }
                    else if (submission.Type == SubmissionTypes.Video)
                    {
                        submission.Img = imgName;

                        var path   = submission.IsHosted ? GetServerPath(submission.Url) : submission.Url;
                        var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
                        ffMpeg.GetVideoThumbnail(path, GetServerPath(submission.Img), 0);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.GetBaseException());
                }
            }
        }
Example #11
0
        // Mo file
        private void bunifuImageButton13_Click(object sender, EventArgs e)
        {
            if (Now__Video_Mode)
            {
                OpenFileDialog openFileDialog1 = new OpenFileDialog();
                openFileDialog1.Filter = "Media Files|*.mpg;*.avi;*.wma;*.mov;*.wav;*mkv;*mp4;|All Files|*.*";

                openFileDialog1.Multiselect = true;
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    var path  = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    var path1 = "";
                    path  = Path.Combine(path, "Save Video");
                    path1 = path;
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    List <string> myList = new List <string>();
                    foreach (string file in openFileDialog1.FileNames)
                    {
                        myList.Add(System.IO.Path.GetFullPath(file));
                    }
                    path = Path.Combine(path, "Meow.txt");
                    TextWriter tsw = new StreamWriter(path, true);
                    foreach (string vidPath in myList)
                    {
                        var imgPath = System.IO.Path.Combine(path1, menu1.getFileName(vidPath)) + ".bmp";
                        if (!File.Exists(imgPath))
                        {
                            var    ffMpeg = new NReco.VideoConverter.FFMpegConverter();
                            Bitmap bmp    = new Bitmap(0, 0);
                            bmp.Save(imgPath);
                            ffMpeg.GetVideoThumbnail(vidPath, imgPath, 1);
                        }
                        tsw.WriteLine(vidPath);
                    }
                    tsw.Close();
                    menu1.Menu_Refresh();
                }
            }
            else
            {
                //Chọn nhạc
                OpenFileDialog List = new OpenFileDialog();
                List.Multiselect = true;
                if (List.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    files = List.SafeFileNames; // Lưu tên bài nhạc vào trong mảng files
                    paths = List.FileNames;     //Lưu đường dẫn nhạc vào mảng paths
                                                //Hiển thị tên nhạc trong PlayList
                    for (int i = 0; i < files.Length; i++)
                    {
                        music_Menu1.listBox1.Items.Add(files[i]);
                    }
                }
            }
        }
        public void GetThumbnail(ref Submission submission, string mimeType)
        {
            if (submission.Type == SubmissionTypes.Image || submission.Type == SubmissionTypes.Video)
            {
                var mime = mimeType.Split('/');

                var fileName = "images/posts/" + submission.AuthorId + "-" + submission.Date.ToBinary() + "." + mime[1];
                var imgName = "images/posts/" + submission.AuthorId + "-" + submission.Date.ToBinary() + ".jpg";

                // Create folders if they don't exist already
                if (!Directory.Exists(GetServerPath("images")))
                {
                    Directory.CreateDirectory(GetServerPath("images"));
                }
                if (!Directory.Exists(GetServerPath("images/posts")))
                {
                    Directory.CreateDirectory(GetServerPath("images/posts"));
                }

                if (submission.IsHosted)
                {
                    using (var webClient = new WebClient())
                    {
                        webClient.DownloadFile(submission.Url, GetServerPath(fileName));
                        submission.Url = fileName;
                    }
                }

                submission.Img = submission.Url;

                try
                {
                    if (submission.Type == SubmissionTypes.Image && mime[1] == "gif")
                    {
                        submission.Img = imgName;

                        var path = submission.IsHosted ? GetServerPath(submission.Url) : submission.Url;
                        using (var img = System.Drawing.Image.FromFile(path))
                        {
                            var imgPath = GetServerPath(submission.Img);
                            img.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                        }
                    }
                    else if (submission.Type == SubmissionTypes.Video)
                    {
                        submission.Img = imgName;

                        var path = submission.IsHosted ? GetServerPath(submission.Url) : submission.Url;
                        var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
                        ffMpeg.GetVideoThumbnail(path, GetServerPath(submission.Img), 0);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.GetBaseException());
                }
            }
        }
        public async Task <ActionResult> Edit(AdvertiseViewModel model, HttpPostedFileBase fileUpload)
        {
            var token = _userSession.BearerToken;

            if (fileUpload == null && String.IsNullOrEmpty(model.Resouce))
            {
                ModelState.AddModelError("Resouce", "Vui lòng chọn hình ảnh");
            }

            if (ModelState.IsValid)
            {
                if (fileUpload != null)
                {
                    string name = "";
                    if (fileUpload.ContentType.Contains("image"))
                    {
                        FileManagement.UploadImage(fileUpload, ValueConstant.IMAGE_ADVERTISE_PATH, ref name);
                        model.Type    = (byte)ValueConstant.MEDIA_TYPE.IMAGE;
                        model.Resouce = name;
                    }
                    else
                    {
                        FileManagement.UploadFile(fileUpload, ValueConstant.IMAGE_ADVERTISE_PATH, ref name);
                        string pathVideo = Server.MapPath(name);
                        model.Type = (byte)ValueConstant.MEDIA_TYPE.VIDEO;

                        string   pathThumbnail = Server.MapPath(ValueConstant.IMAGE_ADVERTISE_PATH);
                        var      ffMpeg        = new NReco.VideoConverter.FFMpegConverter();
                        string[] arrTemp       = fileUpload.FileName.Split('.');
                        string   fileName      = pathThumbnail + "/" + arrTemp[0] + ".jpg";
                        ffMpeg.GetVideoThumbnail(pathVideo, fileName, 10.0f);
                        model.Resouce = name.Replace(fileUpload.FileName, arrTemp[0] + ".jpg");
                    }
                }

                //Call API Provider
                string strUrl = APIProvider.APIGenerator(controllerName, APIConstant.ACTION_UPDATE);
                var    result = await APIProvider.Authorize_DynamicTransaction <AdvertiseViewModel, bool>(model, token, strUrl, APIConstant.API_Resource_CMS, ARS.IgnoredARS);


                if (result)
                {
                    TempData["Alert"] = ApplicationGenerator.RenderResult(ApplicationGenerator.TypeResult.SUCCESS, ApplicationGenerator.GeneralActionMessage(APIConstant.ACTION_UPDATE, ApplicationGenerator.TypeResult.SUCCESS));
                }
                else
                {
                    TempData["Alert"] = ApplicationGenerator.RenderResult(ApplicationGenerator.TypeResult.FAIL, ApplicationGenerator.GeneralActionMessage(APIConstant.ACTION_UPDATE, ApplicationGenerator.TypeResult.FAIL));
                }
                return(RedirectToAction("Index"));
            }
            else
            {
                TempData["Alert"] = ApplicationGenerator.RenderResult(ApplicationGenerator.TypeResult.FAIL, ApplicationGenerator.GeneralActionMessage(APIConstant.ACTION_UPDATE, ApplicationGenerator.TypeResult.FAIL));
                return(View(model));
            }
        }
Example #14
0
        protected virtual string MakeVideoThumbnail(string filePath)
        {
            string outputFile = filePath + ".jpeg";

            var ffMpeg = new NReco.VideoConverter.FFMpegConverter();

            ffMpeg.GetVideoThumbnail(filePath, outputFile);

            return(outputFile);
        }
Example #15
0
        public string getImageFromVideo(string name, string videopath)
        {
            string sourceVideoFolder      = ConfigurationSettings.AppSettings.Get("PhysicalSiteDataDirectory") + @"\video\";
            string sourceVideoImageFolder = ConfigurationSettings.AppSettings.Get("PhysicalSiteDataDirectory") + @"\_thumbs\Videos\";

            var ffMpeg = new NReco.VideoConverter.FFMpegConverter();

            ffMpeg.GetVideoThumbnail(sourceVideoFolder + url_video, sourceVideoImageFolder + name + ".jpg");
            return("/UploadStore/Videos/" + name + ".jpg");
        }
Example #16
0
        public ActionResult Upload(VideoViewModel model, HttpPostedFileBase file)
        {
            if (model != null && file != null)
            {
                var           filename = ImageNameGenerator.VideoIsmiUret(file);
                var           imgname  = ImageNameGenerator.FotoIsmiUret(file);
                StringBuilder sBuilder = new StringBuilder();
                sBuilder.Append(imgname);
                sBuilder.Append(".jpeg");
                imgname         = sBuilder.ToString();
                model.videoName = filename;
                model.frameName = imgname;
                var path = "null";
                if (file != null)
                {
                    path = Path.Combine(Server.MapPath("~/Content/Videos/"), filename);
                    file.SaveAs(path);
                    imgname = Path.Combine(Server.MapPath("~/Content/Images/"), imgname);
                    var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
                    ffMpeg.GetVideoThumbnail(path, imgname, 5);
                    ShellFile so = ShellFile.FromFilePath(path);
                    double    nanoseconds;
                    double.TryParse(so.Properties.System.Media.Duration.Value.ToString(),
                                    out nanoseconds);

                    if (nanoseconds > 0)
                    {
                        double seconds     = Convert100NanosecondsToMilliseconds(nanoseconds) / 1000;
                        int    ttl_seconds = Convert.ToInt32(seconds);
                        model.duration = TimeSpan.FromSeconds(ttl_seconds);
                    }
                }
                res = vManager.VideoYukle(model);
                if (res.Errors.Count > 0)
                {
                    res.Errors.ForEach(x => ModelState.AddModelError("", x.Message));
                    foreach (ErrorMessageObj obj in res.Errors)
                    {
                        if (obj.Code == ErrorMessageCode.VideoDurationLimit)
                        {
                            System.IO.File.Delete(path);
                            System.IO.File.Delete(imgname);
                        }
                    }
                    return(View());
                }
                else
                {
                    vtManager.SplitTagsAndSave(model.videoTag, res.Result.videoNo);
                }
                return(RedirectToAction("Index", "Home"));
            }
            return(View());
        }
        private string[] UploadVideo(HttpPostedFileBase fileUpload, string pathVideo)
        {
            string pathThumbnail = Server.MapPath(ValueConstant.IMAGE_ADVERTISE_PATH);
            var    ffMpeg        = new NReco.VideoConverter.FFMpegConverter();

            string[] arrTemp  = fileUpload.FileName.Split('.');
            string   fileName = pathThumbnail + "/" + arrTemp[0] + ".jpg";

            ffMpeg.GetVideoThumbnail(pathVideo, fileName, 10.0f);
            return(arrTemp);
        }
        public static Bitmap GetVideoThumbnail(string video)
        {
            try
            {
                var    ffMpeg = new NReco.VideoConverter.FFMpegConverter();
                Stream output = new MemoryStream();
                ffMpeg.GetVideoThumbnail(video, output);

                return(LoadImageFromStream(output));
            } catch (Exception)
            { return(Properties.Resources.icons8_safe); }
        }
Example #19
0
 private static void CreateThumbnailForVideo(string filePath, string tempThumbnailPath, NReco.VideoConverter.FFMpegConverter ffMpeg)
 {
     try
     {
         ffMpeg.GetVideoThumbnail(filePath, tempThumbnailPath);
     }
     catch (Exception ex)
     {
         Console.Write(ex);
         Console.Write("Thumbnail already exists in TEMP Folder");
     }
 }
Example #20
0
        public static void CreateThumbnails(string homepath, string setName, string topicName)
        {
            //Get videos in topic folder
            homepath = Path.Combine(homepath, setName, topicName, "Videos");
            var extensions = new List <string> {
                ".mp4", ".avi"
            };
            var videos = Directory.GetFiles(homepath, "*.mp4", SearchOption.TopDirectoryOnly);


            //Thumb folder (save location)
            string topicfolder = Path.Combine(homepath, "Thumbnails");
            var    ffMpeg      = new NReco.VideoConverter.FFMpegConverter();


            //Generate original size thumbnails from existing videos and save them to /Thumbnails dir
            foreach (var video in videos)
            {
                if (!File.Exists(topicfolder + @"\" + Path.GetFileNameWithoutExtension(video) + ".jpg"))
                {
                    ffMpeg.GetVideoThumbnail(video, topicfolder + @"\D" + Path.GetFileNameWithoutExtension(video) + ".jpg", 5);
                }
            }


            //Generate small thumbnails
            List <string> oldImages = new List <string>();

            foreach (string image in Directory.GetFiles(topicfolder, "*.jpg"))
            {
                oldImages.Add(image);
                Bitmap newImage = new Bitmap(260, 130);
                using (Graphics gr = Graphics.FromImage(newImage))
                {
                    gr.SmoothingMode     = SmoothingMode.HighQuality;
                    gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    gr.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                    using (Image img = Image.FromFile(image))
                    {
                        gr.DrawImage(img, new Rectangle(0, 0, 260, 130));
                    }
                }
                var newfilename = Path.Combine(topicfolder, Path.GetFileNameWithoutExtension(image).Remove(0, 1) + ".jpg"); //Generate filename without .ext
                newImage.Save(@newfilename, ImageFormat.Jpeg);                                                              //Save small thumbnail
            }

            //Delete old images
            foreach (string image in oldImages)
            {
                File.Delete(image);
            }
        }
Example #21
0
 private void CreateAndSaveVideoThumbnail(string inputFile, string outputFile)
 {
     try
     {
         var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
         ffMpeg.GetVideoThumbnail(inputFile, outputFile, 5);
     }
     catch (Exception ex)
     {
         var dd = ex.Message;
         // CommonHelpers.Logger(ex.Message);
     }
 }
        public override System.Drawing.Image CreateHtml5VideoThumbnails(Telerik.Sitefinity.Libraries.Model.Video video, System.IO.FileInfo videoFile, string imageFilePath)
        {
            System.Drawing.Image thumbnail = null;
            var   ffMpeg    = new NReco.VideoConverter.FFMpegConverter();
            float?frameTime = 10;

            ffMpeg.GetVideoThumbnail(videoFile.FullName, imageFilePath, frameTime);
            using (FileStream imageStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
            {
                thumbnail = System.Drawing.Image.FromStream(imageStream);
            }
            return(thumbnail);
        }
        private Image LoadMediaCoverArtPosterWithCache(string fullFilePath) //, bool dontReadFilesInCloud, bool isFileInCloud)
        {
            Image image = PosterCacheRead(fullFilePath);

            if (image != null)
            {
                return(image);               //Found in cache
            }
            try
            {
                if (File.Exists(fullFilePath)) //Files can always be moved, deleted or become change outside application (Also may occure when this Rename files)
                {
                    if (ImageAndMovieFileExtentionsUtility.IsVideoFormat(fullFilePath))
                    {
                        var ffMpeg = new NReco.VideoConverter.FFMpegConverter();

                        using (Stream memoryStream = new MemoryStream())
                        {
                            ffMpeg.GetVideoThumbnail(fullFilePath, memoryStream);

                            if (memoryStream.Length > 0)
                            {
                                image = Image.FromStream(memoryStream);
                            }
                            else
                            {
                                image = null;
                            }
                        }
                    }
                    else if (ImageAndMovieFileExtentionsUtility.IsImageFormat(fullFilePath))
                    {
                        bool wasFileLocked = false;
                        image = ImageAndMovieFileExtentionsUtility.LoadImage(fullFilePath, out wasFileLocked);
                        if (image == null && wasFileLocked && File.Exists(fullFilePath))
                        {
                            image = ImageAndMovieFileExtentionsUtility.LoadImage(fullFilePath, out wasFileLocked);
                        }
                        //if (image == null) image = Utility.LoadImageWithoutLock(fullFilePath);
                    }
                }
            } catch (Exception ex)
            {
                Logger.Warn(ex, "LoadMediaCoverArtPoster was not able to create poster of the file " + fullFilePath);
            }
            if (image != null)
            {
                PosterCacheAdd(fullFilePath, image);
            }
            return(image);
        }
Example #24
0
        // creates a thumbnail image, then returns a thumbnail TagEntry for a chosen file containing that thumbnail's info
        public static TagEntry GenerateThumbnail(FileInfo file)
        {
            var    ffMpeg            = new NReco.VideoConverter.FFMpegConverter();
            string thumbnailLocation = _thumbnailDir + "/" + file.Name + "-" +
                                       string.Format("{0:yyyyMMddhhmmsstt}", DateTime.Now) + ".jpg";

            // if the thumbnail directory doesn't exist, create it
            if (!Directory.Exists(_thumbnailDir))
            {
                Directory.CreateDirectory(_thumbnailDir);
            }
            ffMpeg.GetVideoThumbnail(file.FullName, thumbnailLocation);
            return(new TagEntry(9,
                                thumbnailLocation));
        }
Example #25
0
        public Image VideoImage(float time)
        {
            time = time > length ? length : time;
            var ffMpeg      = new NReco.VideoConverter.FFMpegConverter();
            var imageStream = new MemoryStream();

            ffMpeg.GetVideoThumbnail(directory, imageStream, time);
            try
            {
                return(Image.FromStream(imageStream));
            }
            catch (ArgumentException)
            {
                return(VideoImage(time - 1));
            }
        }
Example #26
0
        public static bool CreateThumbnailFromVideo(string path, int width, string pathToSave)
        {
            var ffmpeg   = new NReco.VideoConverter.FFMpegConverter();
            var tempPath = Path.GetTempFileName();

            ffmpeg.GetVideoThumbnail(path, tempPath, 21);

            var image = new BitmapImage();

            image.BeginInit();
            image.UriSource        = new Uri(tempPath);
            image.DecodePixelWidth = width;
            image.EndInit();

            SaveBitmapImageToFile(image, pathToSave);
            return(true);
        }
        private MemoryStream GetVideoFrame(Stream videoStream, string filename)
        {
            var tempPathToFile = @"..\..\" + filename;

            using (FileStream output = new FileStream(tempPathToFile, FileMode.Create))
            {
                videoStream.CopyTo(output);
            }
            MemoryStream thumbnailStream = new MemoryStream();
            var          ffMpeg          = new NReco.VideoConverter.FFMpegConverter();

            ffMpeg.GetVideoThumbnail(tempPathToFile, thumbnailStream, 0);
            if (File.Exists(tempPathToFile))
            {
                File.Delete(tempPathToFile);
            }
            return(thumbnailStream);
        }
Example #28
0
        public bool MakeForVideo(string source, string target)
        {
            var    ffMpeg  = new NReco.VideoConverter.FFMpegConverter();
            string tmpFile = target + ".tmp";

            try
            {
                ffMpeg.GetVideoThumbnail(source, tmpFile);
                bool result = MakeForPhoto(tmpFile, target);
                File.Delete(tmpFile);
                return(result);
            }
            catch
            {
                // may be thrown for bad image or not supported format
                return(false);
            }
        }
Example #29
0
        public override void Render()
        {
            Bitmap thumb = null;
            int    size  = 52;

            try
            {
                Stream thumbJpegStream = new MemoryStream();
                var    ffMpeg          = new NReco.VideoConverter.FFMpegConverter();
                ffMpeg.GetVideoThumbnail(this.Filepath, thumbJpegStream, 1);
                thumb = new Bitmap(thumbJpegStream);
            }
            catch (ArgumentException)
            {
                thumb = new Bitmap(Properties.Resources.error);
            }

            MapHelper mh = MapHelper.Instance();

            mh.AddMarker("video", new Bitmap(thumb, size, size), this.Location, "Date: " + this.Datetimestamp.ToString() + "\nVideo", this);
        }
        private void ConvertAndListImages()
        {
            if (this._filesInfo != default && this._filesInfo.Any())
            {
                var fmmpeg = new NReco.VideoConverter.FFMpegConverter();
                var path   = "temporal";
                if (Directory.Exists(path))
                {
                    DeleteDirectory(path);
                }
                DirectoryInfo directoryInfo = default;
                foreach (var fileInfo in this._filesInfo)
                {
                    directoryInfo = Directory.CreateDirectory(String.Format("{0}/{1}", path, _directoryName));
                    fmmpeg.GetVideoThumbnail(fileInfo.FullName, String.Format("{0}/{1}.jpg", directoryInfo.FullName, fileInfo.Name.Replace(".mp4", String.Empty)), 2f);
                }

                var files = directoryInfo.GetFiles("*.jpg", SearchOption.AllDirectories);
                foreach (var image in files)
                {
                    try
                    {
                        this.imageList.Images.Add(Image.FromFile(image.FullName));
                    }
                    catch (Exception)
                    {
                    }
                }
                this.listView.View           = View.LargeIcon;
                this.imageList.ImageSize     = new Size(128, 128);
                this.listView.LargeImageList = this.imageList;

                for (int i = 0; i < this.imageList.Images.Count; i++)
                {
                    this.listView.Items.Add(new ListViewItem {
                        ImageIndex = i
                    });
                }
            }
        }
Example #31
0
        public ActionResult UploadFile(HttpPostedFileBase fileUpload)
        {
            try
            {
                if (!string.IsNullOrEmpty(folderUpload))
                {
                    if (fileUpload != null)
                    {
                        string name = "";
                        FileManagement.UploadFile(fileUpload, folderUpload, ref name);
                        string pathVideo = Server.MapPath(name);

                        // Get thumbnail video
                        string   pathThumbnail = Server.MapPath(ValueConstant.THUMBNAIL_VIDEO_FOLDER);
                        var      ffMpeg        = new NReco.VideoConverter.FFMpegConverter();
                        string[] arrTemp       = fileUpload.FileName.Split('.');
                        string   fileName      = pathThumbnail + arrTemp[0] + ".jpg";
                        ffMpeg.GetVideoThumbnail(pathVideo, fileName, 10.0f);

                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        TempData["Alert"] = ApplicationGenerator.RenderResult(ApplicationGenerator.TypeResult.FAIL, ApplicationGenerator.GeneralActionMessage(APIConstant.ACTION_INSERT, ApplicationGenerator.TypeResult.FAIL));
                        return(RedirectToAction("Index"));
                    }
                }
                else
                {
                    TempData["Alert"] = ApplicationGenerator.RenderResult(ApplicationGenerator.TypeResult.FAIL, "Vui lòng chọn thư mục cần tải hình lên");
                    return(RedirectToAction("Index"));
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                TempData["Alert"] = ApplicationGenerator.RenderResult(ApplicationGenerator.TypeResult.ERROR, ApplicationGenerator.GeneralActionMessage(APIConstant.ACTION_INSERT, ApplicationGenerator.TypeResult.ERROR));
                return(View());
            }
        }
Example #32
0
        public RedirectResult Thumbnail(int id)
        {
            string path      = HttpContext.Current.Server.MapPath("~");
            string pathVideo = path + @"videos\" + id + ".mp4";
            var    pathImage = path + @"images\" + id + ".jpg";



            var ffMpeg = new NReco.VideoConverter.FFMpegConverter();

            ffMpeg.GetVideoThumbnail(pathVideo, pathImage, 5);

            var bytes = Compression.ImageCompression(File.ReadAllBytes(pathImage), System.Drawing.Imaging.ImageFormat.Jpeg, 400);

            File.WriteAllBytes(pathImage, bytes);



            var host = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);;

            return(Redirect(host + "/images/" + id + ".jpg"));
        }
Example #33
0
        public static Video SaveVideo(Video video, string fileName, List <HttpPostedFileBase> backGroundImages)
        {
            var    tumbPath                 = GetThumbPath();
            var    videoPath                = GetVideoPath();
            string fileExtension            = Path.GetExtension(fileName);
            string fileNameWithoutExtention = Path.GetFileNameWithoutExtension(fileName);
            string currentVideoPath         = Path.Combine(videoPath, video.FileName);
            string tempPath                 = Path.Combine(GetTempPath(), video.ID.ToString() + "." + fileExtension);
            string newVideoPath             = Path.Combine(videoPath, fileName);
            string currentThumbPath         = Path.Combine(tumbPath, fileNameWithoutExtention + ImageExtention);
            string newThumbPath             = Path.Combine(tumbPath, fileNameWithoutExtention + ImageExtention);

            if (File.Exists(currentVideoPath))
            {
                File.Delete(currentVideoPath);
            }
            if (File.Exists(currentThumbPath))
            {
                File.Delete(currentThumbPath);
            }
            File.Copy(tempPath, newVideoPath, true);

            if (backGroundImages.Count > 0 && backGroundImages[0] != null)
            {
                var image = backGroundImages[0];
                image.SaveAs(newThumbPath);
            }
            else
            {
                var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
                ffMpeg.GetVideoThumbnail(newVideoPath, newThumbPath, 5);
            }
            File.Delete(tempPath);
            video.LastModifiedDate = DateTime.Now;
            video.FileName         = fileName;
            video.ThumbName        = fileNameWithoutExtention + ImageExtention;
            video.Size             = new FileInfo(newVideoPath).Length;
            return(video);
        }
Example #34
0
 /// <summary>
 /// Updates the size information for a given url from a given file. Needed to show media properly in the website.
 /// </summary>
 /// <param name="fileName">File which is used to get the size information.</param>
 private static void UpdateSizeInformation(string fileName, string url)
 {
     int width = 0;
       int height = 0;
       if (Path.GetExtension(fileName).Equals(".jpg") || Path.GetExtension(fileName).Equals(".png") || Path.GetExtension(fileName).Equals(".bmp"))
       {
     // Built-in system works for standard images.
     Image image = Image.FromFile(fileName);
     width = image.Width;
     height = image.Height;
     GenerateThumbs(fileName, url, Constants.ThumbWidth, Constants.ThumbHeight);
     GenerateThumbs(fileName, url, Constants.ThumbWidthSmall, Constants.ThumbHeightSmall);
       }
       if (Path.GetExtension(fileName).Equals(".gif"))
       {
     // Gif has to be checked manually.
     byte[] bytes = new byte[10];
     using (FileStream fs = File.OpenRead(fileName))
     {
       // Type (3 bytes), version (3 bytes), width (2 bytes), height (2 bytes).
       fs.Read(bytes, 0, 10);
     }
     // Byte 6 and 7 contain the width but in network byte order so byte 7 has to be left-shifted 8 places and bit-masked to byte 6.
     width = bytes[6] | bytes[7] << 8;
     height = bytes[8] | bytes[9] << 8;
     GenerateThumbs(fileName, url, Constants.ThumbWidth, Constants.ThumbHeight);
     GenerateThumbs(fileName, url, Constants.ThumbWidthSmall, Constants.ThumbHeightSmall);
       }
       if (Path.GetExtension(fileName).Equals(".webm"))
       {
     var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
     var jpgFileName = Directory.GetCurrentDirectory() + "\\" + Path.GetDirectoryName(fileName) + "\\" + Path.GetFileNameWithoutExtension(fileName) + ".jpg";
     ffMpeg.GetVideoThumbnail(Directory.GetCurrentDirectory() + "\\" + fileName, jpgFileName);
     Image image = Image.FromFile(jpgFileName);
     width = image.Width;
     height = image.Height;
     GenerateThumbs(jpgFileName, url, Constants.ThumbWidth, Constants.ThumbHeight);
     GenerateThumbs(jpgFileName, url, Constants.ThumbWidthSmall, Constants.ThumbHeightSmall);
       }
       if (Constants.MediaSizes.ContainsKey(url))
     Constants.MediaSizes[url] = new int[] { width, height };
       else
     Constants.MediaSizes.Add(url, new int[] { width, height });
 }
Example #35
0
        public JsonResult UploadVideo(FormCollection forms)
        {
            try
            {
                string ProductCode = forms.Get("ProductCode");
                var file = Request.Files["Filedata"];
                string savePath = Server.MapPath(@"~\Content\ProductVidoes\" + file.FileName);
                file.SaveAs(savePath);

                //  video = Server.MapPath(savePath);
                string _fileName = file.FileName.Substring(0, file.FileName.LastIndexOf('.')) + ".jpg";
                string thumb = Server.MapPath(@"~\Content\ProductVidoesImages\" + _fileName);
                var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
                ffMpeg.GetVideoThumbnail(savePath, thumb);

                ProductsVideosModel model = new ProductsVideosModel();
                model.VideoURL = file.FileName;
                model.ImageURL = _fileName;
                model.IsMainImage = false;
                model.ProductCode = ProductCode;
                model.Name = file.FileName.Substring(0, file.FileName.LastIndexOf('.'));
                unitOfWork.ProductsVideosRepository.Insert(model);
                unitOfWork.Save();
                model.VideoURL = Url.Content(@"~\Content\ProductVidoes\" + file.FileName);
                return Json(model, JsonRequestBehavior.AllowGet);

            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}",
                                                validationError.PropertyName,
                                                validationError.ErrorMessage);
                    }
                }
                return null;
            }
        }
Example #36
0
 //public void SaveBackgroundPicture(string videoPath, string backgroundPath)
 //{
 //    using (MemoryStream stream = new MemoryStream())
 //    {
 //        var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
 //        ffMpeg.GetVideoThumbnail(videoPath, stream, 0);
 //        if (stream.Length != 0)
 //        {
 //            Image img = Image.FromStream(stream);
 //            img.Save(backgroundPath);
 //        }
 //    }
 //}
 private FastBitmap GetBitmap(float time, MemoryStream stream, string file)
 {
     FastBitmap result = null;
     var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
     ffMpeg.GetVideoThumbnail(file, stream, time);
     if (stream.Length != 0)
     {
         Image img = Image.FromStream(stream);
         result = new FastBitmap(new Bitmap(img, img.Width / Scale, img.Height / Scale));
     }
     return result;
 }
Example #37
0
        public void UploadThumbnail(string tmp_path, string identifier)
        {
            var tmp_img_path = identifier + "-thumbnail";
            try
            {
                NReco.VideoConverter.FFMpegConverter converter = new NReco.VideoConverter.FFMpegConverter();
                converter.GetVideoThumbnail(tmp_path, tmp_img_path);
                using (var fs = new FileStream(tmp_img_path, FileMode.Open))
                {
                    var gridFsInfo = gridFS.Upload(fs, tmp_img_path);
                }
                File.Delete(tmp_img_path);

            }
            catch (MongoConnectionException e)
            {
                DriverException exception = new DriverException(e.Message, e);
                exception.ExplainProblem();
            }
        }
Example #38
0
 // creates a thumbnail image, then returns a thumbnail TagEntry for a chosen file containing that thumbnail's info
 public static TagEntry GenerateThumbnail(FileInfo file)
 {
     var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
     string thumbnailLocation = _thumbnailDir + "/" + file.Name + "-" +
                                string.Format("{0:yyyyMMddhhmmsstt}", DateTime.Now) + ".jpg";
     // if the thumbnail directory doesn't exist, create it
     if (!Directory.Exists(_thumbnailDir))
     {
         Directory.CreateDirectory(_thumbnailDir);
     }
     ffMpeg.GetVideoThumbnail(file.FullName,thumbnailLocation);
     return new TagEntry(9,
         thumbnailLocation);
 }
		public static Image Snapshot(string videoPath, float thumbTime)
		{
			try
			{
				var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
				var input = new System.IO.MemoryStream();
				ffMpeg.GetVideoThumbnail(videoPath, input, thumbTime);
				return Image.FromStream(input);
			}
			catch (Exception e)
			{
				Console.WriteLine(e.ToString());
				return null;
			}
		}