示例#1
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();
 }
示例#2
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 });
        }
示例#3
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);
        }
示例#4
0
        //media converter......
        private void button14_Click_1(object sender, EventArgs e)
        {
            hideSubMenu();

            //hides playlist panel.
            playlistPanel.Visible = false;
            MediaItems.Visible    = false;
            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    OpenDisplay(new Converting());
                    try
                    {
                        var convert = new NReco.VideoConverter.FFMpegConverter();
                        convert.ConvertMedia(ofd.FileName, @"C:\Users\Olanrewaju\Desktop\Converted.mp4", NReco.VideoConverter.Format.mp4);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error: " + ex);
                    }

                    MessageBox.Show("Convert complete");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex);
            }
        }
示例#5
0
        public string Convert()
        {
            string smessage = string.Empty;

            if (string.IsNullOrEmpty(FilePath) || string.IsNullOrEmpty(OutPutFilePath) || string.IsNullOrEmpty(FileFormat))
            {
                smessage = "Input path,Output path and file format are maindatory.";
            }
            else
            {
                try
                {
                    var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
                    switch (FileFormat)
                    {
                    case Format.webm:
                        ffMpeg.ConvertMedia(FilePath, OutPutFilePath, Format.webm);
                        break;

                    case Format.mp4:
                        ffMpeg.ConvertMedia(FilePath, OutPutFilePath, Format.mp4);
                        break;

                    case Format.mov:
                        ffMpeg.ConvertMedia(FilePath, OutPutFilePath, Format.mov);
                        break;
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Unable to convert. " + ex.Message);
                }
            }
            return(smessage);
        }
示例#6
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);
            }
        }
示例#7
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);
            }
        }
示例#8
0
        private void button2_Click(object sender, EventArgs e)
        {
            var videoConv = new NReco.VideoConverter.FFMpegConverter();

            videoConv.ConvertMedia(giris, cikis + ".mp3", "mp3");
            File.Delete(giris);
        }
        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
        }
示例#10
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);
        }
示例#11
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
            }
        }
示例#12
0
        //el async permite que sea un proceso asincrono, es decir que el proceso de conversión siga corriendo
        //independientemente de los demás procesos, y que no parezca que el programa se congeló
        private async void button1_ClickAsync(object sender, EventArgs e)
        {
            //nuevo cliente de Youtube
            var client = new YoutubeClient();
            //lee la dirección de youtube que le escribimos en el textbox
            var videoId = NormalizeVideoId(txtURL.Text);
            var video   = await client.GetVideoAsync(videoId);

            var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(videoId);

            // Busca la mejor resolución en la que está disponible el video
            var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality();

            // Compone el nombre que tendrá el video en base a su título y extensión
            var fileExtension = streamInfo.Container.GetFileExtension();
            var fileName      = $"{video.Title}.{fileExtension}";

            //TODO: Reemplazar los caractéres ilegales del nombre
            //fileName = RemoveIllegalFileNameChars(fileName);

            //Activa el timer para que el proceso funcione de forma asincrona
            tmrVideo.Enabled = true;

            // mensajes indicando que el video se está descargando
            txtMensaje.Text = "Descargando el video ... ";

            //TODO: se pude usar una barra de progreso para ver el avance
            //using (var progress = new ProgressBar())

            //Empieza la descarga
            await client.DownloadMediaStreamAsync(streamInfo, fileName);

            //Ya descargado se inicia la conversión a MP3
            var Convert = new NReco.VideoConverter.FFMpegConverter();
            //Especificar la carpeta donde se van a guardar los archivos, recordar la \ del final
            String SaveMP3File = @"E:\MP3\" + fileName.Replace(".mp4", ".mp3");

            //Guarda el archivo convertido en la ubicación indicada
            Convert.ConvertMedia(fileName, SaveMP3File, "mp3");

            //Si el checkbox de solo audio está chequeado, borrar el mp4 despues de la conversión
            if (ckbAudio.Checked)
            {
                File.Delete(fileName);
            }


            //Indicar que se terminó la conversion
            txtMensaje.Text      = "Archivo Convertido en MP3";
            tmrVideo.Enabled     = false;
            txtMensaje.BackColor = Color.White;

            //TODO: Cargar el MP3 al reproductor o a la lista de reproducción
            //CargarMP3s();
            //Se puede incluir un checkbox para indicar que de una vez se reproduzca el MP3
            //if (ckbAutoPlay.Checked)
            //  ReproducirMP3(SaveMP3File);
            return;
        }
示例#13
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());
                }
            }
        }
        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());
                }
            }
        }
示例#16
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 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));
            }
        }
示例#18
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");
        }
示例#19
0
        protected virtual string MakeVideoThumbnail(string filePath)
        {
            string outputFile = filePath + ".jpeg";

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

            ffMpeg.GetVideoThumbnail(filePath, outputFile);

            return(outputFile);
        }
