Esempio n. 1
0
        private void UploadImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.InitialDirectory = "c:\\";
            openFileDialog.Filter           = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png";
            openFileDialog.FilterIndex      = 2;
            openFileDialog.RestoreDirectory = true;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((openFileDialog.FileName != null))
                    {
                        CoverAlbum.Image    = ImageMethods.ConvertFileToImage(openFileDialog.FileName);
                        CoverAlbum.SizeMode = PictureBoxSizeMode.StretchImage;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }
Esempio n. 2
0
        private async Task <int> loadPatientDetails(string pid)
        {
            try
            {
                string    q = "SELECT * FROM Patient WHERE PID = @pid";
                Statement s = await this.database.PrepareStatementAsync(q);

                s.BindTextParameterWithName("@pid", pid);
                s.EnableColumnsProperty();
                if (await s.StepAsync())
                {
                    VisitPatientName.Text    = s.Columns["FirstName"] + " " + s.Columns["LastName"];
                    VisitPatientPhoto.Source = await ImageMethods.Base64StringToBitmap(s.Columns["Image"]);
                }

                return(DBConnect.RESULT_OK);
            }
            catch (Exception ex)
            {
                var result = SQLiteWinRT.Database.GetSqliteErrorCode(ex.HResult);
                Debug.WriteLine("CREATE_NEW_VISIT---LOAD_PATIENT_DETAILS" + "\n" + ex.Message + "\n" + result.ToString());

                return(DBConnect.RESULT_ERROR);
            }
        }
Esempio n. 3
0
        ///////////////////This are the methods used to update the display immideately after updating
        private async Task <bool> UpdateDiseaseData(BasicDiseases tempDisease)
        {
            docKitName.Text        = tempDisease.Name;
            docKitDescription.Text = "\n" + tempDisease.Description;
            docKitImage.Source     = await ImageMethods.Base64StringToBitmap(tempDisease.Image);

            docKitSymptomsPanel.Children.Clear();
            foreach (var i in tempDisease.Symptoms.Split(','))
            {
                if (i.Equals(""))
                {
                    continue;
                }

                StackPanel docKitSymptomsStackPanels = new StackPanel();
                docKitSymptomsStackPanels.Margin      = new Thickness(0, 15, 0, 0);
                docKitSymptomsStackPanels.Orientation = Orientation.Horizontal;

                TextBlock dot = new TextBlock();
                dot.Width    = 15;
                dot.FontSize = 20;
                dot.Text     = "•";
                docKitSymptomsStackPanels.Children.Add(dot);

                TextBlock Symptom = new TextBlock();
                Symptom.Width        = 650;
                Symptom.Text         = ExtraModules.RemoveStringSpace(i).Replace(",", "");
                Symptom.TextWrapping = TextWrapping.Wrap;
                Symptom.FontSize     = 20;
                docKitSymptomsStackPanels.Children.Add(Symptom);

                docKitSymptomsPanel.Children.Add(docKitSymptomsStackPanels);
            }
            return(true);
        }
Esempio n. 4
0
        private void button6_Click(object sender, EventArgs e)
        {
            var openFileDialog1 = new OpenFileDialog {
                Filter = @"Bmp(*.bmp)|*.bmp"
            };

            if (openFileDialog1.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            var fileName = openFileDialog1.FileName;

            try
            {
                var inputImage = new Image <Bgr, byte>(fileName);
                _picturesForm.Show();
                _picturesForm.GetInputPicture(inputImage);
                ImageMethods.AnalisePicture(inputImage);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }

            button6.Text = fileName;
        }
Esempio n. 5
0
 private void BigAlbumView_Load(object sender, EventArgs e)
 {
     //Slide
     if (slideIndex != -1)
     {
         if (slideIndex != 0)
         {
             SlideLeftButton.Visible = true; SlideLeftButton.FlatAppearance.BorderSize = 0;
         }
         if (slideIndex != slideALbums.Count - 1)
         {
             SlideRightButton.Visible = true; SlideRightButton.FlatAppearance.BorderSize = 0;
         }
         SlideInfo.Visible   = true;
         SlideInfo.Text      = $"({slideIndex + 1}/{slideALbums.Count})";
         CloseButton.Visible = false;
         PdfSave.Visible     = false;
         Edit.Visible        = false;
         Delete.Visible      = false;
     }
     //
     pictureBox1.Image    = ImageMethods.ConvertByteArrayToImage(currentAlbum.CoverPhoto);
     pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
     InitializeData();
     BigAlbumView_SizeChanged(sender, e);
 }
Esempio n. 6
0
 protected void btnFileUpload_Click(object sender, EventArgs e)
 {
     if (this.fileUpload.HasFile && ImageMethods.EhImagem(this.fileUpload.FileName))
     {
         ((Paciente)Session["usuario"]).AdicionarImagem(this.fileUpload);
         Response.Redirect("IndexPaciente.aspx");
     }
 }
Esempio n. 7
0
        private async Task <bool> UpdateFirstAidData(BasicFirstAid tempFirstAid)
        {
            docKitName.Text = tempFirstAid.Name;
            docKitFirstAidDescription.Text = "\n" + tempFirstAid.FirstAid;
            docKitFirstAidImage.Source     = await ImageMethods.Base64StringToBitmap(tempFirstAid.Image);

            docKitFirstAidSymptoms.Text = "\n" + tempFirstAid.DoNot;
            return(true);
        }
Esempio n. 8
0
        private void SaveToDatabase()
        {
            MusicAlbumsGuideDB context = new MusicAlbumsGuideDB();
            Album newAlbum             = new Album();

            newAlbum.Name = NameTextBox.Text;
            Genre currentGenre = context.Genres.Where(p => p.Name == GenreComboBox.Text).Single();

            newAlbum.GenreId     = currentGenre.GenreId;
            newAlbum.ReleaseYear = Convert.ToInt32(ReleaseYearTextBox.Text);
            Carrier currentCarrier = context.Carriers.Where(p => p.Name == CarrierComboBox.Text).Single();

            newAlbum.CarrierId = currentCarrier.CarrierId;
            //
            Database.Models.Type currentType = context.Types.Where(p => p.Name == TypeComboBox.Text).Single();
            newAlbum.TypeId = currentType.TypeId;
            Author author;

            try
            {
                author = context.Authors.Where(p => p.Name == AuthorTextBox.Text).Single();
            }
            catch (Exception)
            {
                context.Authors.Add(new Author()
                {
                    Name = AuthorTextBox.Text
                });
                context.SaveChanges();
                author = context.Authors.Where(p => p.Name == AuthorTextBox.Text).Single();
            }
            newAlbum.AuthorId   = author.AuthorId;
            newAlbum.TrackCount = Convert.ToInt32(TrackCountTextBox.Text);
            //
            ReleasingLabel releasingLabel;

            try
            {
                releasingLabel = context.ReleasingLabels.Where(p => p.Name == ReleaseLabelTextBox.Text).Single();
            }
            catch (Exception)
            {
                context.ReleasingLabels.Add(new ReleasingLabel()
                {
                    Name = ReleaseLabelTextBox.Text
                });
                context.SaveChanges();
                releasingLabel = context.ReleasingLabels.Where(p => p.Name == ReleaseLabelTextBox.Text).Single();
            }
            newAlbum.ReleasingLabelId = releasingLabel.ReleasingLabelId;
            newAlbum.CoverPhoto       = ImageMethods.ConvertImageToByteArray(CoverAlbum.Image);
            context.Albums.Add(newAlbum);
            context.SaveChanges();
        }
Esempio n. 9
0
        private void EnterDataFromAlbum(int AlbumId)
        {
            MusicAlbumsGuideDB context = new MusicAlbumsGuideDB();
            Album current = context.Albums.Include(p => p.Author).Include(p => p.Carrier).Include(p => p.Genre).Include(p => p.Type).Include(p => p.ReleasingLabel).Where(p => p.AlbumId == AlbumId).Single();

            CoverAlbum.Image         = ImageMethods.ConvertByteArrayToImage(current.CoverPhoto);
            CoverAlbum.SizeMode      = PictureBoxSizeMode.StretchImage;
            NameTextBox.Text         = current.Name;
            GenreComboBox.Text       = current.Genre.Name;
            ReleaseYearTextBox.Text  = current.ReleaseYear.ToString();
            CarrierComboBox.Text     = current.Carrier.Name;
            TypeComboBox.Text        = current.Type.Name;
            AuthorTextBox.Text       = current.Author.Name;
            TrackCountTextBox.Text   = current.TrackCount.ToString();
            ReleaseLabelTextBox.Text = current.ReleasingLabel.Name;
        }
Esempio n. 10
0
        private async void docKitDialogBrowse(object sender, RoutedEventArgs e)
        {
            //This is used to Open the FilePicker Browse Menu from which we can select file
            var picker = new Windows.Storage.Pickers.FileOpenPicker();

            picker.FileTypeFilter.Add(".jpg");
            var file = await picker.PickSingleFileAsync();

            decodedImage = await ImageMethods.ConvertStorageFileToBase64String(file);

            if (isDiseaseSelected)
            {
                docKitDImage.Text = file.Name;
            }
            else
            {
                docKitFAImage.Text = file.Name;
            }
        }
        public override void RunCommand(object sender)
        {
            var    engine      = (AutomationEngineInstance)sender;
            string vFolderPath = v_FolderPath.ConvertUserVariableToString(engine);
            string vFileName   = v_FileName.ConvertUserVariableToString(engine);
            string vFilePath   = Path.Combine(vFolderPath, vFileName);

            Bitmap image;

            if (v_ScreenshotWindowName == "Current Window")
            {
                image = ImageMethods.Screenshot();
            }
            else
            {
                image = User32Functions.CaptureWindow(v_ScreenshotWindowName);
            }

            image.Save(vFilePath);
        }
Esempio n. 12
0
        private void frmImageCapture_Load(object sender, EventArgs e)
        {
            if (pbTaggedImage.Image != null)
            {
                pnlMouseContainer.Hide();
                return;
            }
            else
            {
                tabTestMode.Hide();
            }

            FormBorderStyle = FormBorderStyle.None;
            Location        = new Point(0, 0);
            WindowState     = FormWindowState.Maximized;

            //Hide the Form
            Hide();

            Thread.Sleep(1000);

            //Copy Image from the screen
            Bitmap printscreen = ImageMethods.Screenshot();

            //Create a temporal memory stream for the image
            using (MemoryStream s = new MemoryStream())
            {
                //save graphic variable into memory
                printscreen.Save(s, ImageFormat.Bmp);

                pbMainImage.Size = new Size(Width, Height);

                //set the picture box with temporary stream
                pbMainImage.Image = Image.FromStream(s);
            }
            //Show Form
            Show();

            //Cross Cursor
            Cursor = Cursors.Cross;
        }
Esempio n. 13
0
 public void SetInitVariables(Form1 parent, Album album)
 {
     parentForm   = parent;
     currentAlbum = album;
     //
     pictureBox1.Image = ImageMethods.ConvertByteArrayToImage(currentAlbum.CoverPhoto);
     if (currentAlbum.Name.Length <= 20)
     {
         AlbumName.Text = currentAlbum.Name;
     }
     else
     {
         string name = default(string);
         for (int i = 0; i < 21; i++)
         {
             name += currentAlbum.Name[i];
         }
         AlbumName.Text = name;
     }
     ReleaseYear.Text = currentAlbum.ReleaseYear.ToString() + " г.";
     Author.Text      = currentAlbum.Author.Name;
 }
Esempio n. 14
0
        /// <summary>
        /// Draw the Chart.
        /// </summary>
        public virtual void GenerateChart()
        {
            var xAxis = _xAxis1;
            var yAxis = _yAxis;

            CalculateInitialLayout();

            xAxis.FinaliseAxisLayout(xAxis.AxisCoords, yAxis.AxisCoords);
            yAxis.FinaliseAxisLayout(xAxis.AxisCoords, yAxis.AxisCoords);
            CalculateDataPointLabelDimensions();

            if ((ChartLegend.LegendEntries.Count == 0) && (ChartLegend.IsLegendVisible))
            {
                AutoGenerateLegendEntries();
            }
            CalculateLegendDimensions();

            SizeF chartDimension = GetChartDimensions();

            Bitmap bmp = new Bitmap((int)chartDimension.Width, (int)chartDimension.Height);

            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.Clear(ImageBackgroundColor);
                g.SmoothingMode = SmoothingMode.AntiAlias;

                DrawBorder(g);

                DrawTitles(g);

                xAxis.DrawAxis(g, bmp, xAxis.AxisPosition, xAxis.GetDimensions().Width, yAxis.GetDimensions().Height);
                yAxis.DrawAxis(g, bmp, xAxis.AxisPosition, xAxis.GetDimensions().Width, yAxis.GetDimensions().Height);

                /*Pen rectPen = new Pen(Brushes.Red, 1);
                 * rectPen.DashPattern = new float[] { 10, 10 };
                 * ImageMethods.Debug_DrawRectangle(g, new Rectangle(xAxis.AxisCoords, xAxis.GetDimensions()), rectPen);
                 * ImageMethods.Debug_DrawRectangle(g, new Rectangle(yAxis.AxisCoords, yAxis.GetDimensions()), rectPen);*/

                PlotData(g);

                if (ChartLegend.IsLegendVisible)
                {
                    Bitmap legendBMP = DrawLegend();

                    int xOffset = bmp.Width;
                    xOffset -= GetMargin(ElementPosition.RIGHT) + GetPadding(ElementPosition.RIGHT);
                    if (BorderPen != null)
                    {
                        xOffset -= (int)BorderPen.Width;
                    }
                    xOffset -= legendBMP.Width;

                    int yOffset = GetMargin(ElementPosition.TOP) + GetPadding(ElementPosition.TOP);
                    if (BorderPen != null)
                    {
                        yOffset += (int)BorderPen.Width;
                    }

                    ImageMethods.CopyRegionIntoImage(legendBMP, new Rectangle(0, 0, legendBMP.Width, legendBMP.Height),
                                                     ref bmp, new Rectangle(xOffset,
                                                                            yOffset, legendBMP.Width, legendBMP.Height));
                }
            }

            bmp.Save(OutputFile, ImageFormat.Png);
        }
