using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;

namespace ImageCatalog
{
    // Imports System.Threading

    public class CreaImmagineSeparateThread
    {
        /* TODO ERROR: Skipped RegionDirectiveTrivia */
        private string _DirectorySorgente;
        private string _DirectoryDestinazione;
        private int _DimVert;
        private int _MargVert;
        private DirectoryInfo _SourceDir;
        private DirectoryInfo _DestDirStart;
        private int _DimStandard;
        private int _DimStandardMiniatura;
        private bool _NomeData;
        private bool _TestoNome;
        private bool _UsaOrarioMiniatura;
        private bool _UsaOrarioTestoApplicare;
        private bool _UsaTempoGaraTestoApplicare;
        private string _TestoFirmaStart;
        private string _TestoFirmaStartV;
        private DateTime _DataPartenza;
        private string _TestoOrario;
        private bool _UsaRotazioneAutomatica;
        private bool _UsaForzaJpg;
        private int _LarghezzaSmall;
        private int _AltezzaSmall;
        private bool _CreaMiniature;
        private bool _AggiungiScritteMiniature;
        private bool _AggTempoGaraMin;
        private bool _AggNumTempMin;
        private string _NomeFileChild;
        private string _Suffisso;
        private string _Codice;
        private int _Trasparenza;
        private string _IlFont;
        private bool _Grassetto;
        private string _Posizione;
        private string _Allineamento;
        private int _Margine;
        private int _LogoAltezza;
        private int _LogoLarghezza;
        private int _FontColoreR;
        private int _FontColoreG;
        private int _FontColoreB;
        private Color _fontColoreRGB;
        private bool _LogoAggiungi;
        private string _LogoNomeFile;
        private string _LogoTrasparenza;
        private string _LogoMargine;
        private string _LogoPosizioneH;
        private string _LogoPosizioneV;
        private bool _FotoGrandeDimOrigina;
        private int _AltezzaBig;
        private int _LarghezzaBig;
        private DirectoryInfo _DestDir;
        private int _DimMin;
        private bool _TestoMin;
        private bool _SecretDefault;
        private bool _SecretBig;
        private bool _SecretSmall;
        private string _SecretPathSmall;
        private string _SecretPathBig;
        private long _jpegQuality;
        private long _jpegQualityMin;
        private bool FotoRuotaADestra = false;
        private bool FotoRuotaASinistra = false;
        private string TempMinText = "";
        // Private crFont1 As Font


        /* TODO ERROR: Skipped EndRegionDirectiveTrivia */
        private void ProcA(ref Image g, ref DateTime DataFoto, ref string TestoFirma, ref string TestoFirmaV, ref string TestoFirmaPiccola, ref DateTime DataPartenzaI)
        {
            if (g.PropertyIdList.Length > 0) // ci sono dati exif
            {
                var DatiExif = new ExifReader((Bitmap)g);
                DataFoto = DatiExif.DateTimeOriginal;
                TestoFirma = _TestoFirmaStart;
                TestoFirmaV = _TestoFirmaStartV;
                if (DataFoto.Year != 1)
                {
                    TestoFirmaPiccola = DataFoto.ToShortTimeString();
                    if (_UsaOrarioTestoApplicare == true)
                    {
                        TestoFirma += " " + DataFoto.ToShortDateString() + " " + DataFoto.ToLongTimeString();
                        TestoFirmaV += " " + DataFoto.ToShortDateString() + " " + DataFoto.ToLongTimeString();
                    }

                    if (_UsaTempoGaraTestoApplicare == true)
                    {
                        var Orario = new TimeSpan(DateAndTime.DateDiff(DateInterval.Second, DataPartenzaI, DataFoto) * 10000000L);
                        TestoFirma += " " + _TestoOrario + Orario.Hours.ToString("00") + ":" + Orario.Minutes.ToString("00") + ":" + Orario.Seconds.ToString("00");
                        TestoFirmaV += " " + _TestoOrario + Orario.Hours.ToString("00") + ":" + Orario.Minutes.ToString("00") + ":" + Orario.Seconds.ToString("00");
                    }
                }
            }
        }

        private void Rotation(ref Image g)
        {
            FotoRuotaADestra = false;
            FotoRuotaASinistra = false;
            if (_UsaRotazioneAutomatica == true)
            {
                if (g.PropertyIdList.Length > 0) // ci sono dati exif
                {
                    var DatiExif = new ExifReader((Bitmap)g);
                    switch (DatiExif.Orientation)
                    {
                        case ExifReader.Orientations.BottomLeft:
                            {
                                break;
                            }

                        case ExifReader.Orientations.BottomRight:
                            {
                                break;
                            }

                        case ExifReader.Orientations.LeftTop:
                            {
                                break;
                            }

                        case ExifReader.Orientations.LftBottom:
                            {
                                FotoRuotaASinistra = true;
                                break;
                            }

                        case ExifReader.Orientations.RightBottom:
                            {
                                break;
                            }

                        case ExifReader.Orientations.RightTop:
                            {
                                break;
                            }

                        case ExifReader.Orientations.TopLeft:
                            {
                                break;
                            }

                        case ExifReader.Orientations.TopRight:
                            {
                                break;
                            }
                    }
                }
            }

            if (FotoRuotaASinistra == true)
            {
                g.RotateFlip(RotateFlipType.Rotate270FlipNone);
            }

            if (FotoRuotaADestra == true)
            {
                g.RotateFlip(RotateFlipType.Rotate90FlipNone);
            }
        }

