Beispiel #1
0
        public virtual void  saveJPEG(System.String filename)
        {
            try
            {
                // Set the quality to 100 (must be a long)
                System.Drawing.Imaging.Encoder          qualityEncoder = System.Drawing.Imaging.Encoder.Quality;
                System.Drawing.Imaging.EncoderParameter ratio          = new System.Drawing.Imaging.EncoderParameter(qualityEncoder, 100L);
                // Add the quality parameter to the list
                System.Drawing.Imaging.EncoderParameters codecParams = new System.Drawing.Imaging.EncoderParameters(1);
                codecParams.Param[0] = ratio;

                // Get Codec Info using MIME type
                System.Drawing.Imaging.ImageCodecInfo JpegCodecInfo = GetEncoderInfo("image/jpeg");

                //
                System.Console.Out.WriteLine("Saving '" + filename + "'.");

                offImg.Save(filename, JpegCodecInfo, codecParams);

                System.Console.Out.WriteLine("JPEG image saved.");
            }
            catch (System.Exception e)
            {
                System.Console.Out.WriteLine(e);
            }
        }
Beispiel #2
0
        public EncoderParameter(System.Drawing.Imaging.Encoder encoder, int[] numerator1, int[] denominator1, int[] numerator2, int[] denominator2)
        {
            this.parameterGuid = encoder.Guid;
            if (((numerator1.Length != denominator1.Length) || (numerator1.Length != denominator2.Length)) || (denominator1.Length != denominator2.Length))
            {
                throw SafeNativeMethods.Gdip.StatusException(2);
            }
            this.parameterValueType = 8;
            this.numberOfValues     = numerator1.Length;
            int num = Marshal.SizeOf(typeof(int));

            this.parameterValue = Marshal.AllocHGlobal((int)((this.numberOfValues * 4) * num));
            if (this.parameterValue == IntPtr.Zero)
            {
                throw SafeNativeMethods.Gdip.StatusException(3);
            }
            for (int i = 0; i < this.numberOfValues; i++)
            {
                Marshal.WriteInt32(Add(this.parameterValue, (4 * i) * num), numerator1[i]);
                Marshal.WriteInt32(Add(this.parameterValue, ((4 * i) + 1) * num), denominator1[i]);
                Marshal.WriteInt32(Add(this.parameterValue, ((4 * i) + 2) * num), numerator2[i]);
                Marshal.WriteInt32(Add(this.parameterValue, ((4 * i) + 3) * num), denominator2[i]);
            }
            GC.KeepAlive(this);
        }
Beispiel #3
0
        /// <summary>
        /// 儲存圖片
        /// </summary>
        void func_SaveBitmap(System.Drawing.Bitmap b, String type, string path)
        {
            //png
            if (type == "png")
            {
                b.Save(path);
                return;
            }

            //------------


            //jpg

            var jpgEncoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg);

            // Create an Encoder object based on the GUID
            // for the Quality parameter category.
            System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;

            // Create an EncoderParameters object.
            // An EncoderParameters object has an array of EncoderParameter
            // objects. In this case, there is only one
            // EncoderParameter object in the array.
            var myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1);

            var myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(myEncoder, 98L);

            myEncoderParameters.Param[0] = myEncoderParameter;
            b.Save(path, jpgEncoder, myEncoderParameters);
        }
Beispiel #4
0
        private void buttonSavePicture_Click(object sender, EventArgs e)
        {
            if (pictureBoxHierarchy.Image != null)
            {
                SaveFileDialog savedialog = new SaveFileDialog();
                savedialog.Title           = "Сохранить картинку как...";
                savedialog.OverwritePrompt = true;
                savedialog.CheckPathExists = true;
                savedialog.Filter          = "Image Files(*.JPG)|*.JPG";
                savedialog.ShowHelp        = true;

                System.Drawing.Imaging.ImageCodecInfo jpgEncoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg);

                System.Drawing.Imaging.Encoder           myEncoder           = System.Drawing.Imaging.Encoder.Quality;
                System.Drawing.Imaging.EncoderParameters myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
                System.Drawing.Imaging.EncoderParameter  myEncoderParameter  = new System.Drawing.Imaging.EncoderParameter(myEncoder, 100L);
                myEncoderParameters.Param[0] = myEncoderParameter;

                if (savedialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        pictureBoxHierarchy.Image.Save(savedialog.FileName, jpgEncoder, myEncoderParameters);
                    }
                    catch
                    {
                        MessageBox.Show("Невозможно сохранить изображение", "Ошибка",
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
Beispiel #5
0
 public void SaveBmpWithImageCodecInfo(System.Drawing.Image img, string photoPath)
 {
     System.Drawing.Imaging.ImageCodecInfo    encoderInfo       = PictureWaterMark.GetEncoderInfo("image/jpeg");
     System.Drawing.Imaging.Encoder           quality           = System.Drawing.Imaging.Encoder.Quality;
     System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
     System.Drawing.Imaging.EncoderParameter  encoderParameter  = new System.Drawing.Imaging.EncoderParameter(quality, 100L);
     encoderParameters.Param[0] = encoderParameter;
     if (img == null)
     {
         return;
     }
     System.Drawing.Bitmap bitmap = null;
     try
     {
         bitmap = new System.Drawing.Bitmap(img);
         bitmap.Save(photoPath, encoderInfo, encoderParameters);
     }
     catch (Exception ex)
     {
         Log.WriteLog("SaveBmpWithImageCodecInfo出错", ex);
     }
     finally
     {
         bitmap.Dispose();
     }
 }
Beispiel #6
0
        static void Main(string[] args)
        {
            foreach (string file in args)
            {
                try
                {
                    System.Console.Write("Reading file: {0} ... ", file);
                    using (System.Drawing.Image image = System.Drawing.Image.FromFile(file))
                    {
                        System.Console.WriteLine("Done");

                        System.IO.FileInfo info   = new System.IO.FileInfo(file);
                        string             output = file.Replace(info.Extension, ".jpg");

                        System.Console.Write("Writing file: {0} ... ", output);

                        // Create parameters to specify quality.
                        System.Drawing.Imaging.ImageCodecInfo    codec      = Program.getCodecInfo("image/jpeg");
                        System.Drawing.Imaging.Encoder           encoder    = System.Drawing.Imaging.Encoder.Quality;
                        System.Drawing.Imaging.EncoderParameters parameters = new System.Drawing.Imaging.EncoderParameters(1);
                        parameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(encoder, 100L);

                        // Write the file.
                        image.Save(output, codec, parameters);
                        System.Console.WriteLine("Done");
                    }
                }
                catch (System.Exception e)
                {
                    System.Console.WriteLine("Error processing file '", file, ", ", e.Message);
                }
            }
        }
Beispiel #7
0
        public static string GetJPEGBase64StringFromBitmapImage(BitmapImage bmpImage, long jpegEncoderQuality, System.Drawing.RotateFlipType rotateFlip)
        {
            System.Drawing.Bitmap bmp = null;
            MemoryStream          ms  = new MemoryStream();

            try
            {
                System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
                System.Drawing.Imaging.Encoder           myEncoder         = System.Drawing.Imaging.Encoder.Quality;
                encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(myEncoder, jpegEncoderQuality);
                System.Drawing.Imaging.ImageCodecInfo jgpEncoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg);

                bmp = UIHelper.BitmapImage2Bitmap(bmpImage);
                bmp.RotateFlip(rotateFlip);
                bmp.Save(ms, jgpEncoder, encoderParameters);

                return(Convert.ToBase64String(ms.ToArray()));
            }
            finally
            {
                DeleteObject(bmp.GetHbitmap());
                bmp.Dispose();
                bmp = null;
            }
        }
Beispiel #8
0
        public static byte[] ReduceWeightImage(System.Drawing.Image image, long minByteWeight, long maxByteWeight)
        {
            byte[] source = GetBytes(image);
            if (source.Length < maxByteWeight)
            {
                return(source);
            }

            if (minByteWeight > 0 && maxByteWeight > 0)
            {
                if (minByteWeight > maxByteWeight)
                {
                    (minByteWeight, maxByteWeight) = (maxByteWeight, minByteWeight);
                }
                if (maxByteWeight - minByteWeight < 50)
                {
                    maxByteWeight = minByteWeight + 50;
                }
                System.Drawing.Imaging.ImageCodecInfo[] codecs = System.Drawing.Imaging.ImageCodecInfo.GetImageDecoders();
                string mimeType = GetMimeType(image);
                System.Drawing.Imaging.ImageCodecInfo imageCodecInfo = codecs[1];

                System.Drawing.Imaging.Encoder           encoder           = System.Drawing.Imaging.Encoder.Quality;
                System.Drawing.Imaging.EncoderParameters encoderParameters =
                    new System.Drawing.Imaging.EncoderParameters(1);

                return(ReduceWeightImageProcess(source, source, minByteWeight, maxByteWeight, imageCodecInfo,
                                                encoder, encoderParameters, source.LongLength * 85L / 1166927L));
            }
            return(source);
        }
Beispiel #9
0
        private static byte[] ReduceWeightImageProcess(byte[] source, byte[] destination,
                                                       long minByteWeight, long maxByteWeight, System.Drawing.Imaging.ImageCodecInfo imageCodecInfo,
                                                       System.Drawing.Imaging.Encoder encoder, System.Drawing.Imaging.EncoderParameters encoderParameters,
                                                       long ratio)
        {
            if (source == null || source.Length == 0)
            {
                throw new ArgumentNullException("source");
            }

            if (destination == null || destination.Length == 0)
            {
                destination = source;
            }

            var nextRatio = ratio;

            System.IO.MemoryStream ms;
            System.Drawing.Image   image;
            System.Drawing.Bitmap  bmp1;
            int previousLength = source.Length;

            while (nextRatio > 0 && (destination.Length < minByteWeight || destination.Length > maxByteWeight))
            {
                using (image = System.Drawing.Image.FromStream(new System.IO.MemoryStream(source)))
                {
                    using (bmp1 = new System.Drawing.Bitmap(image))
                    {
                        encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(encoder, nextRatio);
                        using (ms = new System.IO.MemoryStream())
                        {
                            bmp1.Save(ms, imageCodecInfo, encoderParameters);
                            destination = ms.ToArray();
                            if (destination.Length == previousLength)
                            {
                                break;
                            }
                            previousLength = destination.Length;
                            if (destination.LongLength > maxByteWeight)
                            {
                                if (nextRatio > 10)
                                {
                                    nextRatio -= 3;
                                }
                                else
                                {
                                    break;
                                }
                            }
                            else if (destination.LongLength < minByteWeight)
                            {
                                nextRatio += 5;
                            }
                        }
                    }
                }
            }
            return(destination);
        }
Beispiel #10
0
        //sets compression properties of codec
        private EncoderParameters getParameters()
        {
            System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
            EncoderParameters myEncoderParameters    = new EncoderParameters(1);
            EncoderParameter  myEncoderParameter     = new EncoderParameter(myEncoder, 30L);

            myEncoderParameters.Param[0] = myEncoderParameter;
            return(myEncoderParameters);
        }
Beispiel #11
0
        public static void SaveImage(System.Drawing.Image Image, string Destination)
        {
            System.Drawing.Imaging.ImageCodecInfo    jgpEncoder          = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg);
            System.Drawing.Imaging.Encoder           myEncoder           = System.Drawing.Imaging.Encoder.Quality;
            System.Drawing.Imaging.EncoderParameters myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
            System.Drawing.Imaging.EncoderParameter  myEncoderParameter  = new System.Drawing.Imaging.EncoderParameter(myEncoder, (long)Settings.ImageQuality);
            myEncoderParameters.Param[0] = myEncoderParameter;

            Image.Save(Destination, jgpEncoder, myEncoderParameters);
        }
Beispiel #12
0
 public EncoderParameter(System.Drawing.Imaging.Encoder encoder, string value)
 {
     this.parameterGuid      = encoder.Guid;
     this.parameterValueType = 2;
     this.numberOfValues     = value.Length;
     this.parameterValue     = Marshal.StringToHGlobalAnsi(value);
     GC.KeepAlive(this);
     if (this.parameterValue == IntPtr.Zero)
     {
         throw SafeNativeMethods.Gdip.StatusException(3);
     }
 }
Beispiel #13
0
        public EncoderParameter(System.Drawing.Imaging.Encoder encoder, int NumberOfValues, int Type, int Value)
        {
            int num;

            IntSecurity.UnmanagedCode.Demand();
            switch (((EncoderParameterValueType)Type))
            {
            case EncoderParameterValueType.ValueTypeByte:
            case EncoderParameterValueType.ValueTypeAscii:
                num = 1;
                break;

            case EncoderParameterValueType.ValueTypeShort:
                num = 2;
                break;

            case EncoderParameterValueType.ValueTypeLong:
                num = 4;
                break;

            case EncoderParameterValueType.ValueTypeRational:
            case EncoderParameterValueType.ValueTypeLongRange:
                num = 8;
                break;

            case EncoderParameterValueType.ValueTypeUndefined:
                num = 1;
                break;

            case EncoderParameterValueType.ValueTypeRationalRange:
                num = 0x10;
                break;

            default:
                throw SafeNativeMethods.Gdip.StatusException(8);
            }
            int cb = num * NumberOfValues;

            this.parameterValue = Marshal.AllocHGlobal(cb);
            if (this.parameterValue == IntPtr.Zero)
            {
                throw SafeNativeMethods.Gdip.StatusException(3);
            }
            for (int i = 0; i < cb; i++)
            {
                Marshal.WriteByte(Add(this.parameterValue, i), Marshal.ReadByte((IntPtr)(Value + i)));
            }
            this.parameterValueType = Type;
            this.numberOfValues     = NumberOfValues;
            this.parameterGuid      = encoder.Guid;
            GC.KeepAlive(this);
        }
Beispiel #14
0
 public EncoderParameter(System.Drawing.Imaging.Encoder encoder, byte[] value)
 {
     this.parameterGuid      = encoder.Guid;
     this.parameterValueType = 1;
     this.numberOfValues     = value.Length;
     this.parameterValue     = Marshal.AllocHGlobal(this.numberOfValues);
     if (this.parameterValue == IntPtr.Zero)
     {
         throw SafeNativeMethods.Gdip.StatusException(3);
     }
     Marshal.Copy(value, 0, this.parameterValue, this.numberOfValues);
     GC.KeepAlive(this);
 }
Beispiel #15
0
 public EncoderParameter(System.Drawing.Imaging.Encoder encoder, byte value)
 {
     this.parameterGuid      = encoder.Guid;
     this.parameterValueType = 1;
     this.numberOfValues     = 1;
     this.parameterValue     = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(byte)));
     if (this.parameterValue == IntPtr.Zero)
     {
         throw SafeNativeMethods.Gdip.StatusException(3);
     }
     Marshal.WriteByte(this.parameterValue, value);
     GC.KeepAlive(this);
 }
Beispiel #16
0
        //takes a screenshot of user's computer at the location where the signature and details about hours/name are
        //then encodes that into .jpg format and loads it into a byte array
        //finally a new record is made in the Signature database table
        //the first three fields are populated from the controlling form (Name, WeekStart, Hours)
        //the last field is the byte array representing the screenshot taken earlier

        private void SubmitButton_Click(object sender, EventArgs e)
        {
            Rectangle screen = RectangleToScreen(this.ClientRectangle);
            Rectangle rect   = new Rectangle(SignaturePanel.Left + screen.Left, InfoLabel.Top + screen.Top - 10,
                                             SignaturePanel.Width, NameLabel.Bottom - InfoLabel.Top + 20);
            Bitmap   bmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb);
            Graphics g   = Graphics.FromImage(bmp);

            g.CopyFromScreen(rect.Left, rect.Top, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy);

            ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);

            System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
            EncoderParameters myEncoderParameters    = new EncoderParameters(1);
            EncoderParameter  myEncoderParameter     = new EncoderParameter(myEncoder, 30L);

            myEncoderParameters.Param[0] = myEncoderParameter;
            GraphicsUnit gu          = GraphicsUnit.Pixel;
            float        ratio       = bmp.GetBounds(ref gu).Height / bmp.GetBounds(ref gu).Width;
            Bitmap       scaledImage = new Bitmap(bmp, 220, (int)(220 * ratio));

            byte[] imgBytes = new byte[1000000];
            try {
                MemoryStream tmpStream = new MemoryStream();
                scaledImage.Save(tmpStream, GetEncoder(ImageFormat.Jpeg), getParameters());
                tmpStream.Seek(0, SeekOrigin.Begin);
                tmpStream.Read(imgBytes, 0, 1000000);
                tmpStream.Close();
            }
            catch (Exception errr) { imgBytes = new byte[10]; }
            try {
                MySqlConnection MyConn =
                    new MySqlConnection(ConfigurationManager.ConnectionStrings["myString"].ConnectionString);
                MyConn.Open();

                MySqlCommand MyCommand = MyConn.CreateCommand();
                MyCommand.CommandText = "INSERT INTO Signature (Name, WeekStart, Hours, Picture) 
                       VALUES(@name, @weekstart, @hours, @picture);";
                insertParameter(MyCommand, "@name", DbType.String, name);
                insertParameter(MyCommand, "@weekstart", DbType.Date, weekstart);
                insertParameter(MyCommand, "@hours", DbType.Double, hours);
                insertParameter(MyCommand, "@picture", DbType.Binary, imgBytes);
                MyCommand.ExecuteNonQuery();
            }
            catch (Exception er) {
                MessageBox.Show(er.Message);
            }
            this.Hide();
        }
Beispiel #17
0
        public EncoderParameter(System.Drawing.Imaging.Encoder encoder, short[] value)
        {
            this.parameterGuid      = encoder.Guid;
            this.parameterValueType = 3;
            this.numberOfValues     = value.Length;
            int num = Marshal.SizeOf(typeof(short));

            this.parameterValue = Marshal.AllocHGlobal((int)(this.numberOfValues * num));
            if (this.parameterValue == IntPtr.Zero)
            {
                throw SafeNativeMethods.Gdip.StatusException(3);
            }
            Marshal.Copy(value, 0, this.parameterValue, this.numberOfValues);
            GC.KeepAlive(this);
        }
Beispiel #18
0
        public EncoderParameter(System.Drawing.Imaging.Encoder encoder, long rangebegin, long rangeend)
        {
            this.parameterGuid      = encoder.Guid;
            this.parameterValueType = 6;
            this.numberOfValues     = 1;
            int b = Marshal.SizeOf(typeof(int));

            this.parameterValue = Marshal.AllocHGlobal((int)(2 * b));
            if (this.parameterValue == IntPtr.Zero)
            {
                throw SafeNativeMethods.Gdip.StatusException(3);
            }
            Marshal.WriteInt32(this.parameterValue, (int)rangebegin);
            Marshal.WriteInt32(Add(this.parameterValue, b), (int)rangeend);
            GC.KeepAlive(this);
        }
Beispiel #19
0
        public EncoderParameter(System.Drawing.Imaging.Encoder encoder, int numerator1, int demoninator1, int numerator2, int demoninator2)
        {
            this.parameterGuid      = encoder.Guid;
            this.parameterValueType = 8;
            this.numberOfValues     = 1;
            int b = Marshal.SizeOf(typeof(int));

            this.parameterValue = Marshal.AllocHGlobal((int)(4 * b));
            if (this.parameterValue == IntPtr.Zero)
            {
                throw SafeNativeMethods.Gdip.StatusException(3);
            }
            Marshal.WriteInt32(this.parameterValue, numerator1);
            Marshal.WriteInt32(Add(this.parameterValue, b), demoninator1);
            Marshal.WriteInt32(Add(this.parameterValue, 2 * b), numerator2);
            Marshal.WriteInt32(Add(this.parameterValue, 3 * b), demoninator2);
            GC.KeepAlive(this);
        }
Beispiel #20
0
        public void saveScreenImage(string file)
        {
            // Grab screen pixels.
            System.Drawing.Rectangle bounds = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
            System.Drawing.Bitmap    bitmap = this._getDesktopImage(bounds);

            // Create parameters to specify quality.
            System.Drawing.Imaging.ImageCodecInfo    codec      = Program.getCodecInfo("image/jpeg");
            System.Drawing.Imaging.Encoder           encoder    = System.Drawing.Imaging.Encoder.Quality;
            System.Drawing.Imaging.EncoderParameters parameters = new System.Drawing.Imaging.EncoderParameters(1);
            parameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(encoder, 100L);

            // Make the output file name.
            string output = ((null == file) ? System.String.Format("{0}_screen_shot.jpg", System.DateTime.Now.ToFileTime()) : file);

            // Write the file.
            bitmap.Save(output, codec, parameters);
        }
Beispiel #21
0
        /// <summary>
        /// 压缩图片处理
        /// </summary>
        /// <param name="stream">图片流</param>
        /// <param name="quality">质量 取值 0-100之间,数值越大质量越高</param>
        public Byte[] CompressionImageProcessing(Stream stream, long quality = 0L)
        {
            using (System.Drawing.Image img = System.Drawing.Image.FromStream(stream))
            {
                using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(img))
                {
                    System.Drawing.Imaging.ImageCodecInfo    codecInfo         = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders().FirstOrDefault(e => e.FormatID == img.RawFormat.Guid);
                    System.Drawing.Imaging.Encoder           encoder           = System.Drawing.Imaging.Encoder.Quality;
                    System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
                    System.Drawing.Imaging.EncoderParameter  encoderParameter  = new System.Drawing.Imaging.EncoderParameter(encoder, quality);

                    encoderParameters.Param[0] = encoderParameter;
                    using (System.IO.MemoryStream ms = new MemoryStream())
                    {
                        bitmap.Save(ms, codecInfo, encoderParameters);
                        encoderParameters.Dispose();
                        encoderParameter.Dispose();
                        return(ms.ToArray());
                    }
                }
            }
        }
Beispiel #22
0
        public EncoderParameter(System.Drawing.Imaging.Encoder encoder, long[] rangebegin, long[] rangeend)
        {
            this.parameterGuid = encoder.Guid;
            if (rangebegin.Length != rangeend.Length)
            {
                throw SafeNativeMethods.Gdip.StatusException(2);
            }
            this.parameterValueType = 6;
            this.numberOfValues     = rangebegin.Length;
            int num = Marshal.SizeOf(typeof(int));

            this.parameterValue = Marshal.AllocHGlobal((int)((this.numberOfValues * 2) * num));
            if (this.parameterValue == IntPtr.Zero)
            {
                throw SafeNativeMethods.Gdip.StatusException(3);
            }
            for (int i = 0; i < this.numberOfValues; i++)
            {
                Marshal.WriteInt32(Add((i * 2) * num, this.parameterValue), (int)rangebegin[i]);
                Marshal.WriteInt32(Add(((i * 2) + 1) * num, this.parameterValue), (int)rangeend[i]);
            }
            GC.KeepAlive(this);
        }
Beispiel #23
0
        public unsafe EncoderParameter(System.Drawing.Imaging.Encoder encoder, long[] value)
        {
            this.parameterGuid      = encoder.Guid;
            this.parameterValueType = 4;
            this.numberOfValues     = value.Length;
            int num = Marshal.SizeOf(typeof(int));

            this.parameterValue = Marshal.AllocHGlobal((int)(this.numberOfValues * num));
            if (this.parameterValue == IntPtr.Zero)
            {
                throw SafeNativeMethods.Gdip.StatusException(3);
            }
            int *parameterValue = (int *)this.parameterValue;

            fixed(long *numRef = value)
            {
                for (int i = 0; i < value.Length; i++)
                {
                    parameterValue[i] = (int)numRef[i];
                }
            }

            GC.KeepAlive(this);
        }
Beispiel #24
0
        /// <summary>
        /// Guarda todos los cambios en la base de datos. Si se trata de un elemento nuevo, se agrega un registro a la base de datos.
        /// Si se trata de un elemento existente, se modifica el registro original.
        /// </summary>
        public virtual Lfx.Types.OperationResult Guardar()
        {
            if (this.Id == 0)
            {
                // Acabo de insertar, averiguo mi propio id
                this.ActualizarId();
            }
            else
            {
                // Es un registro antiguo, lo elimino de la caché
                Lfx.Workspace.Master.Tables[this.TablaDatos].FastRows.RemoveFromCache(this.Id);
            }
            this.Registro.IsModified = false;
            this.Registro.IsNew      = false;

            if (this.m_ImagenCambio)
            {
                // Hay cambios en el campo imagen
                if (this.Imagen == null)
                {
                    // Eliminó la imagen
                    if (this.TablaImagenes == this.TablaDatos)
                    {
                        // La imagen reside en un campo de la misma tabla
                        qGen.Update ActualizarImagen = new qGen.Update(this.TablaImagenes);
                        ActualizarImagen.ColumnValues.AddWithValue("imagen", null);
                        ActualizarImagen.WhereClause = new qGen.Where(this.CampoId, this.Id);
                        this.Connection.ExecuteNonQuery(ActualizarImagen);
                    }
                    else
                    {
                        // Usa una tabla separada para las imágenes
                        qGen.Delete EliminarImagen = new qGen.Delete(this.TablaImagenes);
                        EliminarImagen.WhereClause = new qGen.Where(this.CampoId, this.Id);
                        this.Connection.ExecuteNonQuery(EliminarImagen);
                    }
                    Lbl.Sys.Config.ActionLog(this.Connection, Sys.Log.Acciones.Save, this, "Se eliminó la imagen");
                }
                else
                {
                    // Cargar imagen nueva
                    using (System.IO.MemoryStream ByteStream = new System.IO.MemoryStream()) {
                        System.Drawing.Imaging.ImageCodecInfo   CodecInfo = null;
                        System.Drawing.Imaging.ImageCodecInfo[] Codecs    = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
                        foreach (System.Drawing.Imaging.ImageCodecInfo Codec in Codecs)
                        {
                            if (Codec.MimeType == "image/jpeg")
                            {
                                CodecInfo = Codec;
                            }
                        }

                        if (CodecInfo == null)
                        {
                            this.Imagen.Save(ByteStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                        }
                        else
                        {
                            System.Drawing.Imaging.Encoder QualityEncoder = System.Drawing.Imaging.Encoder.Quality;
                            using (System.Drawing.Imaging.EncoderParameters EncoderParams = new System.Drawing.Imaging.EncoderParameters(1)) {
                                EncoderParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(QualityEncoder, 33L);

                                this.Imagen.Save(ByteStream, CodecInfo, EncoderParams);
                            }
                        }
                        byte[] ImagenBytes = ByteStream.ToArray();

                        qGen.IStatement CambiarImagen;
                        if (this.TablaImagenes != this.TablaDatos)
                        {
                            qGen.Delete EliminarImagen = new qGen.Delete(this.TablaImagenes);
                            EliminarImagen.WhereClause = new qGen.Where(this.CampoId, this.Id);
                            this.Connection.ExecuteNonQuery(EliminarImagen);

                            CambiarImagen = new qGen.Insert(this.TablaImagenes);
                            CambiarImagen.ColumnValues.AddWithValue(this.CampoId, this.Id);
                        }
                        else
                        {
                            CambiarImagen             = new qGen.Update(this.TablaImagenes);
                            CambiarImagen.WhereClause = new qGen.Where(this.CampoId, this.Id);
                        }

                        CambiarImagen.ColumnValues.AddWithValue("imagen", ImagenBytes);
                        this.Connection.ExecuteNonQuery(CambiarImagen);
                        Lbl.Sys.Config.ActionLog(this.Connection, Sys.Log.Acciones.Save, this, "Se cargó una imagen nueva");
                    }
                }
            }

            this.GuardarEtiquetas();
            this.GuardarLog();
            Lfx.Workspace.Master.NotifyTableChange(this.TablaDatos, this.Id);

            this.m_RegistroOriginal  = this.m_Registro.Clone();
            this.m_EtiquetasOriginal = this.m_Etiquetas.Clone();
            this.m_ImagenCambio      = false;

            return(new Lfx.Types.SuccessOperationResult());
        }
Beispiel #25
0
        private void Convert_Click(object sender, EventArgs e)
        {
            if (!isDropped)
            {
                MessageBox.Show("Please drag files.");
                return;
            }
            else if (this.chkMergePDF.Checked && this.PDFTitle.Text.Equals(""))
            {
                MessageBox.Show("Please enter the PDF title.");
                return;
            }
            else if (!(this.chkMergePDF.Checked || this.chkCreateImages.Checked))
            {
                MessageBox.Show("Please check");
                return;
            }

            this.Status.Text = "Converting...";

            int m_idx = 0;

            foreach (string fileImg in imgFiles)
            {
                int m_pos = imgFiles[m_idx].LastIndexOf('\\');
                filepath = imgFiles[m_idx++].Substring(0, m_pos);
                //MessageBox.Show(m_idx + " " + filepath);
                savedPath = filepath + convertedDir + '\\';



                System.IO.Directory.CreateDirectory(savedPath);

                string m_filename = "";
                for (int ii = fileImg.LastIndexOf('\\') + 1; ii < fileImg.Length - 4; ii++)
                {
                    m_filename += fileImg[ii];
                }

                this.Status.Text = "Converting " + m_filename;

                Bitmap i    = System.Drawing.Image.FromFile(fileImg) as Bitmap;
                var    dpiX = i.HorizontalResolution;
                var    dpiY = i.VerticalResolution;
                int    iW   = i.Width;
                int    iH   = i.Height;



                var temp = new Bitmap(iW / 2, iH, i.PixelFormat);
                temp.SetResolution(dpiX, dpiY);

                //MBDN code, 'GetEncoder' is a custom declared method
                //Trying to solve the problem; images drawn by 'Graphics' not being able to be opened on the photoshop app
                System.Drawing.Imaging.ImageCodecInfo    jpgEncoder          = this.GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg);
                System.Drawing.Imaging.Encoder           myEncoder           = System.Drawing.Imaging.Encoder.Quality;
                System.Drawing.Imaging.EncoderParameters myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1);

                //180503-01 adjusted by adding (long)dpiX for the parameter, while dpiX is the original horizontal resolution of the referred image file.
                System.Drawing.Imaging.EncoderParameter myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(myEncoder, (long)dpiX);
                myEncoderParameters.Param[0] = myEncoderParameter;

                /*
                 * using (var gr = Graphics.FromImage(temp))
                 * {
                 *  gr.DrawImageUnscaled(i, 0, 0, iW, iH);
                 * }
                 * temp.Save(savedPath + m_filename + "_L.jpg", jpgEncoder, myEncoderParameters);
                 */

                string lPath = savedPath + m_filename + "_L.jpg";
                string rPath = savedPath + m_filename + "_R.jpg";
                convertedPaths.Add(lPath);
                convertedPaths.Add(rPath);

                int iW2 = iW / 2;

                for (int ii = 0; ii < iW2; ii++)
                {
                    for (int jj = 0; jj < iH; jj++)
                    {
                        temp.SetPixel(ii, jj, i.GetPixel(ii, jj));
                    }
                }
                temp.Save(lPath);
                //temp.Save(lPath, jpgEncoder, myEncoderParameters);


                for (int ii = 0; ii < iW2; ii++)
                {
                    for (int jj = 0; jj < iH; jj++)
                    {
                        temp.SetPixel(ii, jj, i.GetPixel(ii + iW2, jj));
                    }
                }

                temp.Save(rPath);
                //temp.Save(rPath, jpgEncoder, myEncoderParameters);


                /*180503-01, the color has lost its vividness, trying out different options.
                 * using (var gr = Graphics.FromImage(temp))
                 * {
                 *  gr.Clear(Color.Transparent);
                 *  gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                 *  //gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                 *  gr.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
                 *
                 *  gr.DrawImage(i, new System.Drawing.Rectangle(0, 0, iW, iH));
                 * }
                 * temp.Save(lPath, jpgEncoder, myEncoderParameters);
                 * using (var gr = Graphics.FromImage(temp))
                 * {
                 *  gr.Clear(Color.Transparent);
                 *  gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                 *  gr.DrawImage(i, new System.Drawing.Rectangle(0, 0, iW, iH), new System.Drawing.Rectangle(iW / 2, 0, iW, iH), GraphicsUnit.Pixel);
                 * }
                 * temp.Save(rPath, jpgEncoder, myEncoderParameters);
                 */


                /*0502-01. succeeded in diving into two. failed to keep the original resolution
                 * Bitmap i = Image.FromFile(fileImg) as Bitmap;
                 * var dpiX = i.HorizontalResolution;
                 * var dpiY = i.VerticalResolution;
                 * MessageBox.Show(dpiX + "   " + dpiY);
                 * int iW = i.Width;
                 * int iH = i.Height;
                 * Rectangle cropRectL = new Rectangle(0, 0, iW / 2, iH);
                 * Rectangle cropRectR = new Rectangle(iW / 2, 0, iW / 2, iH);
                 * Bitmap target = new Bitmap(i);
                 *
                 * target.Clone(cropRectL, target.PixelFormat).Save(savedPath + m_filename + "_L.jpg");
                 * target.Clone(cropRectR, target.PixelFormat).Save(savedPath + m_filename + "_R.jpg");
                 */

                /*0502-02. succeeded in diving into two, keeping the original resolution, but failed in having the files opened on photoshop
                 * Bitmap i = Image.FromFile(fileImg) as Bitmap;
                 * var dpiX = i.HorizontalResolution;
                 * var dpiY = i.VerticalResolution;
                 *
                 * int iW = i.Width;
                 * int iH = i.Height;
                 *
                 * var temp = new Bitmap(iW/2, iH, i.PixelFormat);
                 * temp.SetResolution(dpiX, dpiY);
                 *
                 * using ( var gr = Graphics.FromImage(temp))
                 * {
                 *  gr.Clear(Color.Transparent);
                 *  gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                 *  gr.DrawImage(i, new Rectangle(0, 0, iW, iH));
                 * }
                 * temp.Save(savedPath + m_filename + "_L.jpg");
                 * using (var gr = Graphics.FromImage(temp))
                 * {
                 *  gr.Clear(Color.Transparent);
                 *  gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                 *  gr.DrawImage(i, new Rectangle(0, 0, iW, iH), new Rectangle(iW/2, 0, iW, iH), GraphicsUnit.Pixel);
                 * }
                 * temp.Save(savedPath + m_filename + "_R.jpg");
                 */


                /*  0501version
                 * Bitmap i = Image.FromFile(fileImg) as Bitmap;
                 * i.Save(savedPath + m_filename + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                 * Rectangle cropRectL = new Rectangle(0, 0, i.Width/2, i.Height);
                 * Rectangle cropRectR = new Rectangle(i.Width / 2, 0, i.Width / 2, i.Height);
                 *
                 * Bitmap newImageL = new Bitmap(cropRectL.Width, cropRectL.Height);
                 * Bitmap newImageR = new Bitmap(cropRectR.Width, cropRectR.Height);
                 *
                 * Graphics gL = Graphics.FromImage(newImageL);
                 * Graphics gR = Graphics.FromImage(newImageR);
                 *
                 * gL.DrawImage(i, cropRectL.X, cropRectL.Y);
                 * string fileL = savedPath + m_filename + "_L.jpg";
                 * newImageL.Save(fileL, System.Drawing.Imaging.ImageFormat.Jpeg);
                 *
                 * gR.DrawImage(i, cropRectL, cropRectR, GraphicsUnit.Pixel);
                 * string fileR = savedPath + m_filename + "_R.jpg";
                 * newImageR.Save(fileR, System.Drawing.Imaging.ImageFormat.Jpeg);
                 *
                 * imgFilesConverted.Add(fileL);
                 * imgFilesConverted.Add(fileR);
                 *
                 * gL.Dispose();
                 * gR.Dispose();
                 * i.Dispose();
                 * newImageL.Dispose();
                 * newImageR.Dispose();
                 */
            }

            string finishedMsg = "Image cut";

            if (this.chkMergePDF.Checked)
            {
                toPDF();
                finishedMsg = "Image cut & PDF merged";
            }

            if (!this.chkCreateImages.Checked)
            {
                try
                {
                    System.GC.Collect();
                    foreach (string img in convertedPaths)
                    {
                        File.Delete(img);
                    }
                    finishedMsg += " & Image Deleted";
                }
                catch (IOException ee)
                {
                    MessageBox.Show("Not able to delete images. error code : " + ee);
                }
            }


            MessageBox.Show(finishedMsg);

            this.setLog();
            this.initDisplay();

            this.Status.Text = "Drag and drop images";
        }
        private void Convert_Click(object sender, EventArgs e)
        {
            if (!isDropped)
            {
                MessageBox.Show(g_lang == 0 ? "Please drag files first" : "변환될 이미지를 입력해주세요");
                return;
            }
            else if (this.chkMergePDF.Checked && this.etxtPDFTitle.Text.Equals(""))
            {
                MessageBox.Show(g_lang == 0 ? "Please input the pdf title" : "PDF 제목을 입력해주세요");
                return;
            }
            else if (!(this.chkMergePDF.Checked || this.chkCreateImages.Checked))
            {
                MessageBox.Show(g_lang == 0 ? "Please check" : "체크해 주세요");
                return;
            }

            this.lblStatus.Text  = g_lang == 0 ? "Converting..." : "변환 중...";
            this.Display.Enabled = false;

            int m_idx = 0;

            foreach (string fileImg in imgFiles)
            {
                int m_pos = imgFiles[m_idx].LastIndexOf('\\');
                filepath = imgFiles[m_idx++].Substring(0, m_pos);
                //MessageBox.Show(m_idx + " " + filepath);
                savedPath = filepath + convertedDir + '\\';



                System.IO.Directory.CreateDirectory(savedPath);

                string m_filename = "";
                for (int ii = fileImg.LastIndexOf('\\') + 1; ii < fileImg.Length - 4; ii++)
                {
                    m_filename += fileImg[ii];
                }

                //this.lblStatus.Text = "Converting " + m_filename;

                //by giving 'true' as the second parameter, i gain the 'use embedded color management' option, 180503
                Bitmap i = System.Drawing.Image.FromFile(fileImg, true) as Bitmap;
                //Bitmap i = System.Drawing.Image.FromFile(fileImg) as Bitmap;
                var dpiX = i.HorizontalResolution;
                var dpiY = i.VerticalResolution;
                int iW   = i.Width;
                int iH   = i.Height;


                var temp = new Bitmap(iW / 2, iH, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
                //var temp = new Bitmap(iW / 2, iH, i.PixelFormat);
                temp.SetResolution(dpiX, dpiY);

                //MBDN code, 'GetEncoder' is a custom declared method
                //Trying to solve the problem; images drawn by 'Graphics' not being able to be opened on the photoshop app
                System.Drawing.Imaging.ImageCodecInfo jpgEncoder = this.GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg);
                System.Drawing.Imaging.Encoder        myEncoder  = System.Drawing.Imaging.Encoder.Quality;

                System.Drawing.Imaging.EncoderParameters myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1);

                //180503-01 adjusted by adding (long)dpiX for the parameter, while dpiX is the original horizontal resolution of the referred image file.
                System.Drawing.Imaging.EncoderParameter myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(myEncoder, (long)dpiX);
                //System.Drawing.Imaging.EncoderParameter myEncoderParameter2 = new System.Drawing.Imaging.EncoderParameter(myEncoder2, (long)System.Drawing.Imaging.EncoderValue.);
                myEncoderParameters.Param[0] = myEncoderParameter;

                /*
                 * using (var gr = Graphics.FromImage(temp))
                 * {
                 *  gr.DrawImageUnscaled(i, 0, 0, iW, iH);
                 * }
                 * temp.Save(savedPath + m_filename + "_L.jpg", jpgEncoder, myEncoderParameters);
                 */

                string lPath = savedPath + m_filename + "_L.jpg";
                string rPath = savedPath + m_filename + "_R.jpg";
                convertedPaths.Add(lPath);
                convertedPaths.Add(rPath);

                /*
                 * //180503-02, drawing pixel by pixel
                 * int iW2 = iW / 2;
                 * for (int ii = 0; ii < iW2; ii++)
                 * {
                 *  for ( int jj = 0; jj < iH; jj++)
                 *  {
                 *      temp.SetPixel(ii, jj, i.GetPixel(ii, jj));
                 *  }
                 * }
                 * temp.Save(lPath);
                 * for (int ii = 0; ii < iW2; ii++)
                 * {
                 *  for (int jj = 0; jj < iH; jj++)
                 *  {
                 *      temp.SetPixel(ii, jj, i.GetPixel(ii+iW2, jj));
                 *  }
                 * }
                 * temp.Save(rPath);
                 */

                //180503-01, the color has lost its vividness, trying out different options.
                using (var gr = Graphics.FromImage(temp))
                {
                    gr.Clear(Color.Transparent);
                    gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    //gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    gr.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;

                    gr.DrawImage(i, new System.Drawing.Rectangle(0, 0, iW, iH));
                }
                //temp.Save(lPath);
                temp.Save(lPath, jpgEncoder, myEncoderParameters);
                using (var gr = Graphics.FromImage(temp))
                {
                    gr.Clear(Color.Transparent);
                    gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    gr.DrawImage(i, new System.Drawing.Rectangle(0, 0, iW, iH), new System.Drawing.Rectangle(iW / 2, 0, iW, iH), GraphicsUnit.Pixel);
                }
                //temp.Save(rPath);
                temp.Save(rPath, jpgEncoder, myEncoderParameters);



                /*0502-01. succeeded in diving into two. failed to keep the original resolution
                 * Bitmap i = Image.FromFile(fileImg) as Bitmap;
                 * var dpiX = i.HorizontalResolution;
                 * var dpiY = i.VerticalResolution;
                 * MessageBox.Show(dpiX + "   " + dpiY);
                 * int iW = i.Width;
                 * int iH = i.Height;
                 * Rectangle cropRectL = new Rectangle(0, 0, iW / 2, iH);
                 * Rectangle cropRectR = new Rectangle(iW / 2, 0, iW / 2, iH);
                 * Bitmap target = new Bitmap(i);
                 *
                 * target.Clone(cropRectL, target.PixelFormat).Save(savedPath + m_filename + "_L.jpg");
                 * target.Clone(cropRectR, target.PixelFormat).Save(savedPath + m_filename + "_R.jpg");
                 */

                /*0502-02. succeeded in diving into two, keeping the original resolution, but failed in having the files opened on photoshop
                 * Bitmap i = Image.FromFile(fileImg) as Bitmap;
                 * var dpiX = i.HorizontalResolution;
                 * var dpiY = i.VerticalResolution;
                 *
                 * int iW = i.Width;
                 * int iH = i.Height;
                 *
                 * var temp = new Bitmap(iW/2, iH, i.PixelFormat);
                 * temp.SetResolution(dpiX, dpiY);
                 *
                 * using ( var gr = Graphics.FromImage(temp))
                 * {
                 *  gr.Clear(Color.Transparent);
                 *  gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                 *  gr.DrawImage(i, new Rectangle(0, 0, iW, iH));
                 * }
                 * temp.Save(savedPath + m_filename + "_L.jpg");
                 * using (var gr = Graphics.FromImage(temp))
                 * {
                 *  gr.Clear(Color.Transparent);
                 *  gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                 *  gr.DrawImage(i, new Rectangle(0, 0, iW, iH), new Rectangle(iW/2, 0, iW, iH), GraphicsUnit.Pixel);
                 * }
                 * temp.Save(savedPath + m_filename + "_R.jpg");
                 */


                /*  0501version
                 * Bitmap i = Image.FromFile(fileImg) as Bitmap;
                 * i.Save(savedPath + m_filename + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                 * Rectangle cropRectL = new Rectangle(0, 0, i.Width/2, i.Height);
                 * Rectangle cropRectR = new Rectangle(i.Width / 2, 0, i.Width / 2, i.Height);
                 *
                 * Bitmap newImageL = new Bitmap(cropRectL.Width, cropRectL.Height);
                 * Bitmap newImageR = new Bitmap(cropRectR.Width, cropRectR.Height);
                 *
                 * Graphics gL = Graphics.FromImage(newImageL);
                 * Graphics gR = Graphics.FromImage(newImageR);
                 *
                 * gL.DrawImage(i, cropRectL.X, cropRectL.Y);
                 * string fileL = savedPath + m_filename + "_L.jpg";
                 * newImageL.Save(fileL, System.Drawing.Imaging.ImageFormat.Jpeg);
                 *
                 * gR.DrawImage(i, cropRectL, cropRectR, GraphicsUnit.Pixel);
                 * string fileR = savedPath + m_filename + "_R.jpg";
                 * newImageR.Save(fileR, System.Drawing.Imaging.ImageFormat.Jpeg);
                 *
                 * imgFilesConverted.Add(fileL);
                 * imgFilesConverted.Add(fileR);
                 *
                 * gL.Dispose();
                 * gR.Dispose();
                 * i.Dispose();
                 * newImageL.Dispose();
                 * newImageR.Dispose();
                 */
            }

            string finishedMsg = g_lang == 0? "Image cut successfully" : "이미지가 분할되었습니다.";

            if (this.chkMergePDF.Checked)
            {
                toPDF();
                finishedMsg = g_lang == 0 ? "Image cut & PDF merged successfully" : "이미지 분할과 PDF병합에 성공하였습니다.";
            }

            //not supported yet in ver0.23

            /*
             * if ( ! this.chkCreateImages.Checked)
             * {
             *  try
             *  {
             *      System.GC.Collect();
             *      foreach (string img in convertedPaths)
             *      {
             *          File.Delete(img);
             *      }
             *      finishedMsg += " & Image Deleted";
             *  }
             *  catch(IOException ee)
             *  {
             *      MessageBox.Show((g_lang==0? "Not able to delete images. error code : " : "이미지를 지울 수 없었습니다. 에러 코드 :") + ee);
             *  }
             * }
             */

            MessageBox.Show(finishedMsg);

            this.setLog();
            this.initDisplay();
        }
Beispiel #27
0
        static int Main(string[] args)
        {
            string gmlSource = String.Empty;
            string cacheSource = String.Empty;
            string cacheTarget = String.Empty;
            int    jpegQuality = -1, maxlevel = -1;
            bool   listFilenames = false;

            for (int i = 0; i < args.Length - 1; i++)
            {
                if (args[i] == "-gml")
                {
                    gmlSource = args[++i];
                }
                if (args[i] == "-cache")
                {
                    cacheSource = args[++i];
                }
                else if (args[i] == "-target")
                {
                    cacheTarget = args[++i];
                }
                else if (args[i] == "-jpeg-qual")
                {
                    jpegQuality = int.Parse(args[++i]);
                }
                else if (args[i] == "-maxlevel")
                {
                    maxlevel = int.Parse(args[++i]);
                }
                else if (args[i] == "-listfilenames")
                {
                    listFilenames = true;
                }
            }

            if (String.IsNullOrWhiteSpace(gmlSource) || String.IsNullOrWhiteSpace(cacheSource) || String.IsNullOrWhiteSpace(cacheTarget))
            {
                Console.WriteLine("USAGE:");
                Console.WriteLine("gView.Cmd.ClipCompactTilecache.exe -gml <Filename> -cache <cachedirectory> -target <cachetarget>");
                Console.WriteLine("                      [-jpeg-qual <quality  0..100>] -maxlevel <level>");
                Console.WriteLine("                      [-listfilenames]");
                return(1);
            }

            PlugInManager   compMan    = new PlugInManager();
            IFeatureDataset gmlDataset = compMan.CreateInstance(new Guid("dbabe7f1-fe46-4731-ab2b-8a324c60554e")) as IFeatureDataset;

            gmlDataset.ConnectionString = gmlSource;
            gmlDataset.Open();

            List <IPolygon> sourcePolygons = new List <IPolygon>();

            foreach (var element in gmlDataset.Elements)
            {
                if (element.Class is IFeatureClass)
                {
                    var fc = (IFeatureClass)element.Class;

                    using (var cursor = fc.GetFeatures(null))
                    {
                        IFeature feature;
                        while ((feature = cursor.NextFeature) != null)
                        {
                            if (feature.Shape is IPolygon)
                            {
                                sourcePolygons.Add((IPolygon)feature.Shape);
                            }
                        }
                    }
                }
            }

            if (!listFilenames)
            {
                Console.WriteLine(sourcePolygons.Count + " polygons found for clipping...");
            }

            FileInfo configFile = new FileInfo(cacheSource + @"\conf.json");

            if (!configFile.Exists)
            {
                throw new ArgumentException("File " + configFile.FullName + " not exists");
            }

            #region Image Encoding Parameters

            System.Drawing.Imaging.ImageCodecInfo jpgEncoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg);

            // Create an Encoder object based on the GUID
            // for the Quality parameter category.
            System.Drawing.Imaging.Encoder myEncoder =
                System.Drawing.Imaging.Encoder.Quality;

            // Create an EncoderParameters object.
            // An EncoderParameters object has an array of EncoderParameter
            // objects. In this case, there is only one
            // EncoderParameter object in the array.
            System.Drawing.Imaging.EncoderParameters myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1);

            #endregion


            CompactTileConfig cacheConfig = JsonConvert.DeserializeObject <CompactTileConfig>(File.ReadAllText(configFile.FullName));
            double            dpm         = cacheConfig.Dpi / 0.0254;

            foreach (var level in cacheConfig.Levels)
            {
                if (!listFilenames)
                {
                    Console.WriteLine("Level: " + level.Level + " Scale=" + level.Scale);
                }

                double resolution      = (level.Scale / dpm);
                double tileWorldWidth  = cacheConfig.TileSize[0] * resolution;
                double tileWorldHeight = cacheConfig.TileSize[1] * resolution;

                var scaleDirectory = new DirectoryInfo(cacheSource + @"\" + ((int)level.Scale).ToString());
                if (!scaleDirectory.Exists)
                {
                    continue;
                }

                foreach (var bundleFile in scaleDirectory.GetFiles("*.tilebundle"))
                {
                    var bundle = new Bundle(bundleFile.FullName);
                    if (!bundle.Index.Exists)
                    {
                        continue;
                    }

                    int    startRow = bundle.StartRow, startCol = bundle.StartCol;
                    double bundleWorldWidth = tileWorldWidth * 128D, bundleWorldHeight = tileWorldHeight * 128D;

                    IPoint bundleLowerLeft = new Point(cacheConfig.Origin[0] + startCol * tileWorldWidth,
                                                       cacheConfig.Origin[1] - startRow * tileWorldHeight - bundleWorldHeight);
                    IEnvelope bundleEnvelope = new Envelope(bundleLowerLeft, new Point(bundleLowerLeft.X + bundleWorldWidth, bundleLowerLeft.Y + bundleWorldHeight));

                    if (!Intersect(bundleEnvelope, sourcePolygons))
                    {
                        continue;
                    }

                    if (listFilenames)
                    {
                        Console.WriteLine(bundleFile.FullName);
                        continue;
                    }

                    Console.WriteLine("Clip bundle: " + bundleFile.FullName);

                    var clippedBundleFile = new FileInfo(cacheTarget + @"\" + (int)level.Scale + @"\" + bundleFile.Name);
                    if (!clippedBundleFile.Directory.Exists)
                    {
                        clippedBundleFile.Directory.Create();
                    }
                    if (clippedBundleFile.Exists)
                    {
                        clippedBundleFile.Delete();
                    }

                    var indexBuilder   = new CompactTilesIndexBuilder();
                    int clippedTilePos = 0;

                    for (int r = 0; r < 128; r++)
                    {
                        for (int c = 0; c < 128; c++)
                        {
                            int tileLength;
                            int tilePos = bundle.Index.TilePosition(r, c, out tileLength);

                            if (tilePos >= 0 && tileLength >= 0)
                            {
                                IPoint tileLowerLeft = new Point(cacheConfig.Origin[0] + (startCol + c) * tileWorldWidth,
                                                                 cacheConfig.Origin[1] - (startRow + r + 1) * tileWorldHeight);
                                IEnvelope tileEnvelope = new Envelope(tileLowerLeft, new Point(tileLowerLeft.X + tileWorldWidth, tileLowerLeft.Y + tileWorldHeight));

                                if (!Intersect(tileEnvelope, sourcePolygons))
                                {
                                    continue;
                                }

                                Console.WriteLine("Append tile " + level.Level + "/" + (startRow + r) + "/" + (startCol + c));

                                byte[] data = bundle.ImageData(tilePos, tileLength);

                                if (jpegQuality > 0)
                                {
                                    #region New Jpeg Quality

                                    MemoryStream ms = new MemoryStream(data);
                                    using (System.Drawing.Image image = System.Drawing.Image.FromStream(ms))
                                    {
                                        MemoryStream outputMs = new MemoryStream();

                                        System.Drawing.Imaging.EncoderParameter myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(myEncoder, Convert.ToInt64(jpegQuality));
                                        myEncoderParameters.Param[0] = myEncoderParameter;

                                        image.Save(outputMs, jpgEncoder, myEncoderParameters);
                                        data = outputMs.ToArray();
                                    }

                                    #endregion
                                }
                                using (var stream = new FileStream(clippedBundleFile.FullName, FileMode.Append))
                                {
                                    stream.Write(data, 0, data.Length);
                                }

                                indexBuilder.SetValue(r, c, clippedTilePos, data.Length);
                                clippedTilePos += data.Length;
                            }
                        }
                    }

                    if (clippedTilePos > 0)
                    {
                        indexBuilder.Save(clippedBundleFile.Directory.FullName + @"\" + new FileInfo(bundle.Index.Filename).Name);
                    }
                }

                if (maxlevel >= 0 && level.Level >= maxlevel)
                {
                    break;
                }
            }

            return(0);
        }
        private static byte[] CompressImageNotChange(byte[] data, long maxLength, ref string fileFullName)
        {
            if (data == null || (long)data.Length < maxLength)
            {
                return(data);
            }
            string text = Path.GetExtension(fileFullName);

            if (string.IsNullOrEmpty(text) || (text.ToLower() != ".jpeg" && text.ToLower() != ".bmp" && text.ToLower() != ".png" && text.ToLower() != ".gif" && text.ToLower() != ".jpg"))
            {
                text = ".jpg";
            }
            System.Drawing.Imaging.ImageCodecInfo encoderInfo;
            if (text.ToLower() == ".gif")
            {
                encoderInfo = ImageCompress.GetEncoderInfo("image/gif");
            }
            else
            {
                encoderInfo = ImageCompress.GetEncoderInfo("image/jpeg");
            }
            if (text.ToLower() == ".png")
            {
                fileFullName = fileFullName.Replace(".png", ".jpg");
            }
            System.Drawing.Imaging.Encoder           quality           = System.Drawing.Imaging.Encoder.Quality;
            System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
            double num = 100.0;

            byte[] array = null;
            System.Drawing.Image image = null;
            using (MemoryStream memoryStream = new MemoryStream(data))
            {
                image = System.Drawing.Image.FromStream(memoryStream);
            }
            System.Drawing.Bitmap   bitmap   = new System.Drawing.Bitmap(image.Width, image.Height);
            System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap);
            graphics.DrawImage(image, 0, 0, image.Width, image.Height);
            do
            {
                System.Drawing.Imaging.EncoderParameter encoderParameter = new System.Drawing.Imaging.EncoderParameter(quality, (long)num);
                encoderParameters.Param[0] = encoderParameter;
                using (MemoryStream memoryStream2 = new MemoryStream())
                {
                    try
                    {
                        bitmap.Save(memoryStream2, encoderInfo, encoderParameters);
                        array = memoryStream2.ToArray();
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLog(ex);
                    }
                    memoryStream2.Close();
                }
                if (num < 8.0)
                {
                    break;
                }
                num *= 0.9;
            }while ((long)array.Length > maxLength);
            if (graphics != null)
            {
                graphics.Dispose();
            }
            if (bitmap != null)
            {
                bitmap.Dispose();
            }
            if (image != null)
            {
                image.Dispose();
            }
            return(array);
        }
Beispiel #29
0
 private Encoder(System.Drawing.Imaging.Encoder encoder)
 {
     WrappedEncoder = encoder;
 }
Beispiel #30
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="T:Common.Drawing.Imaging.Encoder" /> class from the specified
 ///     globally unique identifier (GUID). The GUID specifies an image encoder parameter category.
 /// </summary>
 /// <param name="guid">A globally unique identifier that identifies an image encoder parameter category. </param>
 public Encoder(Guid guid)
 {
     WrappedEncoder = new System.Drawing.Imaging.Encoder(guid);
 }