示例#20
0
        public JsonResult UploadWebmVideoData()
        {
            foreach (string fl in Request.Files)
            {
                if (fl != null && Request.Files[fl].ContentLength > 0)
                {
                    string datestring = DateTime.Now.ToString("yyyyMMdd");
                    string imgdir     = Server.MapPath("~/userfiles") + "\\docs\\" + datestring + "\\";
                    if (!Directory.Exists(imgdir))
                    {
                        Directory.CreateDirectory(imgdir);
                    }

                    var fn       = "V" + "-" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".webm";
                    var onlyname = Path.GetFileNameWithoutExtension(fn);
                    var srcvfile = imgdir + fn;
                    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);

                    var mp4name = onlyname + ".mp4";
                    var mp4path = imgdir + mp4name;
                    var ffMpeg2 = new NReco.VideoConverter.FFMpegConverter();

                    var setting = new NReco.VideoConverter.ConvertSettings();
                    setting.VideoFrameRate  = 30;
                    setting.AudioSampleRate = 44100;

                    ffMpeg2.ConvertMedia(srcvfile, NReco.VideoConverter.Format.webm, mp4path, NReco.VideoConverter.Format.mp4, setting);

                    try { System.IO.File.Delete(srcvfile); } catch (Exception ex) { }

                    var url       = "/userfiles/docs/" + datestring + "/" + mp4name;
                    var videohtml = "<p><video width='640' height='480' controls src='" + url + "' type='video/mp4'>"
                                    + "Your browser does not support the video tag. </video></p>";

                    var ret1 = new JsonResult();
                    ret1.Data = new { data = videohtml };
                    return(ret1);
                }
            }
            var ret = new JsonResult();

            ret.Data = new { data = "<p></p>" };
            return(ret);
        }
示例#21
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);
        }
示例#23
0
        private AudioTrack(string videoFilePath)
        {
            var converter     = new NReco.VideoConverter.FFMpegConverter();
            var fileInfo      = new FileInfo(videoFilePath);
            var directory     = fileInfo.Directory.FullName;
            var fileName      = fileInfo.Name;
            var audioFilePath = Path.Combine(directory, fileName.Replace(".mp4", ".mp3"));

            converter.ConvertMedia(videoFilePath, audioFilePath, "mp3");

            this.AudioFilePath = audioFilePath;
        }
        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); }
        }
示例#25
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);
            }
        }
示例#26
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);
        }
示例#28
0
 private void buttonConvert_Click(object sender, EventArgs e)
 {
     if ((pathAudio.Text == string.Empty && pathVideo.Text == string.Empty) || pathAudio.Text == string.Empty || pathVideo.Text == string.Empty)
     {
         MessageBox.Show("You have to select both options!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
     else
     {
         var convert = new NReco.VideoConverter.FFMpegConverter();
         convert.ConvertMedia(pathVideo.Text.Trim(), pathAudio.Text.Trim(), "mp3");
         MessageBox.Show("Done.", "Convert", MessageBoxButtons.OK);
     }
 }
        private static void ConvertVideoFromQueue(string inputPath)
        {
            ProgramIsBusy = true;
            ProcessQueue.Dequeue();
            //Pick up file paths of files that are created in WatchingPath directory then pass them into converter.
            var fileConverter = new NReco.VideoConverter.FFMpegConverter();
            //Parse inputPath and Create a directory in the OutputPath for the file.
            var filePath   = inputPath.Split('\\').Last();
            var outputPath = string.Format(@"{0}\{1}", ConfigurationSettings.AppSettings["OutputPath"], filePath);

            fileConverter.ConvertMedia(inputPath, outputPath, "mp4");
            ProgramIsBusy = false;
        }
示例#30
0
 private void buttonConvert_Click(object sender, EventArgs e)
 {
     if (!string.IsNullOrEmpty(inputVideo))
     {
         var convertVideo = new NReco.VideoConverter.FFMpegConverter();
         convertVideo.ConvertMedia(inputVideo, outputFile + ".mp3", "mp3");
         MessageBox.Show("converted!!");
     }
     else
     {
         MessageBox.Show("choose video");
     }
 }
        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);
        }
        public ActionResult Index()
        {
            string url     = "https://www.youtube.com/watch?v=kIQypcFvGNM";
            var    youTube = YouTube.Default;       // starting point for YouTube actions
            var    video   = youTube.GetVideo(url); // gets a Video object with info about the video

            System.IO.File.WriteAllBytes(@"C:\Downloads\" + video.FullName, video.GetBytes());
            var ffmpeg = new NReco.VideoConverter.FFMpegConverter();

            new NReco.V
            ffmpeg.ConvertMedia("your_clip.mp4", null, "result.gif", null, new ConvertSettings());

            return(View());
        }
        public string RetrieveUploadVideo()
        {
            var ret = "";

            try
            {
                foreach (string fl in Request.Files)
                {
                    if (fl != null && Request.Files[fl].ContentLength > 0)
                    {
                        string fn = Path.GetFileName(Request.Files[fl].FileName)
                                    .Replace(" ", "_").Replace("#", "")
                                    .Replace("&", "").Replace("?", "").Replace("%", "").Replace("+", "");

                        var ext      = Path.GetExtension(fn).ToLower();
                        var allvtype = ".mp4,.mp3,.h264,.wmv,.wav,.avi,.flv,.mov,.mkv,.webm,.ogg,.mov,.mpg";

                        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 srvfd = Path.GetFileNameWithoutExtension(fn) + "-" + DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetExtension(fn);
                            Request.Files[fl].SaveAs(imgdir + srvfd);

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

                                try { System.IO.File.Delete(imgdir + srvfd); } catch (Exception ex) { }
                                return("/userfiles/docs/" + datestring + "/" + mp4name);
                            }

                            return("/userfiles/docs/" + datestring + "/" + srvfd);
                        } //end if
                    }     //end if
                }
            }
            catch (Exception ex) { }
            return(ret);
        }
示例#34
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;
            }
        }
示例#35
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();
            }
        }
示例#36
0
		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;
			}
		}
示例#37
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;
 }
示例#38
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 });
 }
示例#39
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);
 }