        public void CreaImmagineThread(string Info)
        {
            string TestoFirma = "";
            string TestoFirmaV = "";
            int AlphaScelta = Conversions.ToInteger(255 * (100 - _Trasparenza) / 100d);
            int DimensioneStandard;
            int DimensioneStandardMiniatura;
            var DataFoto = default(DateTime);
            var DataPartenzaI = _DataPartenza;
            if (_TestoOrario.Length > 0)
            {
                _TestoOrario += " ";
            }

            string TestoFirmaPiccola = "";
            int FileConta = 0;
            int ContaFileXDir = 0;
            int ContaDirXDir = 0;
            string TestoTemp = "";
            int ContaTemp = 0;
            DimensioneStandard = _DimStandard;
            DimensioneStandardMiniatura = _DimStandardMiniatura;
            var g = Image.FromFile(Path.Combine(_SourceDir.FullName, _NomeFileChild));
            // dati extra in fondo
            if (_UsaOrarioTestoApplicare | _UsaTempoGaraTestoApplicare | _UsaOrarioMiniatura | _TestoMin | _AggTempoGaraMin | _AggNumTempMin)
            {
                ProcA(ref g, ref DataFoto, ref TestoFirma, ref TestoFirmaV, ref TestoFirmaPiccola, ref DataPartenzaI);
            }

            // If g.PropertyIdList.Length > 0 Then ' ci sono dati exif
            // Dim DatiExif As New ExifReader(CType(g, Bitmap))
            // DataFoto = DatiExif.DateTimeOriginal
            // TestoFirma = _TestoFirmaStart
            // TestoFirmaV = _TestoFirmaStartV

            // If DataFoto.Year <> 1 Then
            // TestoFirmaPiccola = DataFoto.ToShortTimeString
            // If _UsaOrarioTestoApplicare = True Then
            // TestoFirma &= " - " & DataFoto.ToShortDateString & " " & DataFoto.ToLongTimeString
            // TestoFirmaV &= " - " & DataFoto.ToShortDateString & " " & DataFoto.ToLongTimeString
            // End If
            // If _UsaTempoGaraTestoApplicare = True Then
            // Dim Orario As TimeSpan = New TimeSpan(DateDiff(DateInterval.Second, DataPartenzaI, DataFoto) * 10000000)
            // TestoFirma &= " - " & _TestoOrario & Orario.Hours.ToString("00") & ":" & Orario.Minutes.ToString("00") & ":" & Orario.Seconds.ToString("00")
            // TestoFirmaV &= " - " & _TestoOrario & Orario.Hours.ToString("00") & ":" & Orario.Minutes.ToString("00") & ":" & Orario.Seconds.ToString("00")
            // End If
            // End If

            // End If

            else
            {
                TestoFirma = _TestoFirmaStart;
                TestoFirmaV = _TestoFirmaStartV;
            }

            Rotation(ref g);

            // Dim FotoRuotaADestra As Boolean = False
            // Dim FotoRuotaASinistra As Boolean = False

            // If _UsaRotazioneAutomatica = True Then
            // If g.PropertyIdList.Length > 0 Then ' ci sono dati exif
            // Dim DatiExif As New ExifReader(CType(g, Bitmap))

            // Select Case DatiExif.Orientation
            // Case ExifReader.Orientations.BottomLeft

            // Case ExifReader.Orientations.BottomRight

            // Case ExifReader.Orientations.LeftTop

            // Case ExifReader.Orientations.LftBottom
            // FotoRuotaASinistra = True
            // Case ExifReader.Orientations.RightBottom

            // Case ExifReader.Orientations.RightTop

            // Case ExifReader.Orientations.TopLeft

            // Case ExifReader.Orientations.TopRight

            // End Select
            // End If
            // End If

            // If FotoRuotaASinistra = True Then
            // g.RotateFlip(RotateFlipType.Rotate270FlipNone)
            // End If
            // If FotoRuotaADestra = True Then
            // g.RotateFlip(RotateFlipType.Rotate90FlipNone)
            // End If

            var thisFormat = g.RawFormat;
            if (_UsaForzaJpg == true)
            {
                thisFormat = ImageFormat.Jpeg;
            }

            var thumbSizeSmall = new Size();
            var thumbSizeBig = new Size();
            string NomeFileSmall = "";
            string NomeFileBig2 = "";
            string NomeFileBig = "";
            if (g.Width > g.Height)
            {
                thumbSizeSmall = NewthumbSize(g.Width, g.Height, LarghezzaSmall, "Larghezza");
                var SizeOrig = new Size(g.Width, g.Height);
                thumbSizeBig = SizeOrig;
            }
            else
            {
                thumbSizeSmall = NewthumbSize(g.Width, g.Height, AltezzaSmall, "Altezza");
                var SizeOrig = new Size(g.Width, g.Height);
                thumbSizeBig = SizeOrig;
            }

            NomeFileSmall = Suffisso + _NomeFileChild;
            NomeFileBig = _NomeFileChild;
            var imgOutputBig = new Bitmap(g, thumbSizeBig.Width, thumbSizeBig.Height);
            imgOutputBig.SetResolution(g.HorizontalResolution, g.VerticalResolution);
            if (_TestoMin)
            {
                TestoFirmaPiccola = NomeFileBig;
            }
            else if (_AggNumTempMin)
            {
                TestoFirmaPiccola = NomeFileBig + " ";
            }

            var yPosFromBottom4 = default(float);
            Font crFont1 = null;
            Font crFont2 = null;
            var crSize1 = new SizeF();
            var crSize2 = new SizeF();
            if (_CreaMiniature == true)
            {
                if (_AggiungiScritteMiniature == false)
                {
                    if ((_DirectorySorgente.ToUpper() ?? "") == (_DirectoryDestinazione.ToUpper() ?? ""))
                    {
                        NomeFileSmall = NomeFileSmall.Substring(0, NomeFileSmall.Length - 4) + Codice + NomeFileSmall.Substring(NomeFileSmall.Length - 4);
                    }

                    if (_UsaOrarioMiniatura | _TestoMin | _AggTempoGaraMin | _AggNumTempMin)
                    {
                        if (TestoFirmaPiccola.Length > 0)
                        {
                            Bitmap imgOutputSmall;
                            imgOutputSmall = (Bitmap)imgOutputBig.Clone();
                            Graphics grPhoto1;
                            grPhoto1 = Graphics.FromImage(imgOutputSmall);
                            grPhoto1.SmoothingMode = SmoothingMode.AntiAlias;

                            // erano qui

                            int LarghezzaStandard1;
                            // quick fix
                            DimensioneStandardMiniatura = 50;
                            if (_Grassetto == true)
                            {
                                crFont1 = new Font(IlFont, DimensioneStandardMiniatura, FontStyle.Bold);
                                crFont2 = new Font(IlFont, DimensioneStandard, FontStyle.Bold);
                            }
                            else
                            {
                                crFont1 = new Font(_IlFont, DimensioneStandardMiniatura);
                                crFont2 = new Font(IlFont, DimensioneStandard);
                            }

                            crSize1 = grPhoto1.MeasureString(TestoFirmaPiccola, crFont1);
                            crSize2 = grPhoto1.MeasureString(TestoFirma, crFont1);
                            LarghezzaStandard1 = Conversions.ToInteger(crSize1.Width);
                            if (crSize1.Width > Conversions.ToSingle(g.Width))
                            {
                                int Conta = DimensioneStandardMiniatura;
                                do
                                {
                                    if (Conta > 20)
                                    {
                                        Conta -= 5;
                                    }
                                    else
                                    {
                                        Conta -= 1;
                                    }

                                    if (_Grassetto == true)
                                    {
                                        crFont1 = new Font(_IlFont, Conta, FontStyle.Bold);
                                    }
                                    else
                                    {
                                        crFont1 = new Font(_IlFont, Conta);
                                    }

                                    crSize1 = grPhoto1.MeasureString(TestoFirmaPiccola, crFont1);
                                    if (crSize1.Width < Conversions.ToSingle(g.Width))
                                    {
                                        LarghezzaStandard1 = Conversions.ToInteger(crSize1.Width);
                                        break;
                                    }

                                    if (Conta <= 5)
                                        break;
                                }
                                while (true);
                                DimensioneStandardMiniatura = Conta;
                            }

                            var yPosFromBottom1 = default(float);
                            switch (_Posizione.ToUpper() ?? "")
                            {
                                case "ALTO":
                                    {
                                        yPosFromBottom1 = _Margine;
                                        yPosFromBottom4 = _MargVert;
                                        break;
                                    }

                                case "BASSO":
                                    {
                                        // yPosFromBottom = (g.Height - _Margine - DimensioneStandard)
                                        // yPosFromBottom1 = CType((g.Height - crFont1.Height - (g.Height * _Margine / 100) - (crFont1.Height * 0.3)), Single)
                                        yPosFromBottom1 = Conversions.ToSingle(g.Height - crSize1.Height - g.Height * _Margine / 100d);
                                        yPosFromBottom4 = Conversions.ToSingle(g.Height - crSize1.Height - g.Height * _MargVert / 100d);
                                        break;
                                    }
                            }

                            var xCenterOfImg1 = default(float);
                            var StrFormat1 = new StringFormat();
                            switch (_Allineamento.ToUpper() ?? "")
                            {
                                case "SINISTRA":
                                    {
                                        xCenterOfImg1 = Conversions.ToSingle(_Margine + LarghezzaStandard1 / 2d);
                                        if (LarghezzaStandard1 / 2d > g.Width / 2d - _Margine)
                                        {
                                            xCenterOfImg1 = Conversions.ToSingle(g.Width / 2d);
                                        }

                                        break;
                                    }

                                case "CENTRO":
                                    {
                                        xCenterOfImg1 = Conversions.ToSingle(g.Width / 2d);
                                        break;
                                    }

                                case "DESTRA":
                                    {
                                        xCenterOfImg1 = Conversions.ToSingle(g.Width - _Margine - LarghezzaStandard1 / 2d);
                                        if (LarghezzaStandard1 / 2d > g.Width / 2d - _Margine)
                                        {
                                            xCenterOfImg1 = Conversions.ToSingle(g.Width / 2d);
                                        }

                                        break;
                                    }
                            }

                            StrFormat1.Alignment = StringAlignment.Center;
                            var semiTransBrush21 = new SolidBrush(Color.FromArgb(AlphaScelta, 0, 0, 0));
                            var semiTransBrush1 = new SolidBrush(Color.FromArgb(AlphaScelta, _FontColoreR, _FontColoreG, _FontColoreB));
                            // quick fix
                            DimensioneStandardMiniatura = _DimMin;
                            if (_Grassetto == true)
                            {
                                crFont1 = new Font(_IlFont, DimensioneStandardMiniatura, FontStyle.Bold);
                            }
                            else
                            {
                                crFont1 = new Font(_IlFont, DimensioneStandardMiniatura);
                            }
                            // asdgadfhdfhjgfsjgfjygfdhsdafa
                            if (_TestoMin)
                            {
                                grPhoto1.DrawString(NomeFileBig, crFont1, semiTransBrush21, new PointF(xCenterOfImg1 + 1f, yPosFromBottom1 + 1f), StrFormat1);
                                grPhoto1.DrawString(NomeFileBig, crFont1, semiTransBrush1, new PointF(xCenterOfImg1, yPosFromBottom1), StrFormat1);
                            }
                            else if (_AggTempoGaraMin & _UsaTempoGaraTestoApplicare)
                            {
                                var Orario = new TimeSpan(DateAndTime.DateDiff(DateInterval.Second, DataPartenzaI, DataFoto) * 10000000L);
                                string tempstr = "";
                                tempstr += ControlChars.CrLf + _TestoOrario + Orario.Hours.ToString("00") + ":" + Orario.Minutes.ToString("00") + ":" + Orario.Seconds.ToString("00");
                                grPhoto1.DrawString(tempstr, crFont1, semiTransBrush21, new PointF(xCenterOfImg1 + 1f, yPosFromBottom1 + 1f), StrFormat1);
                                grPhoto1.DrawString(tempstr, crFont1, semiTransBrush1, new PointF(xCenterOfImg1, yPosFromBottom1), StrFormat1);
                            }
                            else if (_AggNumTempMin)
                            {
                                var Orario = new TimeSpan(DateAndTime.DateDiff(DateInterval.Second, DataPartenzaI, DataFoto) * 10000000L);
                                string tempstr = "";
                                tempstr += NomeFileBig;
                                tempstr += ControlChars.CrLf + _TestoOrario + Orario.Hours.ToString("00") + ":" + Orario.Minutes.ToString("00") + ":" + Orario.Seconds.ToString("00");
                                grPhoto1.DrawString(tempstr, crFont1, semiTransBrush21, new PointF(xCenterOfImg1 + 1f, yPosFromBottom1 + 1f), StrFormat1);
                                grPhoto1.DrawString(tempstr, crFont1, semiTransBrush1, new PointF(xCenterOfImg1, yPosFromBottom1), StrFormat1);
                            }
                            else
                            {
                                grPhoto1.DrawString(TestoFirmaPiccola, crFont1, semiTransBrush21, new PointF(xCenterOfImg1 + 1f, yPosFromBottom1 + 1f), StrFormat1);
                                grPhoto1.DrawString(TestoFirmaPiccola, crFont1, semiTransBrush1, new PointF(xCenterOfImg1, yPosFromBottom1), StrFormat1);
                            }

                            imgOutputSmall.Save(Path.Combine(_DestDir.FullName, "Temp_" + NomeFileSmall), thisFormat);
                            var g2 = Image.FromFile(Path.Combine(_DestDir.FullName, "Temp_" + NomeFileSmall));
                            var imgOutputSmall2 = new Bitmap(g2, thumbSizeSmall.Width, thumbSizeSmall.Height);
                            imgOutputSmall2.Save(Path.Combine(_DestDir.FullName, NomeFileSmall), thisFormat);
                            imgOutputSmall2.Dispose();
                            imgOutputSmall.Dispose();
                            g2.Dispose();
                            FileSystem.Kill(Path.Combine(_DestDir.FullName, "Temp_" + NomeFileSmall));
                        }
                        else
                        {
                            var imgOutputSmall = new Bitmap(g, thumbSizeSmall.Width, thumbSizeSmall.Height);
                            imgOutputSmall.Save(Path.Combine(_DestDir.FullName, NomeFileSmall), thisFormat);
                            imgOutputSmall.Dispose();
                        }
                    }
                    else
                    {
                        var imgOutputSmall = new Bitmap(g, thumbSizeSmall.Width, thumbSizeSmall.Height);
                        imgOutputSmall.Save(Path.Combine(_DestDir.FullName, NomeFileSmall), thisFormat);
                        imgOutputSmall.Dispose();
                    }
                }
            }

            Graphics grPhoto;
            grPhoto = Graphics.FromImage(imgOutputBig);
            grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
            Font crFont = null;
            var crSize = new SizeF();
            int LarghezzaStandard;
            if (_Grassetto == true)
            {
                crFont = new Font(_IlFont, DimensioneStandard, FontStyle.Bold);
            }
            else
            {
                crFont = new Font(_IlFont, DimensioneStandard);
            }

            crSize = grPhoto.MeasureString(TestoFirma, crFont);
            LarghezzaStandard = Conversions.ToInteger(crSize.Width);
            if (crSize.Width > Conversions.ToSingle(g.Width))
            {
                int Conta = DimensioneStandard;
                do
                {
                    if (Conta > 20)
                    {
                        Conta -= 5;
                    }
                    else
                    {
                        Conta -= 1;
                    }

                    if (_Grassetto == true)
                    {
                        crFont = new Font(_IlFont, Conta, FontStyle.Bold);
                    }
                    else
                    {
                        crFont = new Font(_IlFont, Conta);
                    }

                    crSize = grPhoto.MeasureString(TestoFirma, crFont);
                    if (crSize.Width < Conversions.ToSingle(g.Width))
                    {
                        LarghezzaStandard = Conversions.ToInteger(crSize.Width);
                        break;
                    }

                    if (Conta <= 5)
                        break;
                }
                while (true);
                DimensioneStandard = Conta;
            }

            var yPosFromBottom = default(float);
            var yPosFromBottom3 = default(float);
            switch (_Posizione.ToUpper() ?? "")
            {
                case "ALTO":
                    {
                        yPosFromBottom = _Margine;
                        yPosFromBottom3 = _MargVert;
                        break;
                    }

                case "BASSO":
                    {
                        // yPosFromBottom = (g.Height - _Margine - DimensioneStandard)
                        // yPosFromBottom = CType((g.Height - DimensioneStandard - (g.Height * _Margine / 100) - (DimensioneStandard * 0.3)), Single)
                        yPosFromBottom = Conversions.ToSingle(g.Height - crSize.Height - g.Height * _Margine / 100d);
                        yPosFromBottom3 = Conversions.ToSingle(g.Height - crSize.Height - g.Height * _MargVert / 100d);
                        break;
                    }
            }

            var xCenterOfImg = default(float);
            float xCenterOfImg3;
            var StrFormat = new StringFormat();
            switch (_Allineamento.ToUpper() ?? "")
            {
                case "SINISTRA":
                    {
                        xCenterOfImg = Conversions.ToSingle(_Margine + LarghezzaStandard / 2d);
                        xCenterOfImg3 = Conversions.ToSingle(_MargVert + LarghezzaStandard / 2d);
                        if (LarghezzaStandard / 2d > g.Width / 2d - _Margine)
                        {
                            xCenterOfImg = Conversions.ToSingle(g.Width / 2d);
                        }

                        if (LarghezzaStandard / 2d > g.Width / 2d - _MargVert)
                        {
                            xCenterOfImg3 = Conversions.ToSingle(g.Width / 2d);
                        }

                        break;
                    }

                case "CENTRO":
                    {
                        xCenterOfImg = Conversions.ToSingle(g.Width / 2d);
                        break;
                    }

                case "DESTRA":
                    {
                        xCenterOfImg = Conversions.ToSingle(g.Width - _Margine - LarghezzaStandard / 2d);
                        xCenterOfImg3 = Conversions.ToSingle(g.Width - _MargVert - LarghezzaStandard / 2d);
                        if (LarghezzaStandard / 2d > g.Width / 2d - _Margine)
                        {
                            xCenterOfImg = Conversions.ToSingle(g.Width / 2d);
                        }

                        if (LarghezzaStandard / 2d > g.Width / 2d - _MargVert)
                        {
                            xCenterOfImg3 = Conversions.ToSingle(g.Width / 2d);
                        }

                        break;
                    }
            }

            StrFormat.Alignment = StringAlignment.Center;
            var semiTransBrush2 = new SolidBrush(Color.FromArgb(AlphaScelta, 0, 0, 0));
            var semiTransBrush = new SolidBrush(Color.FromArgb(AlphaScelta, _FontColoreR, _FontColoreG, _FontColoreB));
            if (FotoRuotaADestra | FotoRuotaASinistra)
            {
                if (_Grassetto == true)
                {
                    crFont = new Font(_IlFont, DimVert, FontStyle.Bold);
                }
                else
                {
                    crFont = new Font(_IlFont, DimVert);
                }
            }
            else if (_Grassetto == true)
            {
                crFont = new Font(_IlFont, DimensioneStandard, FontStyle.Bold);
            }
            else
            {
                crFont = new Font(_IlFont, DimensioneStandard);
            }

            aggiungiTesto(g, DataFoto, grPhoto, NomeFileBig, crFont, semiTransBrush, semiTransBrush2, xCenterOfImg, yPosFromBottom, StrFormat, TestoFirmaV, yPosFromBottom3, yPosFromBottom4, TestoFirma, NomeFileBig2);
            aggiungiLogo(imgOutputBig);
            salvaFoto(imgOutputBig, thumbSizeBig, NomeFileBig, NomeFileSmall, thumbSizeSmall);
            g.Dispose();
            grPhoto.Dispose();
            GC.Collect();
        }

        private void aggiungiTesto(Image g, DateTime DataFoto, Graphics grPhoto, string NomeFileBig, Font crFont, SolidBrush semiTransBrush, SolidBrush semiTransBrush2, float xCenterOfImg, float yPosFromBottom, StringFormat StrFormat, string TestoFirmav, float yPosFromBottom3, float yPosFromBottom4, string TestoFirma, string NomeFileBig2)
        {
            // qui scrive il testo (nomefilebig)
            if (_TestoNome)
            {
                if (NomeData & g.PropertyIdList.Length > 0)
                {
                    var DatiExif = new ExifReader((Bitmap)g);
                    DataFoto = DatiExif.DateTimeOriginal;
                    grPhoto.DrawString(NomeFileBig + " " + DataFoto.ToShortDateString(), crFont, semiTransBrush2, new PointF(xCenterOfImg + 1f, yPosFromBottom + 1f), StrFormat);
                    grPhoto.DrawString(NomeFileBig + " " + DataFoto.ToShortDateString(), crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom), StrFormat);
                }
                else
                {
                    grPhoto.DrawString(NomeFileBig, crFont, semiTransBrush2, new PointF(xCenterOfImg + 1f, yPosFromBottom + 1f), StrFormat);
                    grPhoto.DrawString(NomeFileBig, crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom), StrFormat);
                }
            }

            if (_TestoNome == false)
            {
                if (FotoRuotaADestra | FotoRuotaASinistra)
                {
                    if (_TestoMin == false)
                    {
                        grPhoto.DrawString(TestoFirmav, crFont, semiTransBrush2, new PointF(xCenterOfImg + 1f, yPosFromBottom3 + 1f), StrFormat);
                        grPhoto.DrawString(TestoFirmav, crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom3), StrFormat);
                    }

                    if (_TestoMin == true)
                    {
                        grPhoto.DrawString(TestoFirmav, crFont, semiTransBrush2, new PointF(xCenterOfImg + 1f, yPosFromBottom4 + 1f), StrFormat);
                        grPhoto.DrawString(TestoFirmav, crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom4), StrFormat);
                    }
                }
                else
                {
                    grPhoto.DrawString(TestoFirma, crFont, semiTransBrush2, new PointF(xCenterOfImg + 1f, yPosFromBottom + 1f), StrFormat);
                    grPhoto.DrawString(TestoFirma, crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom), StrFormat);
                }
            }

            if ((_DirectorySorgente.ToUpper() ?? "") == (_DirectoryDestinazione.ToUpper() ?? ""))
            {
                NomeFileBig2 = NomeFileBig;
                NomeFileBig = NomeFileBig.Substring(0, NomeFileBig.Length - 4) + Codice + NomeFileBig.Substring(NomeFileBig.Length - 4);
            }
        }

        private void aggiungiLogo(Bitmap imgOutputBig)
        {
            // imgOutputBig
            if (_LogoAggiungi == true & File.Exists(_LogoNomeFile))
            {
                var ImmagineLogo = Image.FromFile(_LogoNomeFile);
                var LogoColoreTrasparente = Color.White;
                // Dim bmWatermark As Bitmap

                // * Create a Bitmap based on the previously modified photograph Bitmap
                // bmWatermark = New Bitmap(imgOutputBig)
                // bmWatermark.SetResolution(imgOutputBig.HorizontalResolution, imgOutputBig.VerticalResolution)

                // * Load this Bitmap into a new Graphic Object
                var grWatermark = Graphics.FromImage(imgOutputBig);

                // * To achieve a transulcent watermark we will apply (2) color manipulations
                var imageAttributes = new ImageAttributes();

                // * The first step replace the background color with one that is trasparent (Alpha=0, R=0, G=0, B=0)
                var colorMap = new ColorMap();

                // * background this will be the color we search for and replace with transparency
                colorMap.OldColor = LogoColoreTrasparente;
                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                var remapTable = new[] { colorMap };
                imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                // * The second color manipulation is used to change the opacity by setting the 3rd row and 3rd column to 0.3f
                var colorMatrixElements = new[] { new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, Conversions.ToSingle(_LogoTrasparenza) / 100f, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } };
                var wmColorMatrix = new ColorMatrix(colorMatrixElements);
                imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                int FotoLogoH = _LogoAltezza;
                int FotoLogoW = _LogoLarghezza;
                double FattoreAlt = ImmagineLogo.Height / (double)FotoLogoH;
                double FattoreLarg = ImmagineLogo.Width / (double)FotoLogoW;
                Size NuovaSize;
                if (FattoreLarg > FattoreAlt)
                {
                    NuovaSize = NewthumbSize(ImmagineLogo.Width, ImmagineLogo.Height, FotoLogoW, "Larghezza");
                }
                else
                {
                    NuovaSize = NewthumbSize(ImmagineLogo.Width, ImmagineLogo.Height, FotoLogoH, "Altezza");
                }

                int MargineUsato;
                int MargineL;
                bool InPercentualeL;
                if (_LogoMargine.EndsWith("%") == true)
                {
                    InPercentualeL = true;
                }
                else
                {
                    InPercentualeL = false;
                }

                MargineL = Conversions.ToInteger(Conversion.Val(_LogoMargine));
                if (InPercentualeL == true)
                {
                    MargineUsato = Conversions.ToInteger(imgOutputBig.Height * MargineL / 100d);
                }
                else
                {
                    MargineUsato = MargineL;
                }

                var xPosOfWm = default(int);
                var yPosOfWm = default(int);
                switch (_LogoPosizioneH.ToUpper() ?? "")
                {
                    case "SINISTRA":
                    case "NESSUNA":
                        {
                            xPosOfWm = MargineUsato;
                            break;
                        }

                    case "CENTRO":
                        {
                            xPosOfWm = Conversions.ToInteger((imgOutputBig.Width - NuovaSize.Width) / 2d);
                            break;
                        }

                    case "DESTRA":
                        {
                            xPosOfWm = imgOutputBig.Width - NuovaSize.Width - MargineUsato;
                            break;
                        }
                }

                switch (_LogoPosizioneV.ToUpper() ?? "")
                {
                    case "ALTO":
                    case "NESSUNA":
                        {
                            yPosOfWm = MargineUsato;
                            break;
                        }

                    case "CENTRO":
                        {
                            yPosOfWm = Conversions.ToInteger((imgOutputBig.Height - NuovaSize.Height) / 2d);
                            break;
                        }

                    case "BASSO":
                        {
                            yPosOfWm = imgOutputBig.Height - NuovaSize.Height - MargineUsato;
                            break;
                        }
                }

                grWatermark.DrawImage(ImmagineLogo, new Rectangle(xPosOfWm, yPosOfWm, NuovaSize.Width, NuovaSize.Height), 0, 0, ImmagineLogo.Width, ImmagineLogo.Height, GraphicsUnit.Pixel, imageAttributes);
                grWatermark.Dispose();
            }
        }

        private void salvaFoto(Bitmap imgOutputBig, Size thumbSizeBig, string NomeFileBig, string NomeFileSmall, Size thumbSizeSmall)
        {
            if (_FotoGrandeDimOrigina == false)
            {
                // attenzione non controlla se è png
                // imgOutputBig.Save(Path.Combine(_DestDir.FullName, "Temp_" & NomeFileBig), thisFormat)
                salvaImmagineCustomQuality(imgOutputBig, Path.Combine(_DestDir.FullName, "Temp_" + NomeFileBig), jpegQuality);
                var g2 = Image.FromFile(Path.Combine(_DestDir.FullName, "Temp_" + NomeFileBig));
                if (g2.Width > g2.Height)
                {
                    thumbSizeBig = NewthumbSize(g2.Width, g2.Height, _LarghezzaBig, "Larghezza");
                }
                else
                {
                    thumbSizeBig = NewthumbSize(g2.Width, g2.Height, _AltezzaBig, "Altezza");
                }

                var imgOutputBig2 = new Bitmap(g2, thumbSizeBig.Width, thumbSizeBig.Height);
                // imgOutputBig2.Save(Path.Combine(_DestDir.FullName, NomeFileBig), thisFormat)
                salvaImmagineCustomQuality(imgOutputBig2, Path.Combine(_DestDir.FullName, NomeFileBig), jpegQuality);
                // imgOutputBig2.Dispose()
                // imgOutputBig.Dispose()
                g2.Dispose();
            }
            else
            {
                // imgOutputBig.Save(Path.Combine(_DestDir.FullName, NomeFileBig), thisFormat)
                salvaImmagineCustomQuality(imgOutputBig, Path.Combine(_DestDir.FullName, NomeFileBig), jpegQuality);
                imgOutputBig.Dispose();
            }

            if (_CreaMiniature)
            {
                if (_AggiungiScritteMiniature == true)
                {
                    Image g1;
                    if (_FotoGrandeDimOrigina == false)
                    {
                        g1 = Image.FromFile(Path.Combine(_DestDir.FullName, "Temp_" + NomeFileBig));
                    }
                    else
                    {
                        g1 = Image.FromFile(Path.Combine(_DestDir.FullName, NomeFileBig));
                    }

                    var imgOutputSmall = new Bitmap(g1, thumbSizeSmall.Width, thumbSizeSmall.Height);
                    if ((_DirectorySorgente.ToUpper() ?? "") == (_DirectoryDestinazione.ToUpper() ?? ""))
                    {
                        NomeFileSmall = NomeFileSmall.Substring(0, NomeFileSmall.Length - 4) + Codice + NomeFileSmall.Substring(NomeFileSmall.Length - 4);
                    }
                    // imgOutputSmall.Save(Path.Combine(_DestDir.FullName, NomeFileSmall), thisFormat)
                    salvaImmagineCustomQuality(imgOutputSmall, Path.Combine(_DestDir.FullName, NomeFileSmall), jpegQualityMin);
                    // imgOutputSmall.Dispose()
                    g1.Dispose();
                }
            }

            if (File.Exists(Path.Combine(_DestDir.FullName, "Temp_" + NomeFileBig)) == true)
            {
                FileSystem.Kill(Path.Combine(_DestDir.FullName, "Temp_" + NomeFileBig));
            }
        }

        private void salvaImmagineCustomQuality(Bitmap imageToSave, string nomeFileFinale, long quality)
        {
            var JgpEncoder = GetEncoder(ImageFormat.Jpeg);
            var MyEncoder = Encoder.Quality;
            var MyEncoderParameters = new EncoderParameters(1);
            var MyEncoderParameter = new EncoderParameter(MyEncoder, jpegQuality);
            MyEncoderParameters.Param[0] = MyEncoderParameter;
            imageToSave.Save(nomeFileFinale, JgpEncoder, MyEncoderParameters);
            imageToSave.Dispose();
        }

        private ImageCodecInfo GetEncoder(ImageFormat format)
        {
            var codecs = ImageCodecInfo.GetImageDecoders();
            foreach (var codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }

            return null;
        }






        /// <summary>
    /// Calculate the Size of the New image
    /// </summary>
    /// <param name="currentwidth">Larghezza</param>
    /// <param name="currentheight">Altezza</param>
    /// <param name="MaxPixel"></param>
    /// <param name="TipoSize"></param>
    /// <returns></returns>
    /// <remarks></remarks>
        public Size NewthumbSize(int currentwidth, int currentheight, int MaxPixel, string TipoSize)
        {
            // e  
            // *** Larghezza, Altezza, Auto

            double tempMultiplier;
            if ((TipoSize.ToUpper() ?? "") == ("Larghezza".ToUpper() ?? ""))
            {
                tempMultiplier = MaxPixel / (double)currentwidth;
            }
            else if ((TipoSize.ToUpper() ?? "") == ("Altezza".ToUpper() ?? ""))
            {
                tempMultiplier = MaxPixel / (double)currentheight;
            }
            else if (currentheight > currentwidth) // portrait  
            {
                tempMultiplier = MaxPixel / (double)currentheight;
            }
            else
            {
                tempMultiplier = MaxPixel / (double)currentwidth;
            }

            var NewSize = new Size((int)Math.Round(currentwidth * tempMultiplier), (int)Math.Round(currentheight * tempMultiplier));
            return NewSize;
        }

        public string DirectorySorgente
        {
            get
            {
                return _DirectorySorgente;
            }

            set
            {
                _DirectorySorgente = value;
            }
        }

        public string DirectoryDestinazione
        {
            get
            {
                return _DirectoryDestinazione;
            }

            set
            {
                _DirectoryDestinazione = value;
            }
        }

        public DirectoryInfo SourceDir
        {
            get
            {
                return _SourceDir;
            }

            set
            {
                _SourceDir = value;
            }
        }

        public DirectoryInfo DestDirStart
        {
            get
            {
                return _DestDirStart;
            }

            set
            {
                _DestDirStart = value;
            }
        }

        public string TestoFirmaStart
        {
            get
            {
                return _TestoFirmaStart;
            }

            set
            {
                _TestoFirmaStart = value;
            }
        }

        public string TestoFirmaStartV
        {
            get
            {
                return _TestoFirmaStartV;
            }

            set
            {
                _TestoFirmaStartV = value;
            }
        }

        public DateTime DataPartenza
        {
            get
            {
                return _DataPartenza;
            }

            set
            {
                _DataPartenza = value;
            }
        }

        public string TestoOrario
        {
            get
            {
                return _TestoOrario;
            }

            set
            {
                _TestoOrario = value;
            }
        }

        public int DimStandard
        {
            get
            {
                return _DimStandard;
            }

            set
            {
                _DimStandard = value;
            }
        }

        public int DimStandardMiniatura
        {
            get
            {
                return _DimStandardMiniatura;
            }

            set
            {
                _DimStandardMiniatura = value;
            }
        }

        public bool NomeData
        {
            get
            {
                return _NomeData;
            }

            set
            {
                _NomeData = value;
            }
        }

        public bool TestoNome
        {
            get
            {
                return _TestoNome;
            }

            set
            {
                _TestoNome = value;
            }
        }

        public bool UsaOrarioMiniatura
        {
            get
            {
                return _UsaOrarioMiniatura;
            }

            set
            {
                _UsaOrarioMiniatura = value;
            }
        }

        public bool UsaOrarioTestoApplicare
        {
            get
            {
                return _UsaOrarioTestoApplicare;
            }

            set
            {
                _UsaOrarioTestoApplicare = value;
            }
        }

        public bool UsaTempoGaraTestoApplicare
        {
            get
            {
                return _UsaTempoGaraTestoApplicare;
            }

            set
            {
                _UsaTempoGaraTestoApplicare = value;
            }
        }

        public bool UsaRotazioneAutomatica
        {
            get
            {
                return _UsaRotazioneAutomatica;
            }

            set
            {
                _UsaRotazioneAutomatica = value;
            }
        }

        public bool UsaForzaJpg
        {
            get
            {
                return _UsaForzaJpg;
            }

            set
            {
                _UsaForzaJpg = value;
            }
        }

        public int LarghezzaSmall
        {
            get
            {
                return _LarghezzaSmall;
            }

            set
            {
                _LarghezzaSmall = value;
            }
        }

        public int AltezzaSmall
        {
            get
            {
                return _AltezzaSmall;
            }

            set
            {
                _AltezzaSmall = value;
            }
        }

        public bool CreaMiniature
        {
            get
            {
                return _CreaMiniature;
            }

            set
            {
                _CreaMiniature = value;
            }
        }

        public bool AggiungiScritteMiniature
        {
            get
            {
                return _AggiungiScritteMiniature;
            }

            set
            {
                _AggiungiScritteMiniature = value;
            }
        }

        public string NomeFileChild
        {
            get
            {
                return _NomeFileChild;
            }

            set
            {
                _NomeFileChild = value;
            }
        }

        public string Suffisso
        {
            get
            {
                return _Suffisso;
            }

            set
            {
                _Suffisso = value;
            }
        }

        public string Codice
        {
            get
            {
                return _Codice;
            }

            set
            {
                _Codice = value;
            }
        }

        public int Trasparenza
        {
            get
            {
                return _Trasparenza;
            }

            set
            {
                _Trasparenza = value;
            }
        }

        public string IlFont
        {
            get
            {
                return _IlFont;
            }

            set
            {
                _IlFont = value;
            }
        }

        public bool Grassetto
        {
            get
            {
                return _Grassetto;
            }

            set
            {
                _Grassetto = value;
            }
        }

        public string Posizione
        {
            get
            {
                return _Posizione;
            }

            set
            {
                _Posizione = value;
            }
        }

        public string Allineamento
        {
            get
            {
                return _Allineamento;
            }

            set
            {
                _Allineamento = value;
            }
        }

        public int Margine
        {
            get
            {
                return _Margine;
            }

            set
            {
                _Margine = value;
            }
        }

        public int LogoAltezza
        {
            get
            {
                return _LogoAltezza;
            }

            set
            {
                _LogoAltezza = value;
            }
        }

        public int LogoLarghezza
        {
            get
            {
                return _LogoLarghezza;
            }

            set
            {
                _LogoLarghezza = value;
            }
        }

        public int FontColoreR
        {
            get
            {
                return _FontColoreR;
            }

            set
            {
                _FontColoreR = value;
            }
        }

        public int FontColoreG
        {
            get
            {
                return _FontColoreG;
            }

            set
            {
                _FontColoreG = value;
            }
        }

        public int FontColoreB
        {
            get
            {
                return _FontColoreB;
            }

            set
            {
                _FontColoreB = value;
            }
        }

        public Color fontColoreRGB
        {
            get
            {
                return _fontColoreRGB;
            }

            set
            {
                _fontColoreRGB = value;
            }
        }

        public bool LogoAggiungi
        {
            get
            {
                return _LogoAggiungi;
            }

            set
            {
                _LogoAggiungi = value;
            }
        }

        public string LogoNomeFile
        {
            get
            {
                return _LogoNomeFile;
            }

            set
            {
                _LogoNomeFile = value;
            }
        }

        public string LogoTrasparenza
        {
            get
            {
                return _LogoTrasparenza;
            }

            set
            {
                _LogoTrasparenza = value;
            }
        }

        public string LogoMargine
        {
            get
            {
                return _LogoMargine;
            }

            set
            {
                _LogoMargine = value;
            }
        }

        public string LogoPosizioneH
        {
            get
            {
                return _LogoPosizioneH;
            }

            set
            {
                _LogoPosizioneH = value;
            }
        }

        public string LogoPosizioneV
        {
            get
            {
                return _LogoPosizioneV;
            }

            set
            {
                _LogoPosizioneV = value;
            }
        }

        public bool FotoGrandeDimOrigina
        {
            get
            {
                return _FotoGrandeDimOrigina;
            }

            set
            {
                _FotoGrandeDimOrigina = value;
            }
        }

        public int AltezzaBig
        {
            get
            {
                return _AltezzaBig;
            }

            set
            {
                _AltezzaBig = value;
            }
        }

        public int LarghezzaBig
        {
            get
            {
                return _LarghezzaBig;
            }

            set
            {
                _LarghezzaBig = value;
            }
        }

        public DirectoryInfo DestDir
        {
            get
            {
                return _DestDir;
            }

            set
            {
                _DestDir = value;
            }
        }

        public int DimVert
        {
            get
            {
                return _DimVert;
            }

            set
            {
                _DimVert = value;
            }
        }

        public int MargVert
        {
            get
            {
                return _MargVert;
            }

            set
            {
                _MargVert = value;
            }
        }

        public bool TestoMin
        {
            get
            {
                return _TestoMin;
            }

            set
            {
                _TestoMin = value;
            }
        }

        public int DimMin
        {
            get
            {
                return _DimMin;
            }

            set
            {
                _DimMin = value;
            }
        }

        public bool SecretDefault
        {
            get
            {
                return _SecretDefault;
            }

            set
            {
                _SecretDefault = value;
            }
        }

        public bool SecretBig
        {
            get
            {
                return _SecretBig;
            }

            set
            {
                _SecretBig = value;
            }
        }

        public bool SecretSmall
        {
            get
            {
                return _SecretSmall;
            }

            set
            {
                _SecretSmall = value;
            }
        }

        public string SecretPathSmall
        {
            get
            {
                return _SecretPathSmall;
            }

            set
            {
                _SecretPathSmall = value;
            }
        }

        public string SecretPathBig
        {
            get
            {
                return _SecretPathBig;
            }

            set
            {
                _SecretPathBig = value;
            }
        }

        public bool AggTempoGaraMin
        {
            get
            {
                return _AggTempoGaraMin;
            }

            set
            {
                _AggTempoGaraMin = value;
            }
        }

        public bool AggNumTempMin
        {
            get
            {
                return _AggNumTempMin;
            }

            set
            {
                _AggNumTempMin = value;
            }
        }

        public long jpegQuality
        {
            get
            {
                return _jpegQuality;
            }

            set
            {
                _jpegQuality = value;
            }
        }

        public long jpegQualityMin
        {
            get
            {
                return _jpegQualityMin;
            }

            set
            {
                _jpegQualityMin = value;
            }
        }
    }
}