Esempio n. 15
0
        private async void Encode(List <FrameInfo> listFrames, int id, Parameters param, CancellationTokenSource tokenSource)
        {
            var processing = this.DispatcherStringResource("Encoder.Processing");

            try
            {
                switch (param.Type)
                {
                case Export.Gif:

                    #region Gif

                    #region Cut/Paint Unchanged Pixels

                    if (param.EncoderType == GifEncoderType.Legacy || param.EncoderType == GifEncoderType.ScreenToGif)
                    {
                        if (param.DetectUnchangedPixels)
                        {
                            Update(id, 0, FindResource("Encoder.Analyzing").ToString());

                            if (param.DummyColor.HasValue)
                            {
                                var color = Color.FromArgb(param.DummyColor.Value.R, param.DummyColor.Value.G, param.DummyColor.Value.B);

                                listFrames = ImageMethods.PaintTransparentAndCut(listFrames, color, id, tokenSource);
                            }
                            else
                            {
                                listFrames = ImageMethods.CutUnchanged(listFrames, id, tokenSource);
                            }
                        }
                        else
                        {
                            var size = listFrames[0].Path.ScaledSize();
                            listFrames.ForEach(x => x.Rect = new Int32Rect(0, 0, (int)size.Width, (int)size.Height));
                        }
                    }

                    #endregion

                    switch (param.EncoderType)
                    {
                    case GifEncoderType.ScreenToGif:

                        #region Improved encoding

                        using (var stream = new MemoryStream())
                        {
                            using (var encoder = new GifFile(stream, param.RepeatCount))
                            {
                                encoder.UseGlobalColorTable = param.UseGlobalColorTable;
                                encoder.TransparentColor    = param.DummyColor;
                                encoder.MaximumNumberColor  = param.MaximumNumberColors;

                                for (var i = 0; i < listFrames.Count; i++)
                                {
                                    if (!listFrames[i].HasArea && param.DetectUnchangedPixels)
                                    {
                                        continue;
                                    }

                                    if (listFrames[i].Delay == 0)
                                    {
                                        listFrames[i].Delay = 10;
                                    }

                                    encoder.AddFrame(listFrames[i].Path, listFrames[i].Rect, listFrames[i].Delay);

                                    Update(id, i, string.Format(processing, i));

                                    #region Cancellation

                                    if (tokenSource.Token.IsCancellationRequested)
                                    {
                                        SetStatus(Status.Canceled, id);
                                        break;
                                    }

                                    #endregion
                                }
                            }

                            try
                            {
                                using (var fileStream = new FileStream(param.Filename, FileMode.Create, FileAccess.Write, FileShare.None, 4096))
                                    stream.WriteTo(fileStream);
                            }
                            catch (Exception ex)
                            {
                                SetStatus(Status.Error, id);
                                LogWriter.Log(ex, "Improved Encoding");
                            }
                        }

                        #endregion

                        break;

                    case GifEncoderType.Legacy:

                        #region Legacy Encoding

                        using (var encoder = new AnimatedGifEncoder())
                        {
                            if (param.DummyColor.HasValue)
                            {
                                var color = Color.FromArgb(param.DummyColor.Value.R,
                                                           param.DummyColor.Value.G, param.DummyColor.Value.B);

                                encoder.SetTransparent(color);
                                encoder.SetDispose(1);         //Undraw Method, "Leave".
                            }

                            encoder.Start(param.Filename);
                            encoder.SetQuality(param.Quality);
                            encoder.SetRepeat(param.RepeatCount);

                            var numImage = 0;
                            foreach (var frame in listFrames)
                            {
                                #region Cancellation

                                if (tokenSource.Token.IsCancellationRequested)
                                {
                                    SetStatus(Status.Canceled, id);
                                    break;
                                }

                                #endregion

                                if (!frame.HasArea && param.DetectUnchangedPixels)
                                {
                                    continue;
                                }

                                var bitmapAux = new Bitmap(frame.Path);

                                encoder.SetDelay(frame.Delay);
                                encoder.AddFrame(bitmapAux, frame.Rect.X, frame.Rect.Y);

                                bitmapAux.Dispose();

                                Update(id, numImage, string.Format(processing, numImage));
                                numImage++;
                            }
                        }

                        #endregion

                        break;

                    case GifEncoderType.PaintNet:

                        #region paint.NET encoding

                        using (var stream = new MemoryStream())
                        {
                            using (var encoder = new GifEncoder(stream, null, null, param.RepeatCount))
                            {
                                for (var i = 0; i < listFrames.Count; i++)
                                {
                                    var bitmapAux = new Bitmap(listFrames[i].Path);
                                    encoder.AddFrame(bitmapAux, 0, 0, TimeSpan.FromMilliseconds(listFrames[i].Delay));
                                    bitmapAux.Dispose();

                                    Update(id, i, string.Format(processing, i));

                                    #region Cancellation

                                    if (tokenSource.Token.IsCancellationRequested)
                                    {
                                        SetStatus(Status.Canceled, id);

                                        break;
                                    }

                                    #endregion
                                }
                            }

                            stream.Position = 0;

                            try
                            {
                                using (var fileStream = new FileStream(param.Filename, FileMode.Create, FileAccess.Write, FileShare.None, Constants.BufferSize, false))
                                    stream.WriteTo(fileStream);
                            }
                            catch (Exception ex)
                            {
                                SetStatus(Status.Error, id);
                                LogWriter.Log(ex, "Encoding with paint.Net.");
                            }
                        }

                        #endregion

                        break;

                    case GifEncoderType.FFmpeg:

                        #region FFmpeg encoding

                        SetStatus(Status.Processing, id, null, true);

                        if (!Util.Other.IsFfmpegPresent())
                        {
                            throw new ApplicationException("FFmpeg not present.");
                        }

                        if (File.Exists(param.Filename))
                        {
                            File.Delete(param.Filename);
                        }

                        #region Generate concat

                        var concat = new StringBuilder();
                        foreach (var frame in listFrames)
                        {
                            concat.AppendLine("file '" + frame.Path + "'");
                            concat.AppendLine("duration " + (frame.Delay / 1000d).ToString(CultureInfo.InvariantCulture));
                        }

                        var concatPath = Path.GetDirectoryName(listFrames[0].Path) ?? Path.GetTempPath();
                        var concatFile = Path.Combine(concatPath, "concat.txt");

                        if (!Directory.Exists(concatPath))
                        {
                            Directory.CreateDirectory(concatPath);
                        }

                        if (File.Exists(concatFile))
                        {
                            File.Delete(concatFile);
                        }

                        File.WriteAllText(concatFile, concat.ToString());

                        #endregion

                        param.Command = string.Format(param.Command, concatFile, param.ExtraParameters.Replace("{H}", param.Height.ToString()).Replace("{W}", param.Width.ToString()), param.Filename);

                        var process = new ProcessStartInfo(UserSettings.All.FfmpegLocation)
                        {
                            Arguments             = param.Command,
                            CreateNoWindow        = true,
                            ErrorDialog           = false,
                            UseShellExecute       = false,
                            RedirectStandardError = true
                        };

                        var pro = Process.Start(process);

                        var str = pro.StandardError.ReadToEnd();

                        var fileInfo = new FileInfo(param.Filename);

                        if (!fileInfo.Exists || fileInfo.Length == 0)
                        {
                            throw new Exception("Error while encoding the gif with FFmpeg.")
                                  {
                                      HelpLink = $"Command:\n\r{param.Command}\n\rResult:\n\r{str}"
                                  }
                        }
                        ;

                        #endregion

                        break;

                    case GifEncoderType.Gifski:

                        #region Gifski encoding

                        SetStatus(Status.Processing, id, null, true);

                        if (!Util.Other.IsGifskiPresent())
                        {
                            throw new ApplicationException("Gifski not present.");
                        }

                        if (File.Exists(param.Filename))
                        {
                            File.Delete(param.Filename);
                        }

                        var gifski = new GifskiInterop();
                        var handle = gifski.Start(UserSettings.All.GifskiQuality, UserSettings.All.Looped);

                        ThreadPool.QueueUserWorkItem(delegate
                        {
                            Thread.Sleep(500);
                            SetStatus(Status.Processing, id, null, false);

                            for (var i = 0; i < listFrames.Count; i++)
                            {
                                Update(id, i, string.Format(processing, i));
                                gifski.AddFrame(handle, (uint)i, listFrames[i].Path, listFrames[i].Delay);
                            }

                            gifski.EndAdding(handle);
                        }, null);

                        gifski.End(handle, param.Filename);

                        var fileInfo2 = new FileInfo(param.Filename);

                        if (!fileInfo2.Exists || fileInfo2.Length == 0)
                        {
                            throw new Exception("Error while encoding the gif with Gifski.", new Win32Exception())
                                  {
                                      HelpLink = $"Command:\n\r{param.Command}\n\rResult:\n\r{Marshal.GetLastWin32Error()}"
                                  }
                        }
                        ;

                        #endregion

                        break;

                    default:
                        throw new Exception("Undefined Gif encoder type");
                    }

                    #endregion

                    break;

                case Export.Apng:

                    #region Apng

                    #region Cut/Paint Unchanged Pixels

                    if (param.DetectUnchangedPixels)
                    {
                        Update(id, 0, FindResource("Encoder.Analyzing").ToString());

                        if (param.DummyColor.HasValue)
                        {
                            var color = Color.FromArgb(param.DummyColor.Value.A, param.DummyColor.Value.R, param.DummyColor.Value.G, param.DummyColor.Value.B);
                            listFrames = ImageMethods.PaintTransparentAndCut(listFrames, color, id, tokenSource);
                        }
                        else
                        {
                            listFrames = ImageMethods.CutUnchanged(listFrames, id, tokenSource);
                        }
                    }
                    else
                    {
                        var size = listFrames[0].Path.ScaledSize();
                        listFrames.ForEach(x => x.Rect = new Int32Rect(0, 0, (int)size.Width, (int)size.Height));
                    }

                    #endregion

                    #region Encoding

                    using (var stream = new MemoryStream())
                    {
                        var frameCount = listFrames.Count(x => x.HasArea);

                        using (var encoder = new Apng(stream, frameCount, param.RepeatCount))
                        {
                            for (var i = 0; i < listFrames.Count; i++)
                            {
                                if (!listFrames[i].HasArea && param.DetectUnchangedPixels)
                                {
                                    continue;
                                }

                                if (listFrames[i].Delay == 0)
                                {
                                    listFrames[i].Delay = 10;
                                }

                                encoder.AddFrame(listFrames[i].Path, listFrames[i].Rect, listFrames[i].Delay);

                                Update(id, i, string.Format(processing, i));

                                #region Cancellation

                                if (tokenSource.Token.IsCancellationRequested)
                                {
                                    SetStatus(Status.Canceled, id);
                                    break;
                                }

                                #endregion
                            }
                        }

                        try
                        {
                            using (var fileStream = new FileStream(param.Filename, FileMode.Create, FileAccess.Write, FileShare.None, 4096))
                                stream.WriteTo(fileStream);
                        }
                        catch (Exception ex)
                        {
                            SetStatus(Status.Error, id);
                            LogWriter.Log(ex, "Apng Encoding");
                        }
                    }

                    #endregion

                    #endregion

                    break;

                case Export.Video:

                    #region Video

                    switch (param.VideoEncoder)
                    {
                    case VideoEncoderType.AviStandalone:

                        #region Avi Standalone

                        var image = listFrames[0].Path.SourceFrom();

                        if (File.Exists(param.Filename))
                        {
                            File.Delete(param.Filename);
                        }

                        //1000 / listFrames[0].Delay
                        using (var aviWriter = new AviWriter(param.Filename, param.Framerate, image.PixelWidth, image.PixelHeight, param.VideoQuality))
                        {
                            var numImage = 0;
                            foreach (var frame in listFrames)
                            {
                                using (var outStream = new MemoryStream())
                                {
                                    var bitImage = frame.Path.SourceFrom();

                                    var enc = new BmpBitmapEncoder();
                                    enc.Frames.Add(BitmapFrame.Create(bitImage));
                                    enc.Save(outStream);

                                    outStream.Flush();

                                    using (var bitmap = new Bitmap(outStream))
                                        aviWriter.AddFrame(bitmap, param.FlipVideo);
                                }

                                Update(id, numImage, string.Format(processing, numImage));
                                numImage++;

                                #region Cancellation

                                if (tokenSource.Token.IsCancellationRequested)
                                {
                                    SetStatus(Status.Canceled, id);
                                    break;
                                }

                                #endregion
                            }
                        }

                        #endregion

                        break;

                    case VideoEncoderType.Ffmpg:

                        #region Video using FFmpeg

                        SetStatus(Status.Processing, id, null, true);

                        if (!Util.Other.IsFfmpegPresent())
                        {
                            throw new ApplicationException("FFmpeg not present.");
                        }

                        if (File.Exists(param.Filename))
                        {
                            File.Delete(param.Filename);
                        }

                        #region Generate concat

                        var concat = new StringBuilder();
                        foreach (var frame in listFrames)
                        {
                            concat.AppendLine("file '" + frame.Path + "'");
                            concat.AppendLine("duration " + (frame.Delay / 1000d).ToString(CultureInfo.InvariantCulture));
                        }

                        var concatPath = Path.GetDirectoryName(listFrames[0].Path) ?? Path.GetTempPath();
                        var concatFile = Path.Combine(concatPath, "concat.txt");

                        if (!Directory.Exists(concatPath))
                        {
                            Directory.CreateDirectory(concatPath);
                        }

                        if (File.Exists(concatFile))
                        {
                            File.Delete(concatFile);
                        }

                        File.WriteAllText(concatFile, concat.ToString());

                        #endregion

                        param.Command = string.Format(param.Command, concatFile, param.ExtraParameters.Replace("{H}", param.Height.ToString()).Replace("{W}", param.Width.ToString()), param.Filename);

                        var process = new ProcessStartInfo(UserSettings.All.FfmpegLocation)
                        {
                            Arguments             = param.Command,
                            CreateNoWindow        = true,
                            ErrorDialog           = false,
                            UseShellExecute       = false,
                            RedirectStandardError = true
                        };

                        var pro = Process.Start(process);

                        var str = pro.StandardError.ReadToEnd();

                        var fileInfo = new FileInfo(param.Filename);

                        if (!fileInfo.Exists || fileInfo.Length == 0)
                        {
                            throw new Exception("Error while encoding with FFmpeg.")
                                  {
                                      HelpLink = str
                                  }
                        }
                        ;

                        #endregion

                        break;

                    default:
                        throw new Exception("Undefined video encoder");
                    }

                    #endregion

                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(param));
                }

                //If it was canceled, try deleting the file.
                if (tokenSource.Token.IsCancellationRequested)
                {
                    if (File.Exists(param.Filename))
                    {
                        File.Delete(param.Filename);
                    }

                    SetStatus(Status.Canceled, id);
                    return;
                }

                #region Upload

                if (param.Upload && File.Exists(param.Filename))
                {
                    InternalUpdate(id, "Encoder.Uploading", true, true);

                    try
                    {
                        ICloud cloud = CloudFactory.CreateCloud(param.UploadDestinationIndex);

                        var uploadedFile = await cloud.UploadFileAsync(param.Filename, CancellationToken.None);

                        InternalSetUpload(id, true, uploadedFile.Link, uploadedFile.DeleteLink);
                    }
                    catch (Exception e)
                    {
                        LogWriter.Log(e, "It was not possible to run the post encoding command.");
                        InternalSetUpload(id, false, null, null, e);
                    }
                }

                #endregion

                #region Copy to clipboard

                if (param.CopyToClipboard && File.Exists(param.Filename))
                {
                    Dispatcher.Invoke(() =>
                    {
                        try
                        {
                            var data = new DataObject();

                            switch (param.CopyType)
                            {
                            case CopyType.File:
                                if (param.Type != Export.Video)
                                {
                                    data.SetImage(param.Filename.SourceFrom());
                                }

                                data.SetText(param.Filename, TextDataFormat.Text);
                                data.SetFileDropList(new StringCollection {
                                    param.Filename
                                });
                                break;

                            case CopyType.FolderPath:
                                data.SetText(Path.GetDirectoryName(param.Filename) ?? param.Filename, TextDataFormat.Text);
                                break;

                            case CopyType.Link:
                                var link = InternalGetUpload(id);

                                data.SetText(string.IsNullOrEmpty(link) ? param.Filename : link, TextDataFormat.Text);
                                break;

                            default:
                                data.SetText(param.Filename, TextDataFormat.Text);
                                break;
                            }

                            //It tries to set the data to the clipboard 10 times before failing it to do so.
                            //This issue may happen if the clipboard is opened by any clipboard manager.
                            for (var i = 0; i < 10; i++)
                            {
                                try
                                {
                                    Clipboard.SetDataObject(data, true);
                                    break;
                                }
                                catch (COMException ex)
                                {
                                    if ((uint)ex.ErrorCode != 0x800401D0) //CLIPBRD_E_CANT_OPEN
                                    {
                                        throw;
                                    }
                                }

                                Thread.Sleep(100);
                            }

                            InternalSetCopy(id, true);
                        }
                        catch (Exception e)
                        {
                            LogWriter.Log(e, "It was not possible to copy the file.");
                            InternalSetCopy(id, false, e);
                        }
                    });
                }

                #endregion

                #region Execute commands

                if (param.ExecuteCommands && !string.IsNullOrWhiteSpace(param.PostCommands))
                {
                    InternalUpdate(id, "Encoder.Executing", true, true);

                    var command = param.PostCommands.Replace("{p}", "\"" + param.Filename + "\"").Replace("{f}", "\"" + Path.GetDirectoryName(param.Filename) + "\"");
                    var output  = "";

                    try
                    {
                        foreach (var com in command.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            var procStartInfo = new ProcessStartInfo("cmd", "/c " + com)
                            {
                                RedirectStandardOutput = true,
                                RedirectStandardError  = true,
                                UseShellExecute        = false,
                                CreateNoWindow         = true
                            };

                            using (var process = new Process())
                            {
                                process.StartInfo = procStartInfo;
                                process.Start();

                                var message = process.StandardOutput.ReadToEnd();
                                var error   = process.StandardError.ReadToEnd();

                                if (!string.IsNullOrWhiteSpace(message))
                                {
                                    output += message + Environment.NewLine;
                                }

                                if (!string.IsNullOrWhiteSpace(message))
                                {
                                    output += message + Environment.NewLine;
                                }

                                if (!string.IsNullOrWhiteSpace(error))
                                {
                                    throw new Exception(error);
                                }

                                process.WaitForExit(1000);
                            }
                        }

                        InternalSetCommand(id, true, command, output);
                    }
                    catch (Exception e)
                    {
                        LogWriter.Log(e, "It was not possible to run the post encoding command.");
                        InternalSetCommand(id, false, command, output, e);
                    }
                }

                #endregion

                if (!tokenSource.Token.IsCancellationRequested)
                {
                    SetStatus(Status.Completed, id, param.Filename);
                }
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Encode");

                SetStatus(Status.Error, id, null, false, ex);
            }
            finally
            {
                #region Delete Encoder Folder

                try
                {
                    var encoderFolder = Path.GetDirectoryName(listFrames[0].Path);

                    if (!string.IsNullOrEmpty(encoderFolder))
                    {
                        if (Directory.Exists(encoderFolder))
                        {
                            Directory.Delete(encoderFolder, true);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogWriter.Log(ex, "Cleaning the Encode folder");
                }

                #endregion

                GC.Collect();
            }
        }
Esempio n. 16
0
        private void Encode(List <FrameInfo> listFrames, int id, Parameters param, CancellationTokenSource tokenSource)
        {
            var processing = FindResource("Encoder.Processing").ToString();

            try
            {
                switch (param.Type)
                {
                case Export.Gif:

                    #region Gif

                    var gifParam = (GifParameters)param;

                    #region Cut/Paint Unchanged Pixels

                    if (gifParam.DetectUnchangedPixels && (gifParam.EncoderType == GifEncoderType.Legacy || gifParam.EncoderType == GifEncoderType.ScreenToGif))
                    {
                        Update(id, 0, FindResource("Encoder.Analyzing").ToString());

                        if (gifParam.DummyColor.HasValue)
                        {
                            var color = Color.FromArgb(gifParam.DummyColor.Value.R, gifParam.DummyColor.Value.G, gifParam.DummyColor.Value.B);

                            listFrames = ImageMethods.PaintTransparentAndCut(listFrames, color, id, tokenSource);
                        }
                        else
                        {
                            listFrames = ImageMethods.CutUnchanged(listFrames, id, tokenSource);
                        }
                    }

                    #endregion

                    switch (gifParam.EncoderType)
                    {
                    case GifEncoderType.ScreenToGif:

                        #region Improved encoding

                        using (var stream = new MemoryStream())
                        {
                            using (var encoder = new GifFile(stream, gifParam.RepeatCount))
                            {
                                encoder.UseGlobalColorTable = gifParam.UseGlobalColorTable;
                                encoder.TransparentColor    = gifParam.DummyColor;
                                encoder.MaximumNumberColor  = gifParam.MaximumNumberColors;

                                for (var i = 0; i < listFrames.Count; i++)
                                {
                                    if (!listFrames[i].HasArea)
                                    {
                                        continue;
                                    }

                                    if (listFrames[i].Delay == 0)
                                    {
                                        listFrames[i].Delay = 10;
                                    }

                                    encoder.AddFrame(listFrames[i].ImageLocation, listFrames[i].Rect, listFrames[i].Delay);

                                    Update(id, i, string.Format(processing, i));

                                    #region Cancellation

                                    if (tokenSource.Token.IsCancellationRequested)
                                    {
                                        SetStatus(Status.Canceled, id);

                                        break;
                                    }

                                    #endregion
                                }
                            }

                            try
                            {
                                using (var fileStream = new FileStream(gifParam.Filename, FileMode.Create, FileAccess.Write, FileShare.None, 4096))
                                {
                                    stream.WriteTo(fileStream);
                                }
                            }
                            catch (Exception ex)
                            {
                                SetStatus(Status.Error, id);
                                LogWriter.Log(ex, "Improved Encoding");
                            }
                        }

                        #endregion

                        break;

                    case GifEncoderType.Legacy:

                        #region Legacy Encoding

                        using (var encoder = new AnimatedGifEncoder())
                        {
                            if (gifParam.DummyColor.HasValue)
                            {
                                var color = Color.FromArgb(gifParam.DummyColor.Value.R,
                                                           gifParam.DummyColor.Value.G, gifParam.DummyColor.Value.B);

                                encoder.SetTransparent(color);
                                encoder.SetDispose(1);         //Undraw Method, "Leave".
                            }

                            encoder.Start(gifParam.Filename);
                            encoder.SetQuality(gifParam.Quality);
                            encoder.SetRepeat(gifParam.RepeatCount);

                            var numImage = 0;
                            foreach (var frame in listFrames)
                            {
                                #region Cancellation

                                if (tokenSource.Token.IsCancellationRequested)
                                {
                                    SetStatus(Status.Canceled, id);
                                    break;
                                }

                                #endregion

                                if (!frame.HasArea && gifParam.DetectUnchangedPixels)
                                {
                                    continue;
                                }

                                var bitmapAux = new Bitmap(frame.ImageLocation);

                                encoder.SetDelay(frame.Delay);
                                encoder.AddFrame(bitmapAux, frame.Rect.X, frame.Rect.Y);

                                bitmapAux.Dispose();

                                Update(id, numImage, string.Format(processing, numImage));
                                numImage++;
                            }
                        }

                        #endregion

                        break;

                    case GifEncoderType.PaintNet:

                        #region paint.NET encoding

                        using (var stream = new MemoryStream())
                        {
                            using (var encoder = new GifEncoder(stream, null, null, gifParam.RepeatCount))
                            {
                                for (var i = 0; i < listFrames.Count; i++)
                                {
                                    var bitmapAux = new Bitmap(listFrames[i].ImageLocation);
                                    encoder.AddFrame(bitmapAux, 0, 0, TimeSpan.FromMilliseconds(listFrames[i].Delay));
                                    bitmapAux.Dispose();

                                    Update(id, i, string.Format(processing, i));

                                    #region Cancellation

                                    if (tokenSource.Token.IsCancellationRequested)
                                    {
                                        SetStatus(Status.Canceled, id);

                                        break;
                                    }

                                    #endregion
                                }
                            }

                            stream.Position = 0;

                            try
                            {
                                using (var fileStream = new FileStream(gifParam.Filename, FileMode.Create, FileAccess.Write, FileShare.None, Constants.BufferSize, false))
                                {
                                    stream.WriteTo(fileStream);
                                }
                            }
                            catch (Exception ex)
                            {
                                SetStatus(Status.Error, id);
                                LogWriter.Log(ex, "Encoding with paint.Net.");
                            }
                        }

                        #endregion

                        break;

                    default:
                        throw new Exception("Undefined Gif encoder type");
                    }

                    #endregion

                    break;

                case Export.Video:

                    #region Video

                    var videoParam = (VideoParameters)param;

                    switch (videoParam.VideoEncoder)
                    {
                    case VideoEncoderType.AviStandalone:

                        #region Avi Standalone

                        var image = listFrames[0].ImageLocation.SourceFrom();

                        using (var aviWriter = new AviWriter(videoParam.Filename, 1000 / listFrames[0].Delay, image.PixelWidth, image.PixelHeight, videoParam.Quality))
                        {
                            var numImage = 0;
                            foreach (var frame in listFrames)
                            {
                                using (var outStream = new MemoryStream())
                                {
                                    var bitImage = frame.ImageLocation.SourceFrom();

                                    var enc = new BmpBitmapEncoder();
                                    enc.Frames.Add(BitmapFrame.Create(bitImage));
                                    enc.Save(outStream);

                                    outStream.Flush();

                                    using (var bitmap = new Bitmap(outStream))
                                    {
                                        aviWriter.AddFrame(bitmap);
                                    }
                                }

                                //aviWriter.AddFrame(new BitmapImage(new Uri(frame.ImageLocation)));

                                Update(id, numImage, string.Format(processing, numImage));
                                numImage++;

                                #region Cancellation

                                if (tokenSource.Token.IsCancellationRequested)
                                {
                                    SetStatus(Status.Canceled, id);
                                    break;
                                }

                                #endregion
                            }
                        }

                        #endregion

                        break;

                    case VideoEncoderType.Ffmpg:

                        #region Video using FFmpeg

                        SetStatus(Status.Encoding, id, null, true);

                        if (!Util.Other.IsFfmpegPresent())
                        {
                            throw new ApplicationException("FFmpeg not present.");
                        }

                        videoParam.Command = string.Format(videoParam.Command,
                                                           Path.Combine(Path.GetDirectoryName(listFrames[0].ImageLocation), "%d.png"),
                                                           videoParam.ExtraParameters, videoParam.Framerate,
                                                           param.Filename);

                        var process = new ProcessStartInfo(Settings.Default.FfmpegLocation)
                        {
                            Arguments             = videoParam.Command,
                            CreateNoWindow        = true,
                            ErrorDialog           = false,
                            UseShellExecute       = false,
                            RedirectStandardError = true
                        };

                        var pro = Process.Start(process);

                        var str = pro.StandardError.ReadToEnd();

                        var fileInfo = new FileInfo(param.Filename);

                        if (!fileInfo.Exists || fileInfo.Length == 0)
                        {
                            throw new Exception("Error while encoding with FFmpeg.", new Exception(str));
                        }

                        #endregion

                        break;

                    default:
                        throw new Exception("Undefined video encoder");
                    }

                    #endregion

                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(param));
                }

                if (!tokenSource.Token.IsCancellationRequested)
                {
                    SetStatus(Status.Completed, id, param.Filename);
                }
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Encode");

                SetStatus(Status.Error, id, null, false, ex.Message);
            }
            finally
            {
                #region Delete Encoder Folder

                try
                {
                    var encoderFolder = Path.GetDirectoryName(listFrames[0].ImageLocation);

                    if (!string.IsNullOrEmpty(encoderFolder))
                    {
                        if (Directory.Exists(encoderFolder))
                        {
                            Directory.Delete(encoderFolder, true);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogWriter.Log(ex, "Cleaning the Encode folder");
                }

                #endregion

                GC.Collect();
            }
        }
Esempio n. 17
0
        private void Encode(List <FrameInfo> listFrames, int id, Parameters param, CancellationTokenSource tokenSource)
        {
            var processing = FindResource("Encoder.Processing").ToString();

            try
            {
                switch (param.Type)
                {
                case Export.Gif:

                    #region Gif

                    #region Cut/Paint Unchanged Pixels

                    if (param.EncoderType == GifEncoderType.Legacy || param.EncoderType == GifEncoderType.ScreenToGif)
                    {
                        if (param.DetectUnchangedPixels)
                        {
                            Update(id, 0, FindResource("Encoder.Analyzing").ToString());

                            if (param.DummyColor.HasValue)
                            {
                                var color = Color.FromArgb(param.DummyColor.Value.R, param.DummyColor.Value.G, param.DummyColor.Value.B);

                                listFrames = ImageMethods.PaintTransparentAndCut(listFrames, color, id, tokenSource);
                            }
                            else
                            {
                                listFrames = ImageMethods.CutUnchanged(listFrames, id, tokenSource);
                            }
                        }
                        else
                        {
                            var size = listFrames[0].Path.ScaledSize();
                            listFrames.ForEach(x => x.Rect = new Int32Rect(0, 0, (int)size.Width, (int)size.Height));
                        }
                    }

                    #endregion

                    switch (param.EncoderType)
                    {
                    case GifEncoderType.ScreenToGif:

                        #region Improved encoding

                        using (var stream = new MemoryStream())
                        {
                            using (var encoder = new GifFile(stream, param.RepeatCount))
                            {
                                encoder.UseGlobalColorTable = param.UseGlobalColorTable;
                                encoder.TransparentColor    = param.DummyColor;
                                encoder.MaximumNumberColor  = param.MaximumNumberColors;

                                for (var i = 0; i < listFrames.Count; i++)
                                {
                                    if (!listFrames[i].HasArea && param.DetectUnchangedPixels)
                                    {
                                        continue;
                                    }

                                    if (listFrames[i].Delay == 0)
                                    {
                                        listFrames[i].Delay = 10;
                                    }

                                    encoder.AddFrame(listFrames[i].Path, listFrames[i].Rect, listFrames[i].Delay);

                                    Update(id, i, string.Format(processing, i));

                                    #region Cancellation

                                    if (tokenSource.Token.IsCancellationRequested)
                                    {
                                        SetStatus(Status.Canceled, id);
                                        break;
                                    }

                                    #endregion
                                }
                            }

                            try
                            {
                                using (var fileStream = new FileStream(param.Filename, FileMode.Create, FileAccess.Write, FileShare.None, 4096))
                                    stream.WriteTo(fileStream);
                            }
                            catch (Exception ex)
                            {
                                SetStatus(Status.Error, id);
                                LogWriter.Log(ex, "Improved Encoding");
                            }
                        }

                        #endregion

                        break;

                    case GifEncoderType.Legacy:

                        #region Legacy Encoding

                        using (var encoder = new AnimatedGifEncoder())
                        {
                            if (param.DummyColor.HasValue)
                            {
                                var color = Color.FromArgb(param.DummyColor.Value.R,
                                                           param.DummyColor.Value.G, param.DummyColor.Value.B);

                                encoder.SetTransparent(color);
                                encoder.SetDispose(1);         //Undraw Method, "Leave".
                            }

                            encoder.Start(param.Filename);
                            encoder.SetQuality(param.Quality);
                            encoder.SetRepeat(param.RepeatCount);

                            var numImage = 0;
                            foreach (var frame in listFrames)
                            {
                                #region Cancellation

                                if (tokenSource.Token.IsCancellationRequested)
                                {
                                    SetStatus(Status.Canceled, id);
                                    break;
                                }

                                #endregion

                                if (!frame.HasArea && param.DetectUnchangedPixels)
                                {
                                    continue;
                                }

                                var bitmapAux = new Bitmap(frame.Path);

                                encoder.SetDelay(frame.Delay);
                                encoder.AddFrame(bitmapAux, frame.Rect.X, frame.Rect.Y);

                                bitmapAux.Dispose();

                                Update(id, numImage, string.Format(processing, numImage));
                                numImage++;
                            }
                        }

                        #endregion

                        break;

                    case GifEncoderType.PaintNet:

                        #region paint.NET encoding

                        using (var stream = new MemoryStream())
                        {
                            using (var encoder = new GifEncoder(stream, null, null, param.RepeatCount))
                            {
                                for (var i = 0; i < listFrames.Count; i++)
                                {
                                    var bitmapAux = new Bitmap(listFrames[i].Path);
                                    encoder.AddFrame(bitmapAux, 0, 0, TimeSpan.FromMilliseconds(listFrames[i].Delay));
                                    bitmapAux.Dispose();

                                    Update(id, i, string.Format(processing, i));

                                    #region Cancellation

                                    if (tokenSource.Token.IsCancellationRequested)
                                    {
                                        SetStatus(Status.Canceled, id);

                                        break;
                                    }

                                    #endregion
                                }
                            }

                            stream.Position = 0;

                            try
                            {
                                using (var fileStream = new FileStream(param.Filename, FileMode.Create, FileAccess.Write, FileShare.None, Constants.BufferSize, false))
                                    stream.WriteTo(fileStream);
                            }
                            catch (Exception ex)
                            {
                                SetStatus(Status.Error, id);
                                LogWriter.Log(ex, "Encoding with paint.Net.");
                            }
                        }

                        #endregion

                        break;

                    default:
                        throw new Exception("Undefined Gif encoder type");
                    }

                    #endregion

                    break;

                case Export.Apng:

                    #region Apng

                    #region Cut/Paint Unchanged Pixels

                    if (param.DetectUnchangedPixels)
                    {
                        Update(id, 0, FindResource("Encoder.Analyzing").ToString());

                        if (param.DummyColor.HasValue)
                        {
                            var color = Color.FromArgb(param.DummyColor.Value.A, param.DummyColor.Value.R, param.DummyColor.Value.G, param.DummyColor.Value.B);
                            listFrames = ImageMethods.PaintTransparentAndCut(listFrames, color, id, tokenSource);
                        }
                        else
                        {
                            listFrames = ImageMethods.CutUnchanged(listFrames, id, tokenSource);
                        }
                    }
                    else
                    {
                        var size = listFrames[0].Path.ScaledSize();
                        listFrames.ForEach(x => x.Rect = new Int32Rect(0, 0, (int)size.Width, (int)size.Height));
                    }

                    #endregion

                    #region Encoding

                    using (var stream = new MemoryStream())
                    {
                        var frameCount = listFrames.Count(x => x.HasArea);

                        using (var encoder = new Apng(stream, frameCount, param.RepeatCount))
                        {
                            for (var i = 0; i < listFrames.Count; i++)
                            {
                                if (!listFrames[i].HasArea && param.DetectUnchangedPixels)
                                {
                                    continue;
                                }

                                if (listFrames[i].Delay == 0)
                                {
                                    listFrames[i].Delay = 10;
                                }

                                encoder.AddFrame(listFrames[i].Path, listFrames[i].Rect, listFrames[i].Delay);

                                Update(id, i, string.Format(processing, i));

                                #region Cancellation

                                if (tokenSource.Token.IsCancellationRequested)
                                {
                                    SetStatus(Status.Canceled, id);
                                    break;
                                }

                                #endregion
                            }
                        }

                        try
                        {
                            using (var fileStream = new FileStream(param.Filename, FileMode.Create, FileAccess.Write, FileShare.None, 4096))
                                stream.WriteTo(fileStream);
                        }
                        catch (Exception ex)
                        {
                            SetStatus(Status.Error, id);
                            LogWriter.Log(ex, "Apng Encoding");
                        }
                    }

                    #endregion

                    #endregion

                    break;

                case Export.Video:

                    #region Video

                    switch (param.VideoEncoder)
                    {
                    case VideoEncoderType.AviStandalone:

                        #region Avi Standalone

                        var image = listFrames[0].Path.SourceFrom();

                        if (File.Exists(param.Filename))
                        {
                            File.Delete(param.Filename);
                        }

                        //1000 / listFrames[0].Delay
                        using (var aviWriter = new AviWriter(param.Filename, param.Framerate, image.PixelWidth, image.PixelHeight, param.VideoQuality))
                        {
                            var numImage = 0;
                            foreach (var frame in listFrames)
                            {
                                using (var outStream = new MemoryStream())
                                {
                                    var bitImage = frame.Path.SourceFrom();

                                    var enc = new BmpBitmapEncoder();
                                    enc.Frames.Add(BitmapFrame.Create(bitImage));
                                    enc.Save(outStream);

                                    outStream.Flush();

                                    using (var bitmap = new Bitmap(outStream))
                                        aviWriter.AddFrame(bitmap, param.FlipVideo);
                                }

                                Update(id, numImage, string.Format(processing, numImage));
                                numImage++;

                                #region Cancellation

                                if (tokenSource.Token.IsCancellationRequested)
                                {
                                    SetStatus(Status.Canceled, id);
                                    break;
                                }

                                #endregion
                            }
                        }

                        #endregion

                        break;

                    case VideoEncoderType.Ffmpg:

                        #region Video using FFmpeg

                        SetStatus(Status.Encoding, id, null, true);

                        if (!Util.Other.IsFfmpegPresent())
                        {
                            throw new ApplicationException("FFmpeg not present.");
                        }

                        if (File.Exists(param.Filename))
                        {
                            File.Delete(param.Filename);
                        }

                        #region Generate concat

                        var concat = new StringBuilder();
                        foreach (var frame in listFrames)
                        {
                            concat.AppendLine("file '" + frame.Path + "'");
                            concat.AppendLine("duration " + (frame.Delay / 1000d).ToString(CultureInfo.InvariantCulture));
                        }

                        var concatPath = Path.GetDirectoryName(listFrames[0].Path) ?? Path.GetTempPath();
                        var concatFile = Path.Combine(concatPath, "concat.txt");

                        if (!Directory.Exists(concatPath))
                        {
                            Directory.CreateDirectory(concatPath);
                        }

                        if (File.Exists(concatFile))
                        {
                            File.Delete(concatFile);
                        }

                        File.WriteAllText(concatFile, concat.ToString());

                        #endregion

                        param.Command = string.Format(param.Command, concatFile, param.ExtraParameters.Replace("{H}", param.Height.ToString()).Replace("{W}", param.Width.ToString()), param.Filename);

                        var process = new ProcessStartInfo(UserSettings.All.FfmpegLocation)
                        {
                            Arguments             = param.Command,
                            CreateNoWindow        = true,
                            ErrorDialog           = false,
                            UseShellExecute       = false,
                            RedirectStandardError = true
                        };

                        var pro = Process.Start(process);

                        var str = pro.StandardError.ReadToEnd();

                        var fileInfo = new FileInfo(param.Filename);

                        if (!fileInfo.Exists || fileInfo.Length == 0)
                        {
                            throw new Exception("Error while encoding with FFmpeg.")
                                  {
                                      HelpLink = str
                                  }
                        }
                        ;

                        #endregion

                        break;

                    default:
                        throw new Exception("Undefined video encoder");
                    }

                    #endregion

                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(param));
                }

                if (!tokenSource.Token.IsCancellationRequested)
                {
                    SetStatus(Status.Completed, id, param.Filename);
                }

                #region Upload

                if (param.Upload && File.Exists(param.Filename))
                {
                    /*
                     * using (var w = new WebClient())
                     * {
                     *  var clientID = "15 digit key";
                     *  w.Headers.Add("Authorization", "Client-ID " + clientID);
                     *  var values = new NameValueCollection { { "image", Convert.ToBase64String(File.ReadAllBytes(@""+filename)) }};
                     *  var response = w.UploadValues("https://api.imgur.com/3/upload.xml", values);
                     *  var x = XDocument.Load(new MemoryStream(response));
                     *  var link = x.Descendants().Where(n => n.Name == "link").FirstOrDefault();
                     *  string href = link.Value;
                     * }
                     */
                }

                #endregion

                #region Copy to clipboard

                if (param.CopyToClipboard && File.Exists(param.Filename))
                {
                    Dispatcher.Invoke(() =>
                    {
                        try
                        {
                            var data = new DataObject();

                            switch (param.CopyType)
                            {
                            case CopyType.File:
                                if (param.Type != Export.Video)
                                {
                                    data.SetImage(param.Filename.SourceFrom());
                                }

                                data.SetText(param.Filename, TextDataFormat.Text);
                                data.SetFileDropList(new StringCollection {
                                    param.Filename
                                });
                                break;

                            case CopyType.FolderPath:
                                data.SetText(Path.GetDirectoryName(param.Filename) ?? param.Filename, TextDataFormat.Text);
                                break;

                            case CopyType.Link:
                                data.SetText(param.Filename, TextDataFormat.Text);     //TODO: Link.
                                break;

                            default:
                                data.SetText(param.Filename, TextDataFormat.Text);
                                break;
                            }

                            Clipboard.SetDataObject(data, true);
                            InternalSetCopy(id, true);
                        }
                        catch (Exception e)
                        {
                            LogWriter.Log(e, "It was not possible to copy the file.");
                            InternalSetCopy(id, false, e);
                        }
                    });
                }

                #endregion

                #region Execute commands

                if (param.ExecuteCommands && !string.IsNullOrWhiteSpace(param.PostCommands))
                {
                    var command = param.PostCommands.Replace("{p}", "\"" + param.Filename + "\"").Replace("{f}", "\"" + Path.GetDirectoryName(param.Filename) + "\"");
                    var output  = "";

                    try
                    {
                        foreach (var com in command.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            var procStartInfo = new ProcessStartInfo("cmd", "/c " + com)
                            {
                                RedirectStandardOutput = true,
                                RedirectStandardError  = true,
                                UseShellExecute        = false,
                                CreateNoWindow         = true
                            };

                            using (var process = new Process())
                            {
                                process.StartInfo = procStartInfo;
                                process.Start();

                                var message = process.StandardOutput.ReadToEnd();
                                var error   = process.StandardError.ReadToEnd();

                                if (!string.IsNullOrWhiteSpace(message))
                                {
                                    output += message + Environment.NewLine;
                                }

                                if (!string.IsNullOrWhiteSpace(message))
                                {
                                    output += message + Environment.NewLine;
                                }

                                if (!string.IsNullOrWhiteSpace(error))
                                {
                                    throw new Exception(error);
                                }

                                process.WaitForExit(1000);
                            }
                        }

                        InternalSetCommand(id, true, output);
                    }
                    catch (Exception e)
                    {
                        LogWriter.Log(e, "It was not possible to run the post encoding command.");
                        InternalSetCommand(id, false, output, e);
                    }
                }

                #endregion
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Encode");

                SetStatus(Status.Error, id, null, false, ex);
            }
            finally
            {
                #region Delete Encoder Folder

                try
                {
                    var encoderFolder = Path.GetDirectoryName(listFrames[0].Path);

                    if (!string.IsNullOrEmpty(encoderFolder))
                    {
                        if (Directory.Exists(encoderFolder))
                        {
                            Directory.Delete(encoderFolder, true);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogWriter.Log(ex, "Cleaning the Encode folder");
                }

                #endregion

                GC.Collect();
            }
        }
Esempio n. 18
0
        private async void LoadDetails()
        {
            try
            {
                string    query     = "SELECT * FROM Patient WHERE PID = @pid";
                Statement statement = await this.database.PrepareStatementAsync(query);

                statement.BindTextParameterWithName("@pid", this.PID);
                statement.EnableColumnsProperty();

                if (await statement.StepAsync())
                {
                    ProfileName.Text    = statement.Columns["LastName"] + " " + statement.Columns["FirstName"];
                    ProfileImage.Source = await ImageMethods.Base64StringToBitmap(statement.Columns["Image"]);

                    ProfileDateOfBirth.Text = statement.Columns["Birthday"];
                    ProfileAge.Text         = (DateTime.Now.Year - Convert.ToInt32(statement.Columns["Birthday"].Substring(0, statement.Columns["Birthday"].IndexOf("-")))).ToString();
                    ProfileBloodGroup.Text  = statement.Columns["BloodGroup"];
                    ProfileSex.Text         = statement.Columns["Sex"];
                }
            }
            catch (Exception ex)
            {
                var result = SQLiteWinRT.Database.GetSqliteErrorCode(ex.HResult);
                Debug.WriteLine("PROFILE_DETAILS_PAGE---LOAD_DETAILS---PATIENT" + "\n" + ex.Message + "\n" + result.ToString());
            }

            string street = "", city = "", state = "", country = "", zip = "";

            try
            {
                string    query     = "SELECT * FROM Address WHERE PID = @pid";
                Statement statement = await this.database.PrepareStatementAsync(query);

                statement.BindTextParameterWithName("@pid", this.PID);
                statement.EnableColumnsProperty();
                if (await statement.StepAsync())
                {
                    street = statement.Columns["Street"];
                    zip    = statement.Columns["ZIP"];
                }
            }
            catch (Exception ex)
            {
                var result = SQLiteWinRT.Database.GetSqliteErrorCode(ex.HResult);
                Debug.WriteLine("PROFILE_DETAILS_PAGE---LOAD_DETAILS---ADDRESS" + "\n" + ex.Message + "\n" + result.ToString());
            }

            try
            {
                string    query     = "SELECT * FROM AddressZIP WHERE ZIP = @zip";
                Statement statement = await this.database.PrepareStatementAsync(query);

                statement.BindIntParameterWithName("@zip", Int32.Parse(zip));
                statement.EnableColumnsProperty();
                if (await statement.StepAsync())
                {
                    city = statement.Columns["City"];
                }
            }
            catch (Exception ex)
            {
                var result = SQLiteWinRT.Database.GetSqliteErrorCode(ex.HResult);
                Debug.WriteLine("PROFILE_DETAILS_PAGE---LOAD_DETAILS---ADDRESS_ZIP" + "\n" + ex.Message + "\n" + result.ToString());
            }

            try
            {
                string    query     = "SELECT * FROM AddressCity WHERE City = @city";
                Statement statement = await this.database.PrepareStatementAsync(query);

                statement.BindTextParameterWithName("@city", city);
                statement.EnableColumnsProperty();
                if (await statement.StepAsync())
                {
                    state = statement.Columns["State"];
                }
            }
            catch (Exception ex)
            {
                var result = SQLiteWinRT.Database.GetSqliteErrorCode(ex.HResult);
                Debug.WriteLine("PROFILE_DETAILS_PAGE---LOAD_DETAILS---ADDRESS_CITY" + "\n" + ex.Message + "\n" + result.ToString());
            }

            try
            {
                string    query     = "SELECT * FROM AddressState WHERE State = @state";
                Statement statement = await this.database.PrepareStatementAsync(query);

                statement.BindTextParameterWithName("@state", state);
                statement.EnableColumnsProperty();
                if (await statement.StepAsync())
                {
                    country = statement.Columns["Country"];
                }
                ProfileAddress.Text = street + "\n" + city + ", " + state + ", " + zip + "\n" + country;
            }
            catch (Exception ex)
            {
                var result = SQLiteWinRT.Database.GetSqliteErrorCode(ex.HResult);
                Debug.WriteLine("PROFILE_DETAILS_PAGE---LOAD_DETAILS---ADDRESS_STATE" + "\n" + ex.Message + "\n" + result.ToString());
            }

            try
            {
                string    queryDetails = "SELECT * FROM MutableDetails WHERE PID = @pid";
                Statement statement    = await this.database.PrepareStatementAsync(queryDetails);

                statement.BindTextParameterWithName("@pid", this.PID);
                statement.EnableColumnsProperty();

                if (await statement.StepAsync())
                {
                    ProfileContact.Text = statement.Columns["Mobile"];

                    if (statement.Columns["EmMobile"].ToString() != "0")
                    {
                        ProfileEmContact.Text = statement.Columns["EmMobile"];
                    }
                    else
                    {
                        ProfileEmContact.Text = "NA";
                    }

                    ProfileEmail.Text         = statement.Columns["Email"];
                    ProfileOccupation.Text    = statement.Columns["Occupation"];
                    ProfileFamilyHistory.Text = statement.Columns["FamilyBackground"];

                    if (statement.Columns["Married"].Equals("T"))
                    {
                        ProfileMaritalStatus.Text = "Married";
                    }
                    else
                    {
                        ProfileMaritalStatus.Text = "Unmarried";
                    }
                }
            }
            catch (Exception ex)
            {
                var result = SQLiteWinRT.Database.GetSqliteErrorCode(ex.HResult);
                Debug.WriteLine("PROFILE_DETAILS_PAGE---LOAD_DETAILS---MUTABLE_DETAILS" + "\n" + ex.Message + "\n" + result.ToString());
            }

            try
            {
                ProfileAllergies.Text = "";
                string    allergyDetails = "SELECT * FROM MutableDetailsAllergy WHERE PID = @pid";
                Statement statement      = await this.database.PrepareStatementAsync(allergyDetails);

                statement.BindTextParameterWithName("@pid", this.PID);
                statement.EnableColumnsProperty();
                while (await statement.StepAsync())
                {
                    ProfileAllergies.Text += statement.Columns["Allergy"] + ",";
                }
                if (!ProfileAllergies.Text.Equals(""))
                {
                    ProfileAllergies.Text = ProfileAllergies.Text.Substring(0, ProfileAllergies.Text.Length - 1).TrimStart().TrimEnd();
                }
                else
                {
                    ProfileAllergies.Text = "NA";
                }
            }
            catch (Exception ex)
            {
                var result = SQLiteWinRT.Database.GetSqliteErrorCode(ex.HResult);
                Debug.WriteLine("PROFILE_DETAILS_PAGE---LOAD_DETAILS---MUTABLE_DETAILS_ALLERGY" + "\n" + ex.Message + "\n" + result.ToString());
            }

            try
            {
                ProfileOperations.Text = "";
                string    operationDetails = "SELECT * FROM MutableDetailsOperation WHERE PID = @pid";
                Statement statement        = await this.database.PrepareStatementAsync(operationDetails);

                statement.BindTextParameterWithName("@pid", this.PID);
                statement.EnableColumnsProperty();

                while (await statement.StepAsync())
                {
                    ProfileOperations.Text += statement.Columns["Operation"] + ",";
                }
                if (!ProfileOperations.Text.Equals(""))
                {
                    ProfileOperations.Text = ProfileOperations.Text.Substring(0, ProfileOperations.Text.Length - 1).TrimStart().TrimEnd();
                }
                else
                {
                    ProfileOperations.Text = "NA";
                }
            }
            catch (Exception ex)
            {
                var result = SQLiteWinRT.Database.GetSqliteErrorCode(ex.HResult);
                Debug.WriteLine("PROFILE_DETAILS_PAGE---LOAD_DETAILS---MUTABLE_DETAILS_OPERATION" + "\n" + ex.Message + "\n" + result.ToString());
            }

            try
            {
                ProfileAddictions.Text = "";
                string    addictionDetails = "SELECT * FROM MutableDetailsAddiction WHERE PID = @pid";
                Statement statement        = await this.database.PrepareStatementAsync(addictionDetails);

                statement.BindTextParameterWithName("@pid", this.PID);
                statement.EnableColumnsProperty();

                while (await statement.StepAsync())
                {
                    ProfileAddictions.Text += statement.Columns["Addiction"] + ",";
                }
                if (!ProfileAddictions.Text.Equals(""))
                {
                    ProfileAddictions.Text = ProfileAddictions.Text.Substring(0, ProfileAddictions.Text.Length - 1).TrimEnd().TrimStart();
                }
                else
                {
                    ProfileAddictions.Text = "NA";
                }
            }
            catch (Exception ex)
            {
                var result = SQLiteWinRT.Database.GetSqliteErrorCode(ex.HResult);
                Debug.WriteLine("PROFILE_DETAILS_PAGE---LOAD_DETAILS---MUTABLE_DETAILS_ADDICTION" + "\n" + ex.Message + "\n" + result.ToString());
            }

            try
            {
                string    query     = "SELECT * FROM MedicalDetails WHERE PID = @pid";
                Statement statement = await database.PrepareStatementAsync(query);

                statement.BindTextParameterWithName("@pid", this.PID);
                statement.EnableColumnsProperty();
                double height = -1;
                double bmi    = -1;
                Int32  weight = -1;
                Int32  bg     = -1;
                Int32  sbp    = -1;
                Int32  dbp    = -1;
                while (await statement.StepAsync())
                {
                    height = Double.Parse(statement.Columns["Height"]);
                    weight = Int32.Parse(statement.Columns["Weight"]);
                    bmi    = Convert.ToDouble(statement.Columns["BMI"]);
                    bmi    = Math.Round(bmi, 3);
                    bg     = Int32.Parse(statement.Columns["BloodGlucose"]);
                    sbp    = Int32.Parse(statement.Columns["SystolicBP"]);
                    dbp    = Int32.Parse(statement.Columns["DiastolicBP"]);
                }

                if (height > 0)
                {
                    VisitTextHeight.Text = height.ToString();
                }
                if (weight > 0)
                {
                    VisitTextWeight.Text = weight.ToString();
                }
                if (bmi > 0)
                {
                    VisitTextBMI.Text = bmi.ToString();
                }
                if (bg > 0)
                {
                    VisitTextBG.Text = bg.ToString();
                }
                if (dbp > 0 && sbp > 0)
                {
                    VisitTextBP.Text = sbp.ToString() + "/" + dbp.ToString();
                }
            }
            catch (Exception ex)
            {
                var result = SQLiteWinRT.Database.GetSqliteErrorCode(ex.HResult);
                Debug.WriteLine("CREATE_NEW_VISIT---Add_Visit_Clicked" + "\n" + ex.Message + "\n" + result.ToString());
            }
        }
Esempio n. 19
0
        private async void RegionClickCanvas_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (isSelecting == false)
            {
                return;
            }

            isSelecting = false;
            CursorClipper.UnClipCursor();
            RegionClickCanvas.ReleaseMouseCapture();
            Matrix m = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice;

            System.Windows.Point mPt         = GetMousePos();
            System.Windows.Point movingPoint = e.GetPosition(this);
            movingPoint.X *= m.M11;
            movingPoint.Y *= m.M22;

            movingPoint.X = Math.Round(movingPoint.X);
            movingPoint.Y = Math.Round(movingPoint.Y);

            if (mPt == movingPoint)
            {
                Debug.WriteLine("Probably on Screen 1");
            }

            double correctedLeft = Left;
            double correctedTop  = Top;

            if (correctedLeft < 0)
            {
                correctedLeft = 0;
            }

            if (correctedTop < 0)
            {
                correctedTop = 0;
            }

            double xDimScaled = Canvas.GetLeft(selectBorder) * m.M11;
            double yDimScaled = Canvas.GetTop(selectBorder) * m.M22;

            Rectangle regionScaled = new Rectangle(
                (int)xDimScaled,
                (int)yDimScaled,
                (int)(selectBorder.Width * m.M11),
                (int)(selectBorder.Height * m.M22));

            string grabbedText = "";

            try { RegionClickCanvas.Children.Remove(selectBorder); } catch { }

            if (regionScaled.Width < 3 || regionScaled.Height < 3)
            {
                BackgroundBrush.Opacity = 0;
                grabbedText             = await ImageMethods.GetClickedWord(this, new System.Windows.Point(xDimScaled, yDimScaled));
            }
            else
            {
                grabbedText = await ImageMethods.GetRegionsText(this, regionScaled);
            }

            if (Settings.Default.CorrectErrors)
            {
                grabbedText.TryFixEveryWordLetterNumberErrors();
            }

            if (SingleLineMenuItem.IsChecked == true)
            {
                grabbedText = grabbedText.MakeStringSingleLine();
            }

            if (string.IsNullOrWhiteSpace(grabbedText) == false)
            {
                textFromOCR = grabbedText;

                if (Settings.Default.NeverAutoUseClipboard == false &&
                    EditWindow is null)
                {
                    Clipboard.SetText(grabbedText);
                }

                if (Settings.Default.ShowToast &&
                    EditWindow is null)
                {
                    NotificationUtilities.ShowToast(grabbedText);
                }

                if (EditWindow is not null)
                {
                    EditWindow.AddThisText(grabbedText);
                }

                WindowUtilities.CloseAllFullscreenGrabs();
            }
            else
            {
                BackgroundBrush.Opacity = .2;
                clippingGeometry.Rect   = new Rect(
                    new System.Windows.Point(0, 0),
                    new System.Windows.Size(0, 0));
            }
        }
Esempio n. 20
0
        public Bitmap DrawLegend()
        {
            int lineWidth = 3;

            int    xOffset      = 0;
            int    yOffset      = 0;
            int    maxTextWidth = 0;
            Bitmap bmp          = new Bitmap(500, 500);

            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.Clear(ImageBackgroundColor);
                g.SmoothingMode = SmoothingMode.AntiAlias;

                if (ChartLegend.Layout == LegendLayout.VERTICAL)
                {
                    foreach (LegendEntry entry in ChartLegend.LegendEntries)
                    {
                        if (entry.EntryLabel.Dimensions.Value.Width > maxTextWidth)
                        {
                            maxTextWidth = (int)entry.EntryLabel.Dimensions.Value.Width;
                        }

                        int textHeight = (int)entry.EntryLabel.Dimensions.Value.Height;

                        if (yOffset == 0)
                        {
                            yOffset = (textHeight - ChartLegend.SizeOfLegendIcon) / 2;
                        }

                        switch (entry.LegendDisplayShape)
                        {
                        case LegendDisplayType.SQUARE:
                            g.FillRectangle(new SolidBrush(entry.IconColor), new Rectangle(xOffset, yOffset, ChartLegend.SizeOfLegendIcon, ChartLegend.SizeOfLegendIcon));
                            break;

                        case LegendDisplayType.LINE:
                            g.DrawLine(new Pen(entry.IconColor, lineWidth),
                                       new Point(0, yOffset + (textHeight / 2)),
                                       new Point(ChartLegend.SizeOfLegendIcon, yOffset + (textHeight / 2)));
                            break;
                        }

                        xOffset += ChartLegend.SizeOfLegendIcon + ChartLegend.GapBetweenIconAndText;
                        yOffset -= (textHeight - ChartLegend.SizeOfLegendIcon) / 2;
                        g.DrawString(entry.EntryLabel.Text, ChartLegend.LegendEntryFont, Brushes.Black, new Point(xOffset, yOffset));
                        yOffset += textHeight + ChartLegend.GapBetweenIconAndText;
                        xOffset  = 0;
                    }
                    yOffset      -= ChartLegend.GapBetweenIconAndText;
                    maxTextWidth += ChartLegend.SizeOfLegendIcon + ChartLegend.GapBetweenIconAndText;
                }

                else if (ChartLegend.Layout == LegendLayout.HORIZONTAL)
                {
                    // In the HORIZONTAL layout the text is aligned in a single row.
                    // The gap between an icon and text is GapBetweenIconAndText.
                    // The gap between the text of an entry and the NEXT entry's icon is 2 x GapBetweenIconAndText.
                    int textHeight = 0;
                    foreach (LegendEntry entry in ChartLegend.LegendEntries)
                    {
                        textHeight = (int)entry.EntryLabel.Dimensions.Value.Height;

                        switch (entry.LegendDisplayShape)
                        {
                        case LegendDisplayType.SQUARE:
                            g.FillRectangle(new SolidBrush(entry.IconColor), new Rectangle(xOffset, yOffset, ChartLegend.SizeOfLegendIcon, ChartLegend.SizeOfLegendIcon));
                            break;

                        case LegendDisplayType.LINE:
                            g.DrawLine(new Pen(entry.IconColor, lineWidth),
                                       new Point(0, yOffset + (textHeight / 2)),
                                       new Point(ChartLegend.SizeOfLegendIcon, yOffset + (textHeight / 2)));
                            break;
                        }

                        xOffset += ChartLegend.SizeOfLegendIcon + ChartLegend.GapBetweenIconAndText;
                        g.DrawString(entry.EntryLabel.Text, ChartLegend.LegendEntryFont, Brushes.Black, new Point(xOffset, yOffset));
                        xOffset += (int)entry.EntryLabel.Dimensions.Value.Width + (2 * ChartLegend.GapBetweenIconAndText);
                    }

                    maxTextWidth = xOffset;
                    yOffset      = textHeight;
                }

                bmp = ImageMethods.CropImage(bmp, new Rectangle(new Point(0, 0), new Size(maxTextWidth, yOffset)));
            }

            return(bmp);
        }
        public ImageElement FindImageElement(Bitmap smallBmp, double accuracy)
        {
            UIControlsHelper.HideAllForms();
            bool    testMode  = TestMode;
            dynamic element   = null;
            double  tolerance = 1.0 - accuracy;

            Bitmap bigBmp = ImageMethods.Screenshot();

            Bitmap smallTestBmp = new Bitmap(smallBmp);

            Bitmap   bigTestBmp      = new Bitmap(bigBmp);
            Graphics bigTestGraphics = Graphics.FromImage(bigTestBmp);

            BitmapData smallData =
                smallBmp.LockBits(new Rectangle(0, 0, smallBmp.Width, smallBmp.Height),
                                  ImageLockMode.ReadOnly,
                                  PixelFormat.Format24bppRgb);
            BitmapData bigData =
                bigBmp.LockBits(new Rectangle(0, 0, bigBmp.Width, bigBmp.Height),
                                ImageLockMode.ReadOnly,
                                PixelFormat.Format24bppRgb);

            int smallStride = smallData.Stride;
            int bigStride   = bigData.Stride;

            int bigWidth    = bigBmp.Width;
            int bigHeight   = bigBmp.Height - smallBmp.Height + 1;
            int smallWidth  = smallBmp.Width * 3;
            int smallHeight = smallBmp.Height;

            int margin = Convert.ToInt32(255.0 * tolerance);

            unsafe
            {
                byte *pSmall = (byte *)(void *)smallData.Scan0;
                byte *pBig   = (byte *)(void *)bigData.Scan0;

                int smallOffset = smallStride - smallBmp.Width * 3;
                int bigOffset   = bigStride - bigBmp.Width * 3;

                bool matchFound = true;

                for (int y = 0; y < bigHeight; y++)
                {
                    for (int x = 0; x < bigWidth; x++)
                    {
                        byte *pBigBackup   = pBig;
                        byte *pSmallBackup = pSmall;

                        //Look for the small picture.
                        for (int i = 0; i < smallHeight; i++)
                        {
                            int j = 0;
                            matchFound = true;
                            for (j = 0; j < smallWidth; j++)
                            {
                                //With tolerance: pSmall value should be between margins.
                                int inf = pBig[0] - margin;
                                int sup = pBig[0] + margin;
                                if (sup < pSmall[0] || inf > pSmall[0])
                                {
                                    matchFound = false;
                                    break;
                                }

                                pBig++;
                                pSmall++;
                            }

                            if (!matchFound)
                            {
                                break;
                            }

                            //We restore the pointers.
                            pSmall = pSmallBackup;
                            pBig   = pBigBackup;

                            //Next rows of the small and big pictures.
                            pSmall += smallStride * (1 + i);
                            pBig   += bigStride * (1 + i);
                        }

                        //If match found, we return.
                        if (matchFound)
                        {
                            element = new ImageElement
                            {
                                LeftX   = x,
                                MiddleX = x + smallBmp.Width / 2,
                                RightX  = x + smallBmp.Width,
                                TopY    = y,
                                MiddleY = y + smallBmp.Height / 2,
                                BottomY = y + smallBmp.Height
                            };

                            if (testMode)
                            {
                                //draw on output to demonstrate finding
                                var Rectangle = new Rectangle(x, y, smallBmp.Width - 1, smallBmp.Height - 1);
                                Pen pen       = new Pen(Color.Red);
                                pen.Width = 5.0F;
                                bigTestGraphics.DrawRectangle(pen, Rectangle);

                                frmImageCapture captureOutput = new frmImageCapture();
                                captureOutput.pbTaggedImage.Image  = smallTestBmp;
                                captureOutput.pbSearchResult.Image = bigTestBmp;
                                captureOutput.TopMost = true;
                                captureOutput.Show();
                            }
                            break;
                        }
                        //If no match found, we restore the pointers and continue.
                        else
                        {
                            pBig   = pBigBackup;
                            pSmall = pSmallBackup;
                            pBig  += 3;
                        }
                    }

                    if (matchFound)
                    {
                        break;
                    }

                    pBig += bigOffset;
                }
            }

            bigBmp.UnlockBits(bigData);
            smallBmp.UnlockBits(smallData);
            bigTestGraphics.Dispose();
            return(element);
        }
Esempio n. 22
0
        private void Encode(List <FrameInfo> listFrames, int id, string fileName, Export type, CancellationTokenSource tokenSource)
        {
            if (type == Export.Gif)
            {
                #region Gif

                if (Settings.Default.CustomEncoding)
                {
                    #region Custom Gif Encoding

                    using (var encoder = new AnimatedGifEncoder())
                    {
                        string cutFolder = null;

                        #region Cut/Paint Unchanged Pixels

                        if (Settings.Default.DetectUnchanged)
                        {
                            Update(id, 0, "Analizing Unchanged Pixels");

                            if (Settings.Default.PaintTransparent)
                            {
                                var color = Color.FromArgb(Settings.Default.TransparentColor.R,
                                                           Settings.Default.TransparentColor.G, Settings.Default.TransparentColor.B);

                                listFrames = ImageMethods.PaintTransparentAndCut(listFrames, color, id, tokenSource);

                                //TODO: Use System.Windows.Media.Color inside the AnimatedGifEncoder.
                                encoder.SetTransparent(color);
                                encoder.SetDispose(1); //Undraw Method, "Leave".
                            }
                            else
                            {
                                listFrames = ImageMethods.CutUnchanged(listFrames, id, tokenSource);
                            }
                        }

                        #endregion

                        encoder.Start(fileName);
                        encoder.SetQuality(Settings.Default.Quality);
                        encoder.SetRepeat(Settings.Default.Looped ? (Settings.Default.RepeatForever ? 0 : Settings.Default.RepeatCount) : -1); // 0 = Always, -1 once

                        int numImage = 0;
                        foreach (FrameInfo image in listFrames)
                        {
                            #region Cancellation

                            if (tokenSource.Token.IsCancellationRequested)
                            {
                                SetStatus(Status.Cancelled, id);

                                break;
                            }

                            #endregion

                            var bitmapAux = new Bitmap(image.ImageLocation);

                            encoder.SetDelay(image.Delay);
                            encoder.AddFrame(bitmapAux, image.PositionTopLeft.X, image.PositionTopLeft.Y);

                            bitmapAux.Dispose();

                            Update(id, numImage, "Processing " + numImage);
                            numImage++;
                        }

                        #region Specific Clear

                        try
                        {
                            if (!String.IsNullOrEmpty(cutFolder))
                            {
                                if (Directory.Exists(cutFolder))
                                {
                                    Directory.Delete(cutFolder, true);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            LogWriter.Log(ex, "Errow while Deleting and Cleaning Specific Variables");
                        }

                        #endregion
                    }

                    #endregion
                }
                else
                {
                    #region paint.NET encoding

                    //0 = Always, -1 = no repeat, n = repeat number (first shown + repeat number = total number of iterations)
                    var repeat = (Settings.Default.Looped ? (Settings.Default.RepeatForever ? 0 : Settings.Default.RepeatCount) : -1);

                    using (var stream = new MemoryStream())
                    {
                        using (var encoderNet = new GifEncoder(stream, null, null, repeat))
                        {
                            for (int i = 0; i < listFrames.Count; i++)
                            {
                                var bitmapAux = new Bitmap(listFrames[i].ImageLocation);
                                encoderNet.AddFrame(bitmapAux, 0, 0, TimeSpan.FromMilliseconds(listFrames[i].Delay));
                                bitmapAux.Dispose();

                                Update(id, i, "Processing " + i);

                                #region Cancellation

                                if (tokenSource.Token.IsCancellationRequested)
                                {
                                    SetStatus(Status.Cancelled, id);

                                    break;
                                }

                                #endregion
                            }
                        }

                        stream.Position = 0;

                        try
                        {
                            using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None,
                                                                   Constants.BufferSize, false))
                            {
                                stream.WriteTo(fileStream);
                            }
                        }
                        catch (Exception ex)
                        {
                            SetStatus(Status.Error, id);
                            LogWriter.Log(ex, "Error while writing to disk.");
                        }
                    }

                    #endregion
                }

                #endregion
            }
            else
            {
                #region Avi

                var image = listFrames[0].ImageLocation.SourceFrom();

                using (var aviWriter = new AviWriter(fileName, 1000 / listFrames[0].Delay,
                                                     (int)image.PixelWidth, (int)image.PixelHeight, 5000))
                {
                    int numImage = 0;
                    foreach (FrameInfo frame in listFrames)
                    {
                        using (MemoryStream outStream = new MemoryStream())
                        {
                            var bitImage = frame.ImageLocation.SourceFrom();

                            var enc = new BmpBitmapEncoder();
                            enc.Frames.Add(BitmapFrame.Create(bitImage));
                            enc.Save(outStream);

                            outStream.Flush();

                            using (var bitmap = new Bitmap(outStream))
                            {
                                aviWriter.AddFrame(bitmap);
                            }
                        }

                        //aviWriter.AddFrame(new BitmapImage(new Uri(frame.ImageLocation)));

                        Update(id, numImage, "Processing " + numImage);
                        numImage++;

                        #region Cancellation

                        if (tokenSource.Token.IsCancellationRequested)
                        {
                            SetStatus(Status.Cancelled, id);
                            break;
                        }

                        #endregion
                    }
                }

                #endregion
            }

            #region Delete Encoder Folder

            try
            {
                var encoderFolder = Path.GetDirectoryName(listFrames[0].ImageLocation);

                if (!String.IsNullOrEmpty(encoderFolder))
                {
                    if (Directory.Exists(encoderFolder))
                    {
                        Directory.Delete(encoderFolder, true);
                    }
                }
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Errow while deleting and cleaning the Encode folder");
            }

            #endregion

            GC.Collect();

            if (!tokenSource.Token.IsCancellationRequested)
            {
                SetStatus(Status.Completed, id, fileName);
            }
        }
Esempio n. 23
0
        private async Task GetSampleDataAsync()
        {
            if (this._groups.Count != 0)
            {
                return;
            }


            this.db = App.database;

            if (this.db != null)
            {
                //Create a hashmap of (pid, item) and one by one query DB and add all the details to it.
                try
                {
                    //string query = "SELECT * FROM (Patient NATURAL JOIN MutableDetails) NATURAL JOIN (Address NATURAL JOIN (AddressZIP NATURAL JOIN (AddressCity NATURAL JOIN AddressState)))";
                    string query = "SELECT Patient.PID, Patient.FirstName, Patient.LastName, Patient.BloodGroup, Patient.Sex, Patient.Birthday, Patient.Image, MutableDetails.Married, MutableDetails.Occupation, MutableDetails.FamilyBackground, MutableDetails.Email, MutableDetails.Mobile, MutableDetails.EmMobile, Address.ZIP, Address.Street, AddressCity.City, AddressCity.State, AddressState.Country FROM (((((Patient INNER JOIN MutableDetails ON Patient.PID = MutableDetails.PID) INNER JOIN Address ON MutableDetails.PID = Address.PID) INNER JOIN AddressZIP ON Address.ZIP = AddressZIP.ZIP) INNER JOIN AddressCity ON AddressZIP.CITY = AddressCity.CITY)  INNER JOIN AddressState ON AddressCity.STATE = AddressState.STATE)";

                    Statement statement = await db.PrepareStatementAsync(query);

                    statement.EnableColumnsProperty();
                    Dictionary <string, AnalysisSampleDataItem> group = new Dictionary <string, AnalysisSampleDataItem>();

                    while (await statement.StepAsync())
                    {
                        //Debug.WriteLine(statement.Columns["PID"] + " " + statement.Columns["FirstName"] + " " + statement.Columns["LastName"] + " " + statement.Columns["ZIP"] + " " + statement.Columns["City"] + " " + statement.Columns["State"] + " " + statement.Columns["Country"] + " " + statement.Columns["Occupation"] + " " + statement.Columns["Married"]);
                        AnalysisSampleDataItem newItem = new AnalysisSampleDataItem();
                        newItem.UniqueId = statement.Columns["PID"];
                        BitmapImage bmp = await ImageMethods.Base64StringToBitmap(statement.Columns["Image"]);

                        newItem.Name       = statement.Columns["FirstName"] + " " + statement.Columns["LastName"];
                        newItem.BloodGroup = statement.Columns["BloodGroup"];
                        newItem.Sex        = statement.Columns["Sex"][0];
                        newItem.Image      = bmp;

                        if (statement.Columns["Married"].Equals("T"))
                        {
                            newItem.Married = true;
                        }
                        else
                        {
                            newItem.Married = false;
                        }

                        newItem.Occupation = statement.Columns["Occupation"];
                        newItem.FamilyBG   = statement.Columns["FamilyBackground"];
                        newItem.City       = statement.Columns["City"];
                        newItem.State      = statement.Columns["State"];
                        newItem.Country    = statement.Columns["Country"];
                        group.Add((statement.Columns["PID"]), newItem);
                    }

                    //Now after adding the basic details and creating their HASHMAP get other details from DB & add it to the HASHMAP which later
                    //would be added to Groups of the GRID VIEW.
                    statement.Reset();
                    string queryAllergy = "SELECT * FROM MutableDetailsAllergy";
                    statement = await this.db.PrepareStatementAsync(queryAllergy);

                    statement.EnableColumnsProperty();

                    while (await statement.StepAsync())
                    {
                        List <string> sample = group[(statement.Columns["PID"])].Allergy;
                        if (sample != null)
                        {
                            sample.Add(statement.Columns["Allergy"]);
                        }
                    }

                    statement.Reset();
                    string queryAddiction = "SELECT * FROM MutableDetailsAddiction";
                    statement = await this.db.PrepareStatementAsync(queryAddiction);

                    statement.EnableColumnsProperty();

                    while (await statement.StepAsync())
                    {
                        List <string> sample = group[(statement.Columns["PID"])].Addiction;
                        if (sample != null)
                        {
                            sample.Add(statement.Columns["Addiction"]);
                        }
                    }

                    statement.Reset();
                    string queryOperation = "SELECT * FROM MutableDetailsOperation";
                    statement = await this.db.PrepareStatementAsync(queryOperation);

                    statement.EnableColumnsProperty();

                    while (await statement.StepAsync())
                    {
                        List <string> sample = group[(statement.Columns["PID"])].Operation;
                        if (sample != null)
                        {
                            sample.Add(statement.Columns["Operation"]);
                        }
                    }

                    statement.Reset();
                    string queryDateVisited = "SELECT * FROM MedicalDetails";
                    statement = await this.db.PrepareStatementAsync(queryDateVisited);

                    statement.EnableColumnsProperty();

                    while (await statement.StepAsync())
                    {
                        List <string> sampleDatesVisited           = group[(statement.Columns["PID"])].DatesVisited;
                        Dictionary <string, string> sampleVaccines = group[(statement.Columns["PID"])].Vaccines;
                        Dictionary <string, string> sampleDiseases = group[(statement.Columns["PID"])].Diseases;
                        if (sampleDatesVisited != null && sampleDiseases != null && sampleVaccines != null)
                        {
                            sampleDatesVisited.Add(statement.Columns["DateVisited"]);
                            sampleVaccines.Add(statement.Columns["DateVisited"], "0");
                            sampleDiseases.Add(statement.Columns["DateVisited"], statement.Columns["DiseaseFound"]);
                        }
                    }

                    statement.Reset();
                    string queryVaccines = "SELECT * FROM MedicalDetailsVaccine";
                    statement = await this.db.PrepareStatementAsync(queryVaccines);

                    statement.EnableColumnsProperty();

                    while (await statement.StepAsync())
                    {
                        Dictionary <string, string> sampleVaccines = group[(statement.Columns["PID"])].Vaccines;
                        if (sampleVaccines != null)
                        {
                            sampleVaccines[statement.Columns["DateVisited"]] = statement.Columns["Vaccine"];
                        }
                    }

                    //After adding all the details add the items to GRID VIEW
                    foreach (KeyValuePair <string, AnalysisSampleDataItem> sample in group)
                    {
                        Groups.Add(sample.Value);
                    }

                    //Collect garbage after all this loading happens
                    GC.Collect();
                }
                catch (Exception ex)
                {
                    var result = SQLiteWinRT.Database.GetSqliteErrorCode(ex.HResult);
                    Debug.WriteLine("ANALYSIS_PAGE_DATA_SOURCE---LOAD_ITEMS_ASYNC" + "\n" + ex.Message + "\n" + result.ToString());
                }
            }
        }
Esempio n. 24
0
        private async Task GetSampleDataAsync()
        {
            if (this.Groups.Count() == 0)
            {
                try
                {
                    this.db = App.database;

                    if (this.db != null)
                    {
                        //string query = "SELECT * FROM (Patient NATURAL JOIN (Address NATURAL JOIN AddressZIP));";
                        string    query     = "SELECT Patient.PID, Patient.FirstName, Patient.LastName, Patient.BloodGroup, Patient.Sex, Patient.Birthday, Patient.Image, Address.ZIP, Address.Street, AddressZIP.City FROM ((Patient INNER JOIN Address ON Patient.PID = Address.PID) INNER JOIN AddressZIP ON AddressZIP.ZIP = Address.ZIP)";
                        Statement statement = await db.PrepareStatementAsync(query);

                        statement.EnableColumnsProperty();
                        List <SampleDataGroup> sampleList = new List <SampleDataGroup>();
                        int edgeCaseCount = 0;
                        //string prevGroup = "xxx";
                        //SampleDataGroup groups = null;

                        //Check previous entered city and current city are same. if same -> add new item to same grp; if not -> create new grp and
                        //add the new item to this new grp.
                        while (await statement.StepAsync())
                        {
                            //Debug.WriteLine(statement.Columns["PID"] + " " + statement.Columns["FirstName"] + " " + statement.Columns["LastName"] + " " + statement.Columns["ZIP"] + " " + statement.Columns["City"]);
                            edgeCaseCount++;
                            BitmapImage bmp = await ImageMethods.Base64StringToBitmap(statement.Columns["Image"]);

                            SampleDataGroup sampleGroup = Groups.ToList().Find(item => item.Title.Equals(statement.Columns["City"]));
                            if (sampleGroup == null)
                            {
                                sampleGroup = new SampleDataGroup(statement.Columns["City"], statement.Columns["City"]);
                                sampleGroup.Items.Add(new SampleDataItem(statement.Columns["PID"], statement.Columns["FirstName"] + " " + statement.Columns["LastName"], statement.Columns["Street"], bmp));
                                Groups.Add(sampleGroup);
                            }
                            else
                            {
                                sampleGroup.Items.Add(new SampleDataItem(statement.Columns["PID"], statement.Columns["FirstName"] + " " + statement.Columns["LastName"], statement.Columns["Street"], bmp));
                            }
                            //string currentGroup = statement.Columns["City"];
                            //if (currentGroup.Equals(prevGroup))
                            //{
                            //    BitmapImage bmp = await ImageMethods.Base64StringToBitmap(statement.Columns["Image"]);
                            //    groups.Items.Add(new SampleDataItem(statement.Columns["PID"], statement.Columns["FirstName"] + " " + statement.Columns["LastName"], statement.Columns["Street"], bmp));
                            //}
                            //else
                            //{
                            //    if (groups != null)
                            //    {
                            //        this.Groups.Add(groups);
                            //    }

                            //    BitmapImage bmp = await ImageMethods.Base64StringToBitmap(statement.Columns["Image"]);
                            //    groups = new SampleDataGroup(statement.Columns["City"], statement.Columns["City"]);
                            //    groups.Items.Add(new SampleDataItem(statement.Columns["PID"], statement.Columns["FirstName"] + " " + statement.Columns["LastName"], statement.Columns["Street"], bmp));
                            //}
                            //prevGroup = currentGroup;
                        }
                        //foreach (SampleDataGroup group in sampleList)
                        //{
                        //    this.Groups.Add(group);
                        //}
                        //if (groups != null)
                        //{
                        //    this.Groups.Add(groups);
                        //}
                    }
                }
                catch (Exception ex)
                {
                    var result = SQLiteWinRT.Database.GetSqliteErrorCode(ex.HResult);
                    Debug.WriteLine("HOME_PAGE_DATA_SOURCE---LOAD_GROUP_ASYNC" + "\n" + ex.Message + "\n" + result.ToString());
                }
            }
            return;
        }
Esempio n. 25
0
 public void SetImageToBackground()
 {
     BackgroundImage.Source  = ImageMethods.GetWindowBoundsImage(this);
     BackgroundBrush.Opacity = 0.2;
 }
Esempio n. 26
0
        public static ImageElement FindImageElement(Bitmap smallBmp, double accuracy, IAutomationEngineInstance engine, DateTime timeToEnd, bool isCaptureTest = false)
        {
            FormsHelper.HideAllForms();

            var     lastRecordedTime = DateTime.Now;
            dynamic element          = null;
            double  tolerance        = 1.0 - accuracy;

            Bitmap bigBmp = ImageMethods.Screenshot();

            Bitmap smallTestBmp = new Bitmap(smallBmp);

            Bitmap   bigTestBmp      = new Bitmap(bigBmp);
            Graphics bigTestGraphics = Graphics.FromImage(bigTestBmp);

            BitmapData smallData =
                smallBmp.LockBits(new Rectangle(0, 0, smallBmp.Width, smallBmp.Height),
                                  ImageLockMode.ReadOnly,
                                  PixelFormat.Format24bppRgb);
            BitmapData bigData =
                bigBmp.LockBits(new Rectangle(0, 0, bigBmp.Width, bigBmp.Height),
                                ImageLockMode.ReadOnly,
                                PixelFormat.Format24bppRgb);

            int smallStride = smallData.Stride;
            int bigStride   = bigData.Stride;

            int bigWidth    = bigBmp.Width;
            int bigHeight   = bigBmp.Height - smallBmp.Height + 1;
            int smallWidth  = smallBmp.Width * 3;
            int smallHeight = smallBmp.Height;

            int margin = Convert.ToInt32(255.0 * tolerance);

            unsafe
            {
                byte *pSmall = (byte *)(void *)smallData.Scan0;
                byte *pBig   = (byte *)(void *)bigData.Scan0;

                int smallOffset = smallStride - smallBmp.Width * 3;
                int bigOffset   = bigStride - bigBmp.Width * 3;

                bool matchFound = true;

                for (int y = 0; y < bigHeight; y++)
                {
                    if (engine != null && engine.IsCancellationPending)
                    {
                        break;
                    }

                    if (engine != null && lastRecordedTime.Second != DateTime.Now.Second)
                    {
                        engine.ReportProgress("Element Not Yet Found... " + (timeToEnd - DateTime.Now).Seconds + "s remain");
                        lastRecordedTime = DateTime.Now;
                    }

                    if (timeToEnd <= DateTime.Now)
                    {
                        break;
                    }

                    for (int x = 0; x < bigWidth; x++)
                    {
                        byte *pBigBackup   = pBig;
                        byte *pSmallBackup = pSmall;

                        //Look for the small picture.
                        for (int i = 0; i < smallHeight; i++)
                        {
                            int j = 0;
                            matchFound = true;
                            for (j = 0; j < smallWidth; j++)
                            {
                                //With tolerance: pSmall value should be between margins.
                                int inf = pBig[0] - margin;
                                int sup = pBig[0] + margin;
                                if (sup < pSmall[0] || inf > pSmall[0])
                                {
                                    matchFound = false;
                                    break;
                                }

                                pBig++;
                                pSmall++;
                            }

                            if (!matchFound)
                            {
                                break;
                            }

                            //We restore the pointers.
                            pSmall = pSmallBackup;
                            pBig   = pBigBackup;

                            //Next rows of the small and big pictures.
                            pSmall += smallStride * (1 + i);
                            pBig   += bigStride * (1 + i);
                        }

                        //If match found, we return.
                        if (matchFound)
                        {
                            element = new ImageElement
                            {
                                LeftX   = x,
                                MiddleX = x + smallBmp.Width / 2,
                                RightX  = x + smallBmp.Width,
                                TopY    = y,
                                MiddleY = y + smallBmp.Height / 2,
                                BottomY = y + smallBmp.Height
                            };

                            if (isCaptureTest)
                            {
                                element.SmallTestImage = smallTestBmp;
                                element.BigTestImage   = bigTestBmp;
                            }

                            break;
                        }
                        //If no match found, we restore the pointers and continue.
                        else
                        {
                            pBig   = pBigBackup;
                            pSmall = pSmallBackup;
                            pBig  += 3;
                        }
                    }

                    if (matchFound)
                    {
                        break;
                    }

                    pBig += bigOffset;
                }
            }

            bigBmp.UnlockBits(bigData);
            smallBmp.UnlockBits(smallData);
            bigTestGraphics.Dispose();
            return(element);
        }
Esempio n. 27
0
        private void Encode(List <FrameInfo> listFrames, int id, Parameters param, CancellationTokenSource tokenSource)
        {
            var processing = this.DispatcherStringResource("Encoder.Processing");

            try
            {
                switch (param.Type)
                {
                case Export.Gif:

                    #region Gif

                    #region Cut/Paint Unchanged Pixels

                    if (param.EncoderType == GifEncoderType.Legacy || param.EncoderType == GifEncoderType.ScreenToGif)
                    {
                        if (param.DetectUnchangedPixels)
                        {
                            Update(id, 0, FindResource("Encoder.Analyzing").ToString());

                            if (param.DummyColor.HasValue)
                            {
                                var color = Color.FromArgb(param.DummyColor.Value.R, param.DummyColor.Value.G, param.DummyColor.Value.B);

                                listFrames = ImageMethods.PaintTransparentAndCut(listFrames, color, id, tokenSource);
                            }
                            else
                            {
                                listFrames = ImageMethods.CutUnchanged(listFrames, id, tokenSource);
                            }
                        }
                        else
                        {
                            var size = listFrames[0].Path.ScaledSize();
                            listFrames.ForEach(x => x.Rect = new Int32Rect(0, 0, (int)size.Width, (int)size.Height));
                        }
                    }

                    #endregion

                    switch (param.EncoderType)
                    {
                    case GifEncoderType.ScreenToGif:

                        #region Improved encoding

                        using (var stream = new MemoryStream())
                        {
                            using (var encoder = new GifFile(stream, param.RepeatCount))
                            {
                                encoder.UseGlobalColorTable = param.UseGlobalColorTable;
                                encoder.TransparentColor    = param.DummyColor;
                                encoder.MaximumNumberColor  = param.MaximumNumberColors;

                                for (var i = 0; i < listFrames.Count; i++)
                                {
                                    if (!listFrames[i].HasArea && param.DetectUnchangedPixels)
                                    {
                                        continue;
                                    }

                                    if (listFrames[i].Delay == 0)
                                    {
                                        listFrames[i].Delay = 10;
                                    }

                                    encoder.AddFrame(listFrames[i].Path, listFrames[i].Rect, listFrames[i].Delay);

                                    Update(id, i, string.Format(processing, i));

                                    #region Cancellation

                                    if (tokenSource.Token.IsCancellationRequested)
                                    {
                                        SetStatus(Status.Canceled, id);
                                        break;
                                    }

                                    #endregion
                                }
                            }

                            try
                            {
                                using (var fileStream = new FileStream(param.Filename, FileMode.Create, FileAccess.Write, FileShare.None, 4096))
                                    stream.WriteTo(fileStream);
                            }
                            catch (Exception ex)
                            {
                                SetStatus(Status.Error, id);
                                LogWriter.Log(ex, "Improved Encoding");
                            }
                        }

                        #endregion

                        break;

                    case GifEncoderType.Legacy:

                        #region Legacy Encoding

                        using (var encoder = new AnimatedGifEncoder())
                        {
                            if (param.DummyColor.HasValue)
                            {
                                var color = Color.FromArgb(param.DummyColor.Value.R,
                                                           param.DummyColor.Value.G, param.DummyColor.Value.B);

                                encoder.SetTransparent(color);
                                encoder.SetDispose(1);         //Undraw Method, "Leave".
                            }

                            encoder.Start(param.Filename);
                            encoder.SetQuality(param.Quality);
                            encoder.SetRepeat(param.RepeatCount);

                            var numImage = 0;
                            foreach (var frame in listFrames)
                            {
                                #region Cancellation

                                if (tokenSource.Token.IsCancellationRequested)
                                {
                                    SetStatus(Status.Canceled, id);
                                    break;
                                }

                                #endregion

                                if (!frame.HasArea && param.DetectUnchangedPixels)
                                {
                                    continue;
                                }

                                var bitmapAux = new Bitmap(frame.Path);

                                encoder.SetDelay(frame.Delay);
                                encoder.AddFrame(bitmapAux, frame.Rect.X, frame.Rect.Y);

                                bitmapAux.Dispose();

                                Update(id, numImage, string.Format(processing, numImage));
                                numImage++;
                            }
                        }

                        #endregion

                        break;

                    case GifEncoderType.PaintNet:

                        #region paint.NET encoding

                        using (var stream = new MemoryStream())
                        {
                            using (var encoder = new GifEncoder(stream, null, null, param.RepeatCount))
                            {
                                for (var i = 0; i < listFrames.Count; i++)
                                {
                                    var bitmapAux = new Bitmap(listFrames[i].Path);
                                    encoder.AddFrame(bitmapAux, 0, 0, TimeSpan.FromMilliseconds(listFrames[i].Delay));
                                    bitmapAux.Dispose();

                                    Update(id, i, string.Format(processing, i));

                                    #region Cancellation

                                    if (tokenSource.Token.IsCancellationRequested)
                                    {
                                        SetStatus(Status.Canceled, id);

                                        break;
                                    }

                                    #endregion
                                }
                            }

                            stream.Position = 0;

                            try
                            {
                                using (var fileStream = new FileStream(param.Filename, FileMode.Create, FileAccess.Write, FileShare.None, Constants.BufferSize, false))
                                    stream.WriteTo(fileStream);
                            }
                            catch (Exception ex)
                            {
                                SetStatus(Status.Error, id);
                                LogWriter.Log(ex, "Encoding with paint.Net.");
                            }
                        }

                        #endregion

                        break;

                    case GifEncoderType.FFmpeg:

                        #region FFmpeg encoding

                        SetStatus(Status.Processing, id, null, true);

                        if (!Util.Other.IsFfmpegPresent())
                        {
                            throw new ApplicationException("FFmpeg not present.");
                        }

                        if (File.Exists(param.Filename))
                        {
                            File.Delete(param.Filename);
                        }

                        #region Generate concat

                        var concat = new StringBuilder();
                        foreach (var frame in listFrames)
                        {
                            concat.AppendLine("file '" + frame.Path + "'");
                            concat.AppendLine("duration " + (frame.Delay / 1000d).ToString(CultureInfo.InvariantCulture));
                        }

                        var concatPath = Path.GetDirectoryName(listFrames[0].Path) ?? Path.GetTempPath();
                        var concatFile = Path.Combine(concatPath, "concat.txt");

                        if (!Directory.Exists(concatPath))
                        {
                            Directory.CreateDirectory(concatPath);
                        }

                        if (File.Exists(concatFile))
                        {
                            File.Delete(concatFile);
                        }

                        File.WriteAllText(concatFile, concat.ToString());

                        #endregion

                        param.Command = string.Format(param.Command, concatFile, param.ExtraParameters.Replace("{H}", param.Height.ToString()).Replace("{W}", param.Width.ToString()), param.Filename);

                        var process = new ProcessStartInfo(UserSettings.All.FfmpegLocation)
                        {
                            Arguments             = param.Command,
                            CreateNoWindow        = true,
                            ErrorDialog           = false,
                            UseShellExecute       = false,
                            RedirectStandardError = true
                        };

                        var pro = Process.Start(process);

                        var str = pro.StandardError.ReadToEnd();

                        var fileInfo = new FileInfo(param.Filename);

                        if (!fileInfo.Exists || fileInfo.Length == 0)
                        {
                            throw new Exception("Error while encoding the gif with FFmpeg.")
                                  {
                                      HelpLink = str
                                  }
                        }
                        ;

                        #endregion

                        break;

                    case GifEncoderType.Gifski:

                        #region Gifski encoding

                        SetStatus(Status.Processing, id, null, true);

                        if (!Util.Other.IsGifskiPresent())
                        {
                            throw new ApplicationException("Gifski not present.");
                        }

                        if (File.Exists(param.Filename))
                        {
                            File.Delete(param.Filename);
                        }

                        var outputPath = Path.GetDirectoryName(listFrames[0].Path);
                        var fps        = !param.ExtraParameters.Contains("--fps") ? "--fps " + (int)(1000d / listFrames.Average(x => x.Delay)) : "";

                        param.Command = $"{param.ExtraParameters} {fps} -o \"{param.Filename}\" \"{Path.Combine(outputPath, "*.png")}\"";

                        var process2 = new ProcessStartInfo(UserSettings.All.GifskiLocation)
                        {
                            Arguments             = param.Command,
                            CreateNoWindow        = true,
                            ErrorDialog           = false,
                            UseShellExecute       = false,
                            RedirectStandardError = true
                        };

                        var pro2 = Process.Start(process2);

                        var str2 = pro2.StandardError.ReadToEnd();

                        var fileInfo2 = new FileInfo(param.Filename);

                        if (!fileInfo2.Exists || fileInfo2.Length == 0)
                        {
                            throw new Exception("Error while encoding the gif with Gifski.")
                                  {
                                      HelpLink = str2
                                  }
                        }
                        ;

                        #endregion

                        break;

                    default:
                        throw new Exception("Undefined Gif encoder type");
                    }

                    #endregion

                    break;

                case Export.Apng:

                    #region Apng

                    #region Cut/Paint Unchanged Pixels

                    if (param.DetectUnchangedPixels)
                    {
                        Update(id, 0, FindResource("Encoder.Analyzing").ToString());

                        if (param.DummyColor.HasValue)
                        {
                            var color = Color.FromArgb(param.DummyColor.Value.A, param.DummyColor.Value.R, param.DummyColor.Value.G, param.DummyColor.Value.B);
                            listFrames = ImageMethods.PaintTransparentAndCut(listFrames, color, id, tokenSource);
                        }
                        else
                        {
                            listFrames = ImageMethods.CutUnchanged(listFrames, id, tokenSource);
                        }
                    }
                    else
                    {
                        var size = listFrames[0].Path.ScaledSize();
                        listFrames.ForEach(x => x.Rect = new Int32Rect(0, 0, (int)size.Width, (int)size.Height));
                    }

                    #endregion

                    #region Encoding

                    using (var stream = new MemoryStream())
                    {
                        var frameCount = listFrames.Count(x => x.HasArea);

                        using (var encoder = new Apng(stream, frameCount, param.RepeatCount))
                        {
                            for (var i = 0; i < listFrames.Count; i++)
                            {
                                if (!listFrames[i].HasArea && param.DetectUnchangedPixels)
                                {
                                    continue;
                                }

                                if (listFrames[i].Delay == 0)
                                {
                                    listFrames[i].Delay = 10;
                                }

                                encoder.AddFrame(listFrames[i].Path, listFrames[i].Rect, listFrames[i].Delay);

                                Update(id, i, string.Format(processing, i));

                                #region Cancellation

                                if (tokenSource.Token.IsCancellationRequested)
                                {
                                    SetStatus(Status.Canceled, id);
                                    break;
                                }

                                #endregion
                            }
                        }

                        try
                        {
                            using (var fileStream = new FileStream(param.Filename, FileMode.Create, FileAccess.Write, FileShare.None, 4096))
                                stream.WriteTo(fileStream);
                        }
                        catch (Exception ex)
                        {
                            SetStatus(Status.Error, id);
                            LogWriter.Log(ex, "Apng Encoding");
                        }
                    }

                    #endregion

                    #endregion

                    break;

                case Export.Video:

                    #region Video

                    switch (param.VideoEncoder)
                    {
                    case VideoEncoderType.AviStandalone:

                        #region Avi Standalone

                        var image = listFrames[0].Path.SourceFrom();

                        if (File.Exists(param.Filename))
                        {
                            File.Delete(param.Filename);
                        }

                        //1000 / listFrames[0].Delay
                        using (var aviWriter = new AviWriter(param.Filename, param.Framerate, image.PixelWidth, image.PixelHeight, param.VideoQuality))
                        {
                            var numImage = 0;
                            foreach (var frame in listFrames)
                            {
                                using (var outStream = new MemoryStream())
                                {
                                    var bitImage = frame.Path.SourceFrom();

                                    var enc = new BmpBitmapEncoder();
                                    enc.Frames.Add(BitmapFrame.Create(bitImage));
                                    enc.Save(outStream);

                                    outStream.Flush();

                                    using (var bitmap = new Bitmap(outStream))
                                        aviWriter.AddFrame(bitmap, param.FlipVideo);
                                }

                                Update(id, numImage, string.Format(processing, numImage));
                                numImage++;

                                #region Cancellation

                                if (tokenSource.Token.IsCancellationRequested)
                                {
                                    SetStatus(Status.Canceled, id);
                                    break;
                                }

                                #endregion
                            }
                        }

                        #endregion

                        break;

                    case VideoEncoderType.Ffmpg:

                        #region Video using FFmpeg

                        SetStatus(Status.Processing, id, null, true);

                        if (!Util.Other.IsFfmpegPresent())
                        {
                            throw new ApplicationException("FFmpeg not present.");
                        }

                        if (File.Exists(param.Filename))
                        {
                            File.Delete(param.Filename);
                        }

                        #region Generate concat

                        var concat = new StringBuilder();
                        foreach (var frame in listFrames)
                        {
                            concat.AppendLine("file '" + frame.Path + "'");
                            concat.AppendLine("duration " + (frame.Delay / 1000d).ToString(CultureInfo.InvariantCulture));
                        }

                        var concatPath = Path.GetDirectoryName(listFrames[0].Path) ?? Path.GetTempPath();
                        var concatFile = Path.Combine(concatPath, "concat.txt");

                        if (!Directory.Exists(concatPath))
                        {
                            Directory.CreateDirectory(concatPath);
                        }

                        if (File.Exists(concatFile))
                        {
                            File.Delete(concatFile);
                        }

                        File.WriteAllText(concatFile, concat.ToString());

                        #endregion

                        param.Command = string.Format(param.Command, concatFile, param.ExtraParameters.Replace("{H}", param.Height.ToString()).Replace("{W}", param.Width.ToString()), param.Filename);

                        var process = new ProcessStartInfo(UserSettings.All.FfmpegLocation)
                        {
                            Arguments             = param.Command,
                            CreateNoWindow        = true,
                            ErrorDialog           = false,
                            UseShellExecute       = false,
                            RedirectStandardError = true
                        };

                        var pro = Process.Start(process);

                        var str = pro.StandardError.ReadToEnd();

                        var fileInfo = new FileInfo(param.Filename);

                        if (!fileInfo.Exists || fileInfo.Length == 0)
                        {
                            throw new Exception("Error while encoding with FFmpeg.")
                                  {
                                      HelpLink = str
                                  }
                        }
                        ;

                        #endregion

                        break;

                    default:
                        throw new Exception("Undefined video encoder");
                    }

                    #endregion

                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(param));
                }

                //If it was canceled, try deleting the file.
                if (tokenSource.Token.IsCancellationRequested)
                {
                    if (File.Exists(param.Filename))
                    {
                        File.Delete(param.Filename);
                    }

                    SetStatus(Status.Canceled, id);
                    return;
                }

                #region Upload

                if (param.Upload && File.Exists(param.Filename))
                {
                    InternalUpdate(id, "Encoder.Uploading", true, true);

                    try
                    {
                        //TODO: Make it less hardcoded.
                        switch (param.UploadDestinationIndex)
                        {
                        case 0:     //Imgur.
                            using (var w = new WebClient())
                            {
                                w.Headers.Add("Authorization", "Client-ID " + Secret.ImgurId);
                                var values = new NameValueCollection {
                                    { "image", Convert.ToBase64String(File.ReadAllBytes(param.Filename)) }
                                };
                                var response = w.UploadValues("https://api.imgur.com/3/upload.xml", values);
                                var x        = XDocument.Load(new MemoryStream(response));

                                var node     = x.Descendants().FirstOrDefault(n => n.Name == "link");
                                var nodeHash = x.Descendants().FirstOrDefault(n => n.Name == "deletehash");

                                if (node == null)
                                {
                                    throw new Exception("No link was provided by Imgur", new Exception(x.Document?.ToString() ?? "The document was null. :/"));
                                }

                                InternalSetUpload(id, true, node.Value, "https://imgur.com/delete/" + nodeHash?.Value);
                            }
                            break;

                        case 1:     //Gfycat.
                            using (var client = new HttpClient())
                            {
                                using (var res = client.PostAsync(@"https://api.gfycat.com/v1/gfycats", null).Result)
                                {
                                    var result = res.Content.ReadAsStringAsync().Result;
                                    //{"isOk":true,"gfyname":"ThreeWordCode","secret":"15alphanumerics","uploadType":"filedrop.gfycat.com"}

                                    var ser = new JavaScriptSerializer();

                                    if (!(ser.DeserializeObject(result) is Dictionary <string, object> thing))
                                    {
                                        throw new Exception("It was not possible to get the gfycat name: " + res);
                                    }

                                    var name = thing["gfyname"] as string;

                                    using (var content = new MultipartFormDataContent())
                                    {
                                        content.Add(new StringContent(name), "key");
                                        content.Add(new ByteArrayContent(File.ReadAllBytes(param.Filename)), "file", name);

                                        using (var res2 = client.PostAsync("https://filedrop.gfycat.com", content).Result)
                                        {
                                            if (!res2.IsSuccessStatusCode)
                                            {
                                                throw new Exception("It was not possible to get the gfycat upload result: " + res2);
                                            }

                                            //{"task": "complete", "gfyname": "ThreeWordCode"}
                                            //{"progress": "0.03", "task": "encoding", "time": 10}

                                            //If the task is not yet completed, try waiting.

                                            var input2 = "";

                                            while (!input2.Contains("complete"))
                                            {
                                                using (var res3 = client.GetAsync("https://api.gfycat.com/v1/gfycats/fetch/status/" + name).Result)
                                                {
                                                    input2 = res3.Content.ReadAsStringAsync().Result;

                                                    if (!res3.IsSuccessStatusCode)
                                                    {
                                                        throw new Exception("It was not possible to get the gfycat upload status: " + res3);
                                                    }
                                                }

                                                if (!input2.Contains("complete"))
                                                {
                                                    Thread.Sleep(1000);
                                                }
                                            }

                                            if (res2.IsSuccessStatusCode)
                                            {
                                                InternalSetUpload(id, true, "https://gfycat.com/" + name);
                                            }
                                        }
                                    }
                                }
                            }
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        LogWriter.Log(e, "It was not possible to run the post encoding command.");
                        InternalSetUpload(id, false, null, null, e);
                    }
                }

                #endregion

                #region Copy to clipboard

                if (param.CopyToClipboard && File.Exists(param.Filename))
                {
                    Dispatcher.Invoke(() =>
                    {
                        try
                        {
                            var data = new DataObject();

                            switch (param.CopyType)
                            {
                            case CopyType.File:
                                if (param.Type != Export.Video)
                                {
                                    data.SetImage(param.Filename.SourceFrom());
                                }

                                data.SetText(param.Filename, TextDataFormat.Text);
                                data.SetFileDropList(new StringCollection {
                                    param.Filename
                                });
                                break;

                            case CopyType.FolderPath:
                                data.SetText(Path.GetDirectoryName(param.Filename) ?? param.Filename, TextDataFormat.Text);
                                break;

                            case CopyType.Link:
                                data.SetText(param.Filename, TextDataFormat.Text);     //TODO: Link.
                                break;

                            default:
                                data.SetText(param.Filename, TextDataFormat.Text);
                                break;
                            }

                            Clipboard.SetDataObject(data, true);
                            InternalSetCopy(id, true);
                        }
                        catch (Exception e)
                        {
                            LogWriter.Log(e, "It was not possible to copy the file.");
                            InternalSetCopy(id, false, e);
                        }
                    });
                }

                #endregion

                #region Execute commands

                if (param.ExecuteCommands && !string.IsNullOrWhiteSpace(param.PostCommands))
                {
                    InternalUpdate(id, "Encoder.Executing", true, true);

                    var command = param.PostCommands.Replace("{p}", "\"" + param.Filename + "\"").Replace("{f}", "\"" + Path.GetDirectoryName(param.Filename) + "\"");
                    var output  = "";

                    try
                    {
                        foreach (var com in command.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            var procStartInfo = new ProcessStartInfo("cmd", "/c " + com)
                            {
                                RedirectStandardOutput = true,
                                RedirectStandardError  = true,
                                UseShellExecute        = false,
                                CreateNoWindow         = true
                            };

                            using (var process = new Process())
                            {
                                process.StartInfo = procStartInfo;
                                process.Start();

                                var message = process.StandardOutput.ReadToEnd();
                                var error   = process.StandardError.ReadToEnd();

                                if (!string.IsNullOrWhiteSpace(message))
                                {
                                    output += message + Environment.NewLine;
                                }

                                if (!string.IsNullOrWhiteSpace(message))
                                {
                                    output += message + Environment.NewLine;
                                }

                                if (!string.IsNullOrWhiteSpace(error))
                                {
                                    throw new Exception(error);
                                }

                                process.WaitForExit(1000);
                            }
                        }

                        InternalSetCommand(id, true, command, output);
                    }
                    catch (Exception e)
                    {
                        LogWriter.Log(e, "It was not possible to run the post encoding command.");
                        InternalSetCommand(id, false, command, output, e);
                    }
                }

                #endregion

                if (!tokenSource.Token.IsCancellationRequested)
                {
                    SetStatus(Status.Completed, id, param.Filename);
                }
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Encode");

                SetStatus(Status.Error, id, null, false, ex);
            }
            finally
            {
                #region Delete Encoder Folder

                try
                {
                    var encoderFolder = Path.GetDirectoryName(listFrames[0].Path);

                    if (!string.IsNullOrEmpty(encoderFolder))
                    {
                        if (Directory.Exists(encoderFolder))
                        {
                            Directory.Delete(encoderFolder, true);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogWriter.Log(ex, "Cleaning the Encode folder");
                }

                #endregion

                GC.Collect();
            }
        }
Esempio n. 28
0
        private async void button5_Click(object sender, EventArgs e)
        {
            try
            {
                switch (_currentGraph)
                {
                case GraphType.MonochromaticRadiationN1:
                    if (_dotPlot)
                    {
                        await CreateOneLineDot(DataController.GetFirstPoints());

                        break;
                    }
                    await CreateOneLine(DataController.GetFirstPoints());

                    break;

                case GraphType.MonochromaticRadiationN2:
                    if (_dotPlot)
                    {
                        await CreateOneLineDot(DataController.GetSecondPoints());

                        break;
                    }
                    await CreateOneLine(DataController.GetSecondPoints());

                    break;

                case GraphType.TwoWaves:
                    if (_dotPlot)
                    {
                        await CreateOneLineDot(DataController.GetThirdPoints());

                        break;
                    }
                    await CreateOneLine(DataController.GetThirdPoints());

                    break;

                case GraphType.WavelengthRange:
                    if (_dotPlot)
                    {
                        await CreateOneLineDot(DataController.GetFourthPoints());

                        break;
                    }
                    await CreateOneLine(DataController.GetFourthPoints());

                    break;

                case GraphType.DependenceRadiusRings:
                    if (_dotPlot)
                    {
                        await CreateTwoLinesDot(
                            DataHandler.LinePointsInRadiusDependence(
                                DataHandler.FindMaxInAllData(DataController.GetFirstPoints()),
                                DataHandler.FindMinInAllData(DataController.GetFirstPoints())),
                            DataHandler.LinePointsInRadiusDependence(
                                DataHandler.FindMaxInAllData(DataController.GetSecondPoints()),
                                DataHandler.FindMinInAllData(DataController.GetSecondPoints())));

                        break;
                    }
                    await CreateTwoLines(
                        DataHandler.LinePointsInRadiusDependence(
                            DataHandler.FindMaxInAllData(DataController.GetFirstPoints()),
                            DataHandler.FindMinInAllData(DataController.GetFirstPoints())),
                        DataHandler.LinePointsInRadiusDependence(
                            DataHandler.FindMaxInAllData(DataController.GetSecondPoints()),
                            DataHandler.FindMinInAllData(DataController.GetSecondPoints())));

                    break;

                case GraphType.VisibilityFunctionTwoWaves:
                    if (textBox1.Text == null)
                    {
                        throw new TextBoxException();
                    }
                    var opticalPathDifference = VisibilityFunctionMethods.OpticalPathDifference(
                        VisibilityFunctionMethods.FindRAverage(
                            DataHandler.FindMaxInAllData(DataController.GetThirdPoints()),
                            DataHandler.FindMinInAllData(DataController.GetThirdPoints())),
                        DataHandler.FindRByN(
                            DataHandler.FindMaxInAllData(DataController.GetThirdPoints()),
                            double.Parse(textBox1.Text)));
                    var vExperimental = VisibilityFunctionMethods.FindVExperimental(
                        DataHandler.FindMaxInAllData(DataController.GetThirdPoints()),
                        DataHandler.FindMinInAllData(DataController.GetThirdPoints()));
                    var vTheoretical = VisibilityFunctionMethods.FindVTheoretical(
                        opticalPathDifference,
                        VisibilityFunctionMethods.FindL(opticalPathDifference),
                        VisibilityFunctionMethods.FindErrorL(
                            opticalPathDifference,
                            VisibilityFunctionMethods.FindL(opticalPathDifference)));
                    if (_dotPlot)
                    {
                        await CreateTwoLinesDot(
                            VisibilityFunctionMethods.CreatePointForVisibility(
                                opticalPathDifference,
                                vExperimental),
                            VisibilityFunctionMethods.CreatePointForVisibility(
                                opticalPathDifference,
                                vTheoretical));

                        break;
                    }
                    await CreateTwoLines(
                        VisibilityFunctionMethods.CreatePointForVisibility(
                            opticalPathDifference,
                            vExperimental),
                        VisibilityFunctionMethods.CreatePointForVisibility(
                            opticalPathDifference,
                            vTheoretical)
                        );

                    break;

                case GraphType.VisibilityFunctionWavelengthRange:
                    if (textBox1.Text == null)
                    {
                        throw new TextBoxException();
                    }
                    opticalPathDifference = VisibilityFunctionMethods.OpticalPathDifference(
                        VisibilityFunctionMethods.FindRAverage(
                            DataHandler.FindMaxInAllData(DataController.GetFourthPoints()),
                            DataHandler.FindMinInAllData(DataController.GetFourthPoints())),
                        DataHandler.FindRByN(
                            DataHandler.FindMaxInAllData(DataController.GetFourthPoints()),
                            double.Parse(textBox1.Text)));
                    vExperimental = VisibilityFunctionMethods.FindVExperimental(
                        DataHandler.FindMaxInAllData(DataController.GetFourthPoints()),
                        DataHandler.FindMinInAllData(DataController.GetFourthPoints()));
                    vTheoretical = VisibilityFunctionMethods.FindVTheoretical(
                        opticalPathDifference,
                        VisibilityFunctionMethods.FindL(opticalPathDifference),
                        VisibilityFunctionMethods.FindErrorL(
                            opticalPathDifference,
                            VisibilityFunctionMethods.FindL(opticalPathDifference)));
                    if (_dotPlot)
                    {
                        await CreateTwoLinesDot(
                            VisibilityFunctionMethods.CreatePointForVisibility(
                                opticalPathDifference,
                                vExperimental),
                            VisibilityFunctionMethods.CreatePointForVisibility(
                                opticalPathDifference,
                                vTheoretical));

                        break;
                    }
                    await CreateTwoLines(
                        VisibilityFunctionMethods.CreatePointForVisibility(
                            opticalPathDifference,
                            vExperimental),
                        VisibilityFunctionMethods.CreatePointForVisibility(
                            opticalPathDifference,
                            vTheoretical)
                        );

                    break;

                case GraphType.VisibilityFunctionPicture:
                    if (textBox1.Text == null)
                    {
                        throw new TextBoxException();
                    }

                    if (ImageMethods.FindCircleNum() == 0 && ImageMethods.FindCircleCenterX() == 0 && ImageMethods.FindCircleCenterY() == 0)
                    {
                        MessageBox.Show(@"Попробуйте другую картинку. На этой не получается найти полное кольцо");
                        break;
                    }
                    ImageMethods.DrawContours();
                    _picturesForm.GetCenter(ImageMethods.FindCircleCenterX(), ImageMethods.FindCircleCenterY());
                    _picturesForm.GetOutputPicture(DataController.GetImageWithContour());

                    var points        = ImageMethods.FindPointsForVisibilityFunction();
                    var approximation = ImageMethods.ApproximationPoints(points);

                    opticalPathDifference = VisibilityFunctionMethods.OpticalPathDifference(
                        VisibilityFunctionMethods.FindRAverage(
                            DataHandler.FindMaxInAllData(approximation),
                            DataHandler.FindMinInAllData(approximation)),
                        DataHandler.FindRByN(
                            DataHandler.FindMaxInAllData(approximation),
                            double.Parse(textBox1.Text)));
                    vExperimental = VisibilityFunctionMethods.FindVExperimental(
                        DataHandler.FindMaxInAllData(approximation),
                        DataHandler.FindMinInAllData(approximation));
                    if (_dotPlot)
                    {
                        await CreateOneLineDot(DataHandler.SortPointsByX(VisibilityFunctionMethods.CreatePointForVisibility(
                                                                             opticalPathDifference,
                                                                             vExperimental)));

                        break;
                    }
                    await CreateOneLine(DataHandler.SortPointsByX(VisibilityFunctionMethods.CreatePointForVisibility(
                                                                      opticalPathDifference,
                                                                      vExperimental)));

                    break;

                case GraphType.PictureGraphic:
                    if (ImageMethods.FindCircleNum() == 0 && ImageMethods.FindCircleCenterX() == 0 && ImageMethods.FindCircleCenterY() == 0)
                    {
                        MessageBox.Show(@"Попробуйте другую картинку. На этой не получается найти полное кольцо");
                        break;
                    }
                    ImageMethods.DrawContours();
                    _picturesForm.GetCenter(ImageMethods.FindCircleCenterX(), ImageMethods.FindCircleCenterY());
                    _picturesForm.GetOutputPicture(DataController.GetImageWithContour());

                    points        = ImageMethods.FindPointsForVisibilityFunction();
                    approximation = ImageMethods.ApproximationPoints(points);
                    if (_dotPlot)
                    {
                        await CreateTwoLinesDot(points, approximation);

                        break;
                    }
                    //await CreateOneLine(points);
                    await CreateTwoLines(points, approximation);

                    //await CreateOneLine(approximation);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }