Exemplo n.º 1
2
 System.Drawing.Imaging.ImageFormat getImageFormat(string in_ext)
 {
     System.Drawing.Imaging.ImageFormat if_ret = new System.Drawing.Imaging.ImageFormat(Guid.NewGuid());
     switch (in_ext.ToLower())
     { 
         case "bmp":
             if_ret = System.Drawing.Imaging.ImageFormat.Bmp;
             break;
         case "gif":
             if_ret = System.Drawing.Imaging.ImageFormat.Gif;
             break;
         case "jpg":
             if_ret = System.Drawing.Imaging.ImageFormat.Jpeg;
             break;
         case "ico":
             if_ret = System.Drawing.Imaging.ImageFormat.Icon;
             break;
         case "png":
             if_ret = System.Drawing.Imaging.ImageFormat.Png;
             break;
         case "tif":
             if_ret = System.Drawing.Imaging.ImageFormat.Tiff;
             break;
     }
     return if_ret;
 }
Exemplo n.º 2
0
 public static Stream ImageToStream(Image image, ImageFormat formaw)
 {
     var stream = new MemoryStream();
     image.Save(stream, formaw);
     stream.Position = 0;
     return stream;
 }
Exemplo n.º 3
0
 protected ImageFormatSpec(string extension, string contentType, System.Drawing.Imaging.ImageFormat format)
 {
     Checks.Argument.IsNotEmpty(extension, "extension");
     Checks.Argument.IsNotEmpty(contentType, "contentType");
     Checks.Argument.IsNotNull(format, "format");
     Extension = extension;
     ContentType = contentType;
     Format = format;
 }
Exemplo n.º 4
0
            /// <summary>
            /// 改变图片大小
            /// </summary>
            /// <param name="sourceImage"></param>
            /// <param name="targetWidth"></param>
            /// <param name="targetHeight"></param>
            /// <returns></returns>
            public static Image ChangeImageSize(Image sourceImage, int targetWidth, int targetHeight)
            {
                int width;  //图片最终的宽
                int height; //图片最终的高

                try
                {
                    System.Drawing.Imaging.ImageFormat format = sourceImage.RawFormat;
                    Bitmap   targetPicture = new Bitmap(targetWidth, targetHeight);
                    Graphics g             = Graphics.FromImage(targetPicture);
                    g.Clear(Color.White);

                    //计算缩放图片的大小
                    if (sourceImage.Width > targetWidth && sourceImage.Height <= targetHeight)
                    {
                        width  = targetWidth;
                        height = (width * sourceImage.Height) / sourceImage.Width;
                    }
                    else if (sourceImage.Width <= targetWidth && sourceImage.Height > targetHeight)
                    {
                        height = targetHeight;
                        width  = (height * sourceImage.Width) / sourceImage.Height;
                    }
                    else if (sourceImage.Width <= targetWidth && sourceImage.Height <= targetHeight)
                    {
                        width  = sourceImage.Width;
                        height = sourceImage.Height;
                    }
                    else
                    {
                        width  = targetWidth;
                        height = (width * sourceImage.Height) / sourceImage.Width;
                        if (height > targetHeight)
                        {
                            height = targetHeight;
                            width  = (height * sourceImage.Width) / sourceImage.Height;
                        }
                    }
                    g.DrawImage(sourceImage, (targetWidth - width) / 2, (targetHeight - height) / 2, width, height);
                    sourceImage.Dispose();

                    return(targetPicture);
                }
                catch (Exception ex)
                {
                }
                return(null);
            }
Exemplo n.º 5
0
        public Image ZoomPicture(Image SourceImage, int TargetWidth, int TargetHeight)
        {
            int IntWidth;  //新的图片宽
            int IntHeight; //新的图片高

            try
            {
                System.Drawing.Imaging.ImageFormat format = SourceImage.RawFormat;
                System.Drawing.Bitmap SaveImage           = new System.Drawing.Bitmap(TargetWidth, TargetHeight);
                Graphics g = Graphics.FromImage(SaveImage);
                g.Clear(Color.White);
                if (SourceImage.Width > TargetWidth && SourceImage.Height <= TargetHeight) //宽度比目的图片宽度大,长度比目的图片长度小
                {
                    IntWidth  = TargetWidth;
                    IntHeight = (IntWidth * SourceImage.Height) / SourceImage.Width;
                }
                else if (SourceImage.Width <= TargetWidth && SourceImage.Height > TargetHeight) //宽度比目的图片宽度小,长度比目的图片长度大
                {
                    IntHeight = TargetHeight;
                    IntWidth  = (IntHeight * SourceImage.Width) / SourceImage.Height;
                }
                else if (SourceImage.Width <= TargetWidth && SourceImage.Height <= TargetHeight)  //长宽比目的图片长宽都小
                {
                    IntHeight = SourceImage.Width;
                    IntWidth  = SourceImage.Height;
                }
                else //长宽比目的图片的长宽都大
                {
                    IntWidth  = TargetWidth;
                    IntHeight = (IntWidth * SourceImage.Height) / SourceImage.Width;
                    if (IntHeight > TargetHeight)//重新计算
                    {
                        IntHeight = TargetHeight;
                        IntWidth  = (IntHeight * SourceImage.Width) / SourceImage.Height;
                    }
                }

                g.DrawImage(SourceImage, (TargetWidth - IntWidth) / 2, (TargetHeight - IntHeight) / 2, IntWidth, IntHeight);
                SourceImage.Dispose();

                return(SaveImage);
            }
            catch (Exception ex)
            {
            }

            return(null);
        }
Exemplo n.º 6
0
 public static string ImageFormatToString(System.Drawing.Imaging.ImageFormat imgFormat)
 {
     if (null == imgFormat)
     {
         return("null");
     }
     if (System.Drawing.Imaging.ImageFormat.Bmp.Equals(imgFormat))
     {
         return("Bmp");
     }
     if (System.Drawing.Imaging.ImageFormat.Emf.Equals(imgFormat))
     {
         return("Emf");
     }
     if (System.Drawing.Imaging.ImageFormat.Exif.Equals(imgFormat))
     {
         return("Exif");
     }
     if (System.Drawing.Imaging.ImageFormat.Gif.Equals(imgFormat))
     {
         return("Gif");
     }
     if (System.Drawing.Imaging.ImageFormat.Icon.Equals(imgFormat))
     {
         return("Icon");
     }
     if (System.Drawing.Imaging.ImageFormat.Jpeg.Equals(imgFormat))
     {
         return("Jpeg");
     }
     if (System.Drawing.Imaging.ImageFormat.MemoryBmp.Equals(imgFormat))
     {
         return("MemoryBmp");
     }
     if (System.Drawing.Imaging.ImageFormat.Png.Equals(imgFormat))
     {
         return("Png");
     }
     if (System.Drawing.Imaging.ImageFormat.Tiff.Equals(imgFormat))
     {
         return("Tiff");
     }
     if (System.Drawing.Imaging.ImageFormat.Wmf.Equals(imgFormat))
     {
         return("Wmf");
     }
     return(imgFormat.ToString());
 }
Exemplo n.º 7
0
        public void SavePanelImage(string path)
        {
            Bitmap bitmap = new Bitmap(panel.Width, panel.Height);

            panel.DrawToBitmap(bitmap, new Rectangle(0, 0, panel.Width, panel.Height));

            if (image != null)
            {
                image.Dispose();
            }

            try
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                System.Drawing.Imaging.ImageFormat fmt = System.Drawing.Imaging.ImageFormat.Jpeg;
                switch (Path.GetExtension(path))
                {
                case ".jpg":
                case ".jpeg":
                    fmt = System.Drawing.Imaging.ImageFormat.Jpeg;
                    break;

                case ".png":
                    fmt = System.Drawing.Imaging.ImageFormat.Png;
                    break;

                case ".bmp":
                    fmt = System.Drawing.Imaging.ImageFormat.Bmp;
                    break;

                case ".gif":
                    fmt = System.Drawing.Imaging.ImageFormat.Gif;
                    break;
                }
                bitmap.Save(path, fmt);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                bitmap.Dispose();
            }
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            //inputs
            string slidePath = GetParam(args);//@"C:\Users\AnnaToshiba2\Desktop\WSI\CMU-1.ndpi"; //GetParam(args);// @"C:\Users\AnnaToshiba2\Desktop\WSI\CMU-1.ndpi"; // @"C:\Wsi\tmp232\BIH-249_IIa_FC19560800.ndpi";

            string outputDir     = Path.Combine(Path.GetDirectoryName(slidePath));
            string outpathPrefix = outputDir + "\\" + Path.GetFileNameWithoutExtension(slidePath);

            // parameter
            int   tileSize   = 512;
            int   numThreads = 4;
            float scale      = 0.5f;
            float threshold  = 0.3f;

            // result paths and infos
            System.Drawing.Imaging.ImageFormat sharpnessformat = System.Drawing.Imaging.ImageFormat.Png;
            //Debug Sharpness Map
            string debug_outpath = outpathPrefix + "Debug.png";
            //Sharpness Map by Semaphore System
            string result_outpath = outpathPrefix + ".png";
            //Report with technical details
            string param_outpath = outpathPrefix + ".parameters.csv";

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

            //current params
            var result = new SharpAccessory.VirtualMicroscopy.SlideSharpnessEvaluation().Execute(slidePath, tileSize, numThreads, scale);

            result.MinSharpness = threshold;
            result.MinEdgeCount = 200;

            result.GetDebugBitmap().Save(debug_outpath, sharpnessformat);
            result.GetEvaluationBitmap().Save(result_outpath, sharpnessformat);

            StringBuilder csv = new StringBuilder();

            csv.AppendLine("Wsi Url\t" + slidePath);
            csv.AppendLine("Results Data Prefix\t" + outpathPrefix);
            csv.AppendLine("Sharpness Threshold Value\t" + threshold.ToString());
            csv.AppendLine("Tile Size\t" + tileSize.ToString());
            csv.AppendLine("Scaling\t" + scale.ToString());
            csv.AppendLine("Number of Threads\t" + numThreads.ToString());
            csv.AppendLine("Version SharpAcessoryExtension\t" + "1.0.5357.26298"); //from properties...
            File.WriteAllText(param_outpath, csv.ToString());
        }
Exemplo n.º 9
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (pictureBox1.Image == null)
            {
                MessageBox.Show("请先获取图像!");
            }
            else
            {
                SaveFileDialog saveImageDialog = new SaveFileDialog();
                saveImageDialog.Title  = "图片保存";
                saveImageDialog.Filter = @"jpeg|*.jpg|bmp|*.bmp";
                if (saveImageDialog.ShowDialog() == DialogResult.OK)
                {
                    string fileName = saveImageDialog.FileName.ToString();
                    if (fileName != "" && fileName != null)
                    {
                        string fileExtName = fileName.Substring(fileName.LastIndexOf(".") + 1).ToString();
                        System.Drawing.Imaging.ImageFormat imgformat = null;
                        if (fileExtName != "")
                        {
                            switch (fileExtName)
                            {
                            case "jpg":
                                imgformat = System.Drawing.Imaging.ImageFormat.Jpeg;
                                break;

                            case "bmp":
                                imgformat = System.Drawing.Imaging.ImageFormat.Bmp;
                                break;

                            default:
                                imgformat = System.Drawing.Imaging.ImageFormat.Jpeg;
                                break;
                            }
                            try
                            {
                                Bitmap bit = new Bitmap(pictureBox1.Image);
                                MessageBox.Show(fileName);
                                pictureBox1.Image.Save(fileName, imgformat);
                            }
                            catch
                            {
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 10
0
        private void ButtonSaveAsPicture_Click(object sender, EventArgs e)
        {
            var dialog = new SaveFileDialog();

            dialog.Filter = "Изображения в формате jpeg|*.jpg|Изображения в формате bmp|*.bmp";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                System.Drawing.Imaging.ImageFormat format = null;
                switch (dialog.FilterIndex)
                {
                case 1:     //jpeg
                    format = System.Drawing.Imaging.ImageFormat.Jpeg;
                    break;

                case 2:     //bmp
                    format = System.Drawing.Imaging.ImageFormat.Bmp;
                    break;

                default:     // png
                    format = System.Drawing.Imaging.ImageFormat.Png;
                    break;
                }


                mainBitmap = new Bitmap(pictureBox3.Width, pictureBox3.Height);

                using (Graphics graphics = Graphics.FromImage(mainBitmap))
                {
                    graphics.DrawImage(newBitmap, 0, 0);
                    graphics.DrawImage(listOfBitmap[0],
                                       pictureBox1.Location.X - pictureBox3.Location.X, pictureBox1.Location.Y - pictureBox3.Location.Y);
                    graphics.DrawImage(listOfBitmap[1],
                                       pictureBox2.Location.X - pictureBox3.Location.X, pictureBox2.Location.Y - pictureBox3.Location.Y);
                }

                SaveImage newImage = new SaveImage(mainBitmap);

                mainBitmap.Save(dialog.FileName, format);

                // создаем объект BinaryFormatter
                BinaryFormatter formatter = new BinaryFormatter();
                // получаем поток, куда будем записывать сериализованный объект
                using (FileStream fs = new FileStream(@"D:\testForLab\directoryOne\people.dat", FileMode.OpenOrCreate))
                {
                    formatter.Serialize(fs, newImage);
                }
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// 根据图片扩展名返回图片格式
        /// </summary>
        /// <param name="sExtension"></param>
        /// <returns></returns>
        public static System.Drawing.Imaging.ImageFormat GetImageType(string sExtension)
        {
            System.Drawing.Imaging.ImageFormat format = System.Drawing.Imaging.ImageFormat.MemoryBmp;
            switch (sExtension)
            {
            case ".jpg":
                format = System.Drawing.Imaging.ImageFormat.Jpeg;
                break;

            case ".gif":
                format = System.Drawing.Imaging.ImageFormat.Gif;
                break;
            }

            return(format);
        }
Exemplo n.º 12
0
        public string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                // Convert Image to byte[]
                if (image != null)
                {
                    image.Save(ms, format);
                    byte[] imageBytes = ms.ToArray();

                    // Convert byte[] to Base64 String
                    return(Convert.ToBase64String(imageBytes));
                }
                return(null);
            }
        }
Exemplo n.º 13
0
Arquivo: Form1.cs Projeto: tetla/KCSS
 private void savePicture2(System.Drawing.Imaging.ImageFormat format, DateTime date)
 {
     if (!System.IO.Directory.Exists(textBox3.Text + @"\" + date.ToString("yyyy-MM-dd-HH-mm-ss")))
     {
         System.IO.Directory.CreateDirectory(textBox3.Text + @"\" + date.ToString("yyyy-MM-dd-HH-mm-ss"));
         for (int i = 0; i < 10; i++)
         {
             tmpbmp[i].Save(textBox3.Text + @"\" + date.ToString("yyyy-MM-dd-HH-mm-ss") + @"\" + i.ToString() + "." + format.ToString(), format);
             tmpbmp[i].Dispose();
         }
         if (radioButton5.Checked)
         {
             timer1.Start();
         }
     }
 }
Exemplo n.º 14
0
        void ControlToBitmap1(Control ctrol, string fileName)
        {
            Size      ctrlSize = ctrol.Size;
            Rectangle rect     = new Rectangle(new Point(0, 0), ctrlSize);
            Bitmap    bitmap   = new Bitmap(ctrlSize.Width, ctrlSize.Height);

            ctrol.DrawToBitmap(bitmap, rect);
            Bitmap   result = new Bitmap(ctrlSize.Width, ctrlSize.Height);
            Graphics g      = Graphics.FromImage(result);

            rect.Size = ctrlSize;
            g.DrawImage(bitmap, rect);
            pictureBox1.Image = result;
            System.Drawing.Imaging.ImageFormat format = System.Drawing.Imaging.ImageFormat.Png;
            pictureBox1.Image.Save(fileName, format);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Converts Image to Base64 string
        /// </summary>
        /// <param name="image">A System.Drawing.Image object</param>
        /// <param name="format">Format for saving image to memory stream</param>
        /// <returns>Base64 of an image</returns>
        public static string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
        {
            using (MemoryStream ms = new MemoryStream()) {
                // Convert Image to byte[]
                try {
                    image.Save(ms, format);
                } catch (Exception) {
                    //
                }
                byte[] imageBytes = ms.ToArray();

                // Convert byte[] to Base64 String
                string base64String = Convert.ToBase64String(imageBytes);
                return(base64String);
            }
        }
Exemplo n.º 16
0
        public FileCardExporter(int nLayoutStartIndex, int nLayoutEndIdx, string sExportFolder, bool bOverrideLayoutStringFormat, string sStringFormat,
            System.Drawing.Imaging.ImageFormat eImageFormat)
            : base(nLayoutStartIndex, nLayoutEndIdx)
        {
            if (!sExportFolder.EndsWith(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture)))
            {
                sExportFolder += Path.DirectorySeparatorChar;
            }

            m_sExportFolder = sExportFolder;
            if (!bOverrideLayoutStringFormat)
            {
                m_sStringFormat = sStringFormat;
            }
            m_eImageFormat = eImageFormat;
        }
        public BarcodeModel(
            string barcodeContent,
            System.Drawing.Imaging.ImageFormat imageFormat,
            ZXing.BarcodeFormat barcodeFormat = DEFAULT_BARCODE_FORMAT,
            int widthPx  = defaultWidthPx,
            int heightPx = defaultHeightPx)
        {
            ImageFormat    = imageFormat;
            BarcodeContent = barcodeContent;
            BarcodeFormat  = barcodeFormat;
            WidthPx        = widthPx;
            HeightPx       = heightPx;

            EncodeBarcodeSvg();
            EncodeBarcodeBmp();
        }
Exemplo n.º 18
0
        /// <summary>
        /// 在图片上添加图片水印
        /// </summary>
        /// <param name="path">要打水印的图片路径</param>
        /// <param name="syPicPath">水印图片的路径</param>
        /// <param name="waterPicPath">生成后水印图片存放路径</param>
        public void AddWaterPic(string path, string syPicPath, string filename)
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(path);
            System.Drawing.Imaging.ImageFormat thisFormat = image.RawFormat;

            System.Drawing.Image    waterImage = System.Drawing.Image.FromFile(syPicPath);
            System.Drawing.Graphics g          = System.Drawing.Graphics.FromImage(image);
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.DrawImage(waterImage, new System.Drawing.Rectangle(image.Width - waterImage.Width, image.Height - waterImage.Height, waterImage.Width, waterImage.Height), 0, 0, waterImage.Width, waterImage.Height, System.Drawing.GraphicsUnit.Pixel);
            g.Dispose();

            image.Save(filename, thisFormat);
            image.Dispose();
        }
Exemplo n.º 19
0
        public static BitmapImage ToBitmapSource(this System.Drawing.Bitmap bitmap, System.Drawing.Imaging.ImageFormat fmt)
        {
            using var memory = new MemoryStream();
            bitmap.Save(memory, fmt);
            memory.Position = 0;

            var bm = new BitmapImage();

            bm.BeginInit();
            bm.StreamSource = memory;
            bm.CacheOption  = BitmapCacheOption.OnLoad;
            bm.EndInit();
            bm.Freeze();

            return(bm);
        }
Exemplo n.º 20
0
        /// <summary>
        /// bitmap转base64
        /// </summary>
        public string BitmapToBase64(Bitmap bimap, System.Drawing.Imaging.ImageFormat format)
        {
            var bast64Result = string.Empty;

            using (MemoryStream ms = new MemoryStream())
            {
                bimap.Save(ms, format);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                bast64Result = Convert.ToBase64String(arr);
                ms.Close();
            }

            return(bast64Result);
        }
Exemplo n.º 21
0
        void ControlToBitmap(Control ctrol)
        {
            Size      ctrlSize = ctrol.Size;
            Rectangle rect     = new Rectangle(new Point(0, 0), ctrlSize);
            Bitmap    bitmap   = new Bitmap(ctrlSize.Width, ctrlSize.Height);

            ctrol.DrawToBitmap(bitmap, rect);
            Bitmap   result = new Bitmap(ctrlSize.Width, ctrlSize.Height);
            Graphics g      = Graphics.FromImage(result);

            rect.Size = ctrlSize;
            g.DrawImage(bitmap, rect);
            //picResult.Image = result;
            System.Drawing.Imaging.ImageFormat format = System.Drawing.Imaging.ImageFormat.Jpeg;
            //picResult.Image.Save("D://test_image.png",format);
        }
Exemplo n.º 22
0
 public ImageFormat(System.Drawing.Imaging.ImageFormat imageFormat)
 {
     // convert imageformat to string
     if (imageFormat == System.Drawing.Imaging.ImageFormat.Jpeg)
     {
         _imageFormat = "jpg";
     }
     else if (imageFormat == System.Drawing.Imaging.ImageFormat.Bmp)
     {
         _imageFormat = "bmp";
     }
     else if (imageFormat == System.Drawing.Imaging.ImageFormat.Png)
     {
         _imageFormat = "png";
     }
 }
Exemplo n.º 23
0
        public static string GetHatchRectangleAsDataString(
            int iLegendPattern
            , System.Drawing.Color colFC
            , System.Drawing.Color colHB
            , System.Drawing.Color colHL
            , System.Drawing.Imaging.ImageFormat format
            )
        {
            //pbRectangle.Image = SimpleHtmlToPdfConverter.Draw.DrawHatchRectangle_Img(9, colFC, colHB, colHL);
            //pbRectangle.Image = SimpleHtmlToPdfConverter.Draw.DrawHatchRectangle_Img(35, colFC, colHB, colHL);
            //pbRectangle.Image = SimpleHtmlToPdfConverter.Draw.DrawHatchRectangle_Img(69, colFC, colHB, colHL);

            string str = DrawHatchRectangleToBase64String(iLegendPattern, colFC, colHB, colHL, format);

            return("data:" + GetMimeType(format) + ";base64," + str);
        }
Exemplo n.º 24
0
        } // End Sub Main

        // SaveAImage(model, @"test.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
        public static void SaveAImage(DxfModel model, string path, System.Drawing.Imaging.ImageFormat fmt)
        {
            // Convert the CAD drawing to a bitmap.
            System.Drawing.Bitmap bitmap = ImageExporter.CreateAutoSizedBitmap(
                model,
                Matrix4D.Identity,
                GraphicsConfig.WhiteBackgroundCorrectForBackColor,
                System.Drawing.Drawing2D.SmoothingMode.HighQuality,
                new System.Drawing.Size(500, 400)
                );

            // Send the bitmap to the client.
            // context.Response.ContentType = "image/jpeg";
            // bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            bitmap.Save(path, fmt);
        } // End Sub SaveAImage
Exemplo n.º 25
0
        private string GetImageExtension(System.Drawing.Imaging.ImageFormat format)
        {
            string ext = ".jpg";

            System.Reflection.PropertyInfo[] pi = typeof(System.Drawing.Imaging.ImageFormat).GetProperties();
            foreach (System.Reflection.PropertyInfo item in pi)
            {
                if (item.PropertyType == typeof(System.Drawing.Imaging.ImageFormat) &&
                    format.Guid.ToString() == ((System.Drawing.Imaging.ImageFormat)item.GetValue(format)).Guid.ToString())
                {
                    ext = item.Name.ToLower();
                    break;
                }
            }
            return("." + ext);
        }
        // sUri of the form  "pack://application:,,,/myPack;component/Images/image.jpg"
        private byte[] GetBufferImage(string sUri, esriTextureCompressionType compressionType)
        {
            System.Drawing.Imaging.ImageFormat format = (compressionType == esriTextureCompressionType.CompressionJPEG) ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Bmp;

            Uri uri = new Uri(sUri, UriKind.RelativeOrAbsolute);
            StreamResourceInfo info = Application.GetResourceStream(uri);

            System.Drawing.Image image = System.Drawing.Image.FromStream(info.Stream);

            MemoryStream memoryStream = new MemoryStream();

            image.Save(memoryStream, format);
            byte[] imageBuffer = memoryStream.ToArray();

            return(imageBuffer);
        }
Exemplo n.º 27
0
        void InsertNewProduct(string name, string description, string price, Image image, string mark, string category)
        {
            OleDbConnection connection = new OleDbConnection(connstring);

            try
            {
                connection.Open();

                OleDbCommand   command   = new OleDbCommand("INSERT INTO [" + category + "](Название, Описание, Цена, Изображение, ID_Марки) VALUES(?, ?, ?, ?, ?)", connection);
                OleDbParameter parameter = new OleDbParameter("Название", OleDbType.VarChar);
                parameter.Value = name;
                command.Parameters.Add(parameter);

                OleDbParameter parameter1 = new OleDbParameter("Описание", OleDbType.VarChar);
                parameter1.Value = description;
                command.Parameters.Add(parameter1);

                OleDbParameter parameter2 = new OleDbParameter("Цена", OleDbType.Integer);
                parameter2.Value = Convert.ToInt32(price);
                command.Parameters.Add(parameter2);

                MemoryStream memoryStream = new MemoryStream();
                System.Drawing.Imaging.ImageFormat format = image.RawFormat;
                image.Save(memoryStream, format);
                OleDbParameter parameter3 = new OleDbParameter("Изображение", OleDbType.Binary);
                parameter3.Value = memoryStream.ToArray();
                command.Parameters.Add(parameter3);

                OleDbParameter parameter4 = new OleDbParameter("ID_Марки", OleDbType.Integer);
                parameter4.Value = Convert.ToInt32(getID_Марки(mark));
                command.Parameters.Add(parameter4);

                command.ExecuteNonQuery();

                MetroFramework.MetroMessageBox.Show(this, "Запись успешно добавлена", "Доавление нового товара");
                UC.flowLayoutPanel1.Controls.Clear();
                UC.LoadProducts(UC.lNameCategory.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                connection.Close();
            }
        }
Exemplo n.º 28
0
        private void btnOK_Click_1(object sender, EventArgs e)
        {
            OleDbConnection connection = new OleDbConnection(connstring);

            try
            {
                connection.Open();

                OleDbCommand   command   = new OleDbCommand("INSERT INTO Корзина(ID_Пользователя, Название, Описание, Цена, Изображение) VALUES(?,?,?,?,?)", connection);
                OleDbParameter parameter = new OleDbParameter("ID_Пользователя", OleDbType.Integer);
                parameter.Value = Convert.ToInt32(getID_Пользователя());
                command.Parameters.Add(parameter);

                OleDbParameter parameter1 = new OleDbParameter("Название", OleDbType.VarChar);
                parameter1.Value = Name;
                command.Parameters.Add(parameter1);

                OleDbParameter parameter2 = new OleDbParameter("Описание", OleDbType.VarChar);
                parameter2.Value = Description;
                command.Parameters.Add(parameter2);

                OleDbParameter parameter3 = new OleDbParameter("Цена", OleDbType.Integer);
                parameter3.Value = Convert.ToInt32(Price);
                command.Parameters.Add(parameter3);

                Image image = pictureBox1.Image;

                MemoryStream memoryStream = new MemoryStream();
                System.Drawing.Imaging.ImageFormat format = pictureBox1.Image.RawFormat;
                image.Save(memoryStream, format);
                OleDbParameter parameter4 = new OleDbParameter("Изображение", OleDbType.Binary);
                parameter4.Value = memoryStream.ToArray();
                command.Parameters.Add(parameter4);

                command.ExecuteNonQuery();

                MetroFramework.MetroMessageBox.Show(this, "Товар добавлен в корзину!", "Корзина");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                connection.Close();
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// 百度识别(限次数)
        /// </summary>
        /// <returns></returns>
        public static string BaiduTextOrc(Image image)
        {
            try
            {
                var        location = "";
                HttpHelper httper   = new HttpHelper();
                HttpItem   item2    = new HttpItem()
                {
                    URL = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY + "&",
                };
                var res1    = httper.GetHtml(item2);
                var jobject = JObject.Parse(res1.Html);
                var jtoken  = JToken.Parse(jobject.ToString());
                var token1  = jtoken["access_token"].ToString();
                System.Drawing.Imaging.ImageFormat format = image.RawFormat;
                MemoryStream mqs = new MemoryStream();

                image.Save(mqs, format);
                var            d          = mqs.ToArray();
                var            strbaser64 = Convert.ToBase64String(d);
                string         host       = "https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token=" + token1;
                Encoding       encoding   = Encoding.Default;
                HttpWebRequest request    = (HttpWebRequest)WebRequest.Create(host);
                request.Method      = "post";
                request.ContentType = "application/x-www-form-urlencoded";
                request.KeepAlive   = true;
                String str    = "image=" + HttpUtility.UrlEncode(strbaser64);
                byte[] buffer = encoding.GetBytes(str);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader    reader   = new StreamReader(response.GetResponseStream(), Encoding.Default);
                string          result   = reader.ReadToEnd();
                var             job      = JObject.Parse(result.ToString());
                if (!result.ToString().Contains("limit"))
                {
                    var words_result = job["words_result"];
                    var jot          = JToken.Parse(words_result.ToString());
                    location = jot[0]["words"].ToString();
                }
                return(location);
            }
            catch (Exception ex)
            {
                return("");
            }
        }
Exemplo n.º 30
0
 public static byte[] CreateThumbnailImage(byte[] img, System.Drawing.Imaging.ImageFormat thumbFormat, int thumbWidth, int thumbHeight)
 {
     using (var imgStream = new MemoryStream(img))
     {
         using (var srcImage = System.Drawing.Image.FromStream(imgStream))
         {
             using (var thmbImage = srcImage.GetThumbnailImage(thumbWidth, thumbHeight, () => true, System.IntPtr.Zero))
             {
                 using (var thmbStream = new MemoryStream())
                 {
                     thmbImage.Save(thmbStream, thumbFormat);
                     return(thmbStream.ToArray());
                 }
             }
         }
     }
 }
Exemplo n.º 31
0
        private void menu_SaveToImage_Click(object sender, System.EventArgs e)
        {
            Bitmap bmp = ViewCtrl1.PrintToImage();

            if (bmp == null)
            {
                MessageBox.Show("Diagram is empty", "Nothing to save", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            SaveFileDialog sfd    = new SaveFileDialog();
            string         filter = String.Empty;

            for (int i = 0; i < formats.Length; i++)
            {
                filter += "|" + formats[i].descr + "(*." + formats[i].ext + ")|*." + formats[i].ext;
            }
            sfd.Filter        = filter.Substring(1);
            sfd.FilterIndex   = 0;
            sfd.AddExtension  = true;
            sfd.Title         = "Save To Image...";
            sfd.ValidateNames = true;
            sfd.FileName      = ViewCtrl1.Curr.name;


            if (sfd.ShowDialog(this) == DialogResult.OK)
            {
                string ext = System.IO.Path.GetExtension(sfd.FileName).ToLower();
                System.Drawing.Imaging.ImageFormat format = null;
                for (int i = 0; i < formats.Length; i++)
                {
                    if (ext.Equals("." + formats[i].ext))
                    {
                        format = formats[i].format;
                    }
                }
                if (format != null)
                {
                    bmp.Save(sfd.FileName, format);
                }
                else
                {
                    MessageBox.Show("Unknown extension: " + ext, "Cannot save", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
Exemplo n.º 32
0
        public static string GraphicToBase64(Image aGraphic, System.Drawing.Imaging.ImageFormat format)
        {
            using (MemoryStream vStream = new MemoryStream())
            {
                using (Bitmap bitmap = new Bitmap(aGraphic)) // 解决GDI+ 中发生一般性错误,因为该文件仍保留锁定对于对象的生存期
                {
                    bitmap.Save(vStream, format);            //  System.Drawing.Imaging.ImageFormat.Bmp
                }

                byte[] vArr = new byte[vStream.Length];
                vStream.Position = 0;
                vStream.Read(vArr, 0, (int)vStream.Length);
                vStream.Close();
                vStream.Dispose();
                return(Convert.ToBase64String(vArr));
            }
        }
Exemplo n.º 33
0
 /// <summary>
 /// Sets the output file type based on the file extension given.
 /// </summary>
 /// <param name="outPath">Output file path</param>
 static void SetOutputFileType(string outPath)
 {
     outPath = outPath.ToLower();
     html    = (outPath.EndsWith(".htm") || outPath.EndsWith(".html"));
     if (html)
     {
         if (overlap != 1)
         {
             Log(LogType.Warning, "Overlap is not supported for HTML outputs.");
         }
         return;
     }
     else if (outPath.EndsWith(".bmp"))
     {
         outputFmt = ImageFormat.Bmp;
     }
     else if (outPath.EndsWith(".gif"))
     {
         outputFmt = ImageFormat.Gif;
     }
     else if (outPath.EndsWith(".jpg"))
     {
         outputFmt = ImageFormat.Jpeg;
     }
     else if (outPath.EndsWith(".jpeg"))
     {
         outputFmt = ImageFormat.Jpeg;
     }
     else if (outPath.EndsWith(".png"))
     {
         outputFmt = ImageFormat.Png;
     }
     else if (outPath.EndsWith(".tif"))
     {
         outputFmt = ImageFormat.Tiff;
     }
     else if (outPath.EndsWith(".tiff"))
     {
         outputFmt = ImageFormat.Tiff;
     }
     else
     {
         Log(LogType.Warning, "Could not detect output file type. Defaulting to BMP.");
         outputFmt = ImageFormat.Bmp;
     }
 }
 /// <summary>
 /// Save Methods
 /// </summary>
 public bool SaveAsFile(string strFilePath, int width, int height,
                        System.Drawing.Imaging.ImageFormat imageFormat)
 {
     if ((null == strFilePath) || ("" == strFilePath))
     {
         return(false);
     }
     if (strFilePath.IndexOf('.') == -1)
     {
         strFilePath = strFilePath + "." + imageFormat.ToString();
     }
     System.Drawing.Rectangle MyRect   = new System.Drawing.Rectangle(0, 0, width, height);
     System.Drawing.Bitmap    MyBitmap = new System.Drawing.Bitmap(width, height);
     Draw(Graphics.FromImage(MyBitmap), MyRect);
     MyBitmap.Save(strFilePath, imageFormat);
     return(true);
 }
Exemplo n.º 35
0
 public ImageHandler(string name, Stream stream)
 {
     _filename = name;
     original_image = System.Drawing.Image.FromStream(stream);
     _final_image = new System.Drawing.Bitmap(stream);
     _currentType = name.Substring(name.LastIndexOf('.')).ToLower();
     switch (_currentType) {
         case ".jpg":
         case ".jpeg":
             _format = System.Drawing.Imaging.ImageFormat.Jpeg;
             break;
         case ".bmp":
             _format = System.Drawing.Imaging.ImageFormat.Bmp;
             break;
         case ".png":
             _format = System.Drawing.Imaging.ImageFormat.Png;
             break;
         case ".gif":
             _format = System.Drawing.Imaging.ImageFormat.Gif;
             break;
     }
 }
Exemplo n.º 36
0
        private void MakeThumbnail()
        {
            using (Image img = new Bitmap(_filePath))
            {
                Size newSize = GenerateImageDimensions(img.Width, img.Height, _maxWidth, _maxHeight);
                int imgWidth = newSize.Width;
                int imgHeight = newSize.Height;

                // create the thumbnail image
                using (Image img2 =
                          img.GetThumbnailImage(imgWidth, imgHeight,
                          new Image.GetThumbnailImageAbort(Abort),
                          IntPtr.Zero))
                {

                    using (Graphics g = Graphics.FromImage(img2)) // Create Graphics object from original Image
                    {
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

                        //BMP 0, JPEG 1 , GIF 2 , TIFF 3, PNG 4
                        System.Drawing.Imaging.ImageCodecInfo codec;

                        switch (Path.GetExtension(_filePath))
                        {
                            case ".gif":
                                codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[2];
                                ImageFormat = System.Drawing.Imaging.ImageFormat.Gif;
                                MimeType = "image/gif";
                                break;

                            case ".png":
                                codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[4];
                                ImageFormat = System.Drawing.Imaging.ImageFormat.Png;
                                MimeType = "image/png";
                                break;

                            default: //jpg
                                codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
                                ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
                                MimeType = "image/jpg";
                                break;
                        }

                        //Set the parameters for defining the quality of the thumbnail... here it is set to 100%
                        System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
                        eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);

                        //Now draw the image on the instance of thumbnail Bitmap object
                        g.DrawImage(img, new Rectangle(0, 0, img2.Width, img2.Height));

                        MemoryStream ms = new MemoryStream();
                        img2.Save(ms, codec, eParams);
                        ImageBytes = new byte[ms.Length];
                        ImageBytes = ms.ToArray();

                        ms.Close();
                        ms.Dispose();
                    }
                }
            }
        }
Exemplo n.º 37
0
        private void MainForm_Load(object sender, System.EventArgs e)
        {
            try
            {
                this.SuppressThirdPartyWarningMessage = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["SuppressThirdPartyImageConverterWarningMessage"]);
                this.ExportLocationTextBox.Text = AppDomain.CurrentDomain.BaseDirectory;
                this.KeyPreview = true;
                ThirdPartyImageConverterPath = System.Configuration.ConfigurationManager.AppSettings["ThirdPartyImageConverter"];

                if (ThirdPartyImageConverterPath.StartsWith("\\"))
                {
                    ThirdPartyImageConverterPath = AppDomain.CurrentDomain.BaseDirectory + ThirdPartyImageConverterPath;
                }
                AutoOpenDestinationFolder = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["AutoOpenDestinationFolder"]);
                PromptForDestinationFolder = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["PromptForDestinationFolder"]);
                Outline.Width = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TileOutlineWidth"]);
                DistanceBetweenTiles = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["DistanceBetweenFrames"]);
                MakeBackgroundTransparent = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["ExportedOptionsMakeBackgroundTransparent"]);

                Dictionary<string, System.Drawing.Imaging.ImageFormat> formats = new Dictionary<string, System.Drawing.Imaging.ImageFormat>();
                formats.Add("png", System.Drawing.Imaging.ImageFormat.Png);
                formats.Add("bmp", System.Drawing.Imaging.ImageFormat.Bmp);
                formats.Add("gif", System.Drawing.Imaging.ImageFormat.Gif);
                formats.Add("tiff", System.Drawing.Imaging.ImageFormat.Tiff);
                formats.Add("jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
                formats.Add("jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                ExportFormat = formats[System.Configuration.ConfigurationManager.AppSettings["ExportedOptionsFileFormat"].Replace(".", "").ToLower()];
            }
            catch (Exception ex)
            {
                ForkandBeard.Logic.ExceptionHandler.HandleException(ex, "*****@*****.**");
            }
        }
Exemplo n.º 38
0
        private void btn_Select_Click(object sender, EventArgs e)
        {
            DialogResult dRes;
            OpenFileDialog opnFileDlg = new OpenFileDialog();
            opnFileDlg.Filter = "Picture files (*.jpg)|*.jpg|All files (*.*)|*.* ";
            opnFileDlg.FilterIndex = 2;
            opnFileDlg.FileName = "*.*"; //PathImport + "\\" + btnSelectFile.m_InputTextBox.Text;
            opnFileDlg.RestoreDirectory = true;
            dRes = opnFileDlg.ShowDialog();
            if (dRes == DialogResult.OK)
            {
                Image OrgImage = new Bitmap(opnFileDlg.FileName);
                //if ((OrgImage.Width <= MAX_PICTURE_WIDTH) && (OrgImage.Height <= MAX_PICTURE_HEIGHT))
                //{
                //    Picture.Image = OrgImage;
                //}
                //else
                //{

                //}

                ResizeImage_Form resdlg = new ResizeImage_Form(OrgImage);
                if (resdlg.ShowDialog() == DialogResult.OK)
                {
                    this.Image = (Image)resdlg.m_NewImage.Clone();
                    imgFormat = this.Image.RawFormat;
                }
                else
                {
                    this.Image = OrgImage;
                    imgFormat = this.Image.RawFormat;
                }
                pic.SizeMode = PictureBoxSizeMode.Zoom;
            }
        }
Exemplo n.º 39
0
        /// <summary>
        /// The entry point of the handler. Reads settings and request and processes the image or retrieves it from cache
        /// </summary>
        /// <param name="context">The context in which the request is done</param>
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                //Store the context object for other procedures
                _context = context;

                //Get the format and if only format are alowed and one is not given we can stop here. Also scheck if the format actually exists in the settings
                _format = (_context.Request["format"] ?? string.Empty).ToLower();
                if ((string.IsNullOrEmpty(_format) && Settings.FormatsOnly) || (!string.IsNullOrEmpty(_format) && !Settings.Formats.Any(f => f.Key.ToLower() == _format)))
                {
                    WriteNotFoundResponse();
                    return;
                }

                //resolve the requested file from the servekmage request. (Supports old style serveimage.ashx and new style /image.*)
                if (_context.Request.Url.AbsolutePath.StartsWith("/serveimage.ashx"))
                {
                    _requestedFile = _context.Request["path"];
                }
                else
                {
                    _requestedFile = _context.Request.Url.AbsolutePath.Substring(Settings.PathPrefix.Length); //new
                }

                //decode the requested file
                _requestedFile = HttpUtility.UrlDecode(_requestedFile);

                //return 404 if the requested file is null or empty
                if (string.IsNullOrEmpty(_requestedFile))
                {
                    WriteNotFoundResponse();
                    return;
                }

                //Resolve the requested category or use the default
                _category = (_context.Request["cat"] ?? Settings.DefaultCategory).ToLower();

                //if a category was given and valid, we add the prefix belonging to the cateogry to the requested file
                //otherwise If no category could be determined: return a 404
                if (Settings.Categories.ContainsKey(_category))
                {
                    var prefix = Settings.Categories[_category];
                    if (!_requestedFile.StartsWith(prefix))
                    {
                        _requestedFile = prefix + _requestedFile;
                    }
                }
                else
                {
                    WriteNotFoundResponse();
                    return;
                }

                //Resolve the mimetype of the original file and set the contenttype to default to text/html for now.
                var mimeType = Web.GetMimeType(_requestedFile).ToLower();
                _context.Response.ContentType = "text/html";

                //Check if the cachepath exists
                Settings.CheckCachePath(context);

                //If the requested file is not a local image we return the file as download (e.g. a document)
                if (!Settings.Categories[_category].StartsWith("http") && !mimeType.StartsWith("image"))
                {
                    _cacheFile = _context.Server.MapPath(_requestedFile);
                    _cacheFileInfo = new FileInfo(_cacheFile);
                    _serveAsDownload = true;
                    ServeCacheFile();
                    //and so we can stop here
                    return;
                }

                //Fetching more request params
                _enableCache = bool.Parse(_context.Request["cache"] ?? "true");
                _retina = bool.Parse(_context.Request["retina"] ?? "false");
                _sizeFactor = _retina ? 2 : 1;
                _quality = int.Parse(_context.Request["q"] ?? Settings.Quality.ToString());

                //Resolve the image manipulation params using the format or the values from the querystring.
                var format = new NameValueCollection();
                if (Settings.Formats.ContainsKey(_format)) { format = Settings.Formats[_format]; }
                _actions = (format["action"] ?? _context.Request["action"] ?? string.Empty).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                _serveAsDownload = bool.Parse(format["download"] ?? _context.Request["download"] ?? "false");
                _constrainProportions = bool.Parse(format["constrain"] ?? _context.Request["constrain"] ?? "true");
                _noUpSizing = bool.Parse(format["noupsizing"] ?? _context.Request["noupsizing"] ?? "false");
                _cX = int.Parse(format["cx"] ?? _context.Request["cx"] ?? "0") * _sizeFactor;
                _cY = int.Parse(format["cy"] ?? _context.Request["cy"] ?? "0") * _sizeFactor;
                _cW = int.Parse(format["cw"] ?? _context.Request["cw"] ?? "0") * _sizeFactor;
                _cH = int.Parse(format["ch"] ?? _context.Request["ch"] ?? "0") * _sizeFactor;
                _rW = int.Parse(format["rw"] ?? _context.Request["rw"] ?? "0") * _sizeFactor;
                _rH = int.Parse(format["rh"] ?? _context.Request["rh"] ?? "0") * _sizeFactor;
                _fW = int.Parse(format["fw"] ?? _context.Request["fw"] ?? "0") * _sizeFactor;
                _fH = int.Parse(format["fh"] ?? _context.Request["fh"] ?? "0") * _sizeFactor;
                _bW = int.Parse(format["bw"] ?? _context.Request["bw"] ?? "0") * _sizeFactor;
                _bH = int.Parse(format["bh"] ?? _context.Request["bh"] ?? "0") * _sizeFactor;
                _mW = int.Parse(format["mw"] ?? _context.Request["mw"] ?? "0") * _sizeFactor;
                _mH = int.Parse(format["mh"] ?? _context.Request["mh"] ?? "0") * _sizeFactor;
                _bColor = _context.Request[format["bcolor"] ?? "bcolor"] ?? "ffffff";

                //Check if it is an external file
                _isExternalFile = (_requestedFile.StartsWith("http"));

                //If not external: get the local file and run some checks
                if (!_isExternalFile)
                {
                    if (MediaProvider != null)
                    {
                        var width = (_rW > 0 ? _rW : (_fW > 0 ? _fW : 0)) * (!_retina && Settings.AlwaysUseRetinaAsSource ? 2 : 1);
                        var height = (_rH > 0 ? _rH : (_fH > 0 ? _fH : 0)) * (!_retina && Settings.AlwaysUseRetinaAsSource ? 2 : 1);
                        _mediaFile = MediaProvider(_requestedFile, width, height);
                    }
                    else
                    {
                        _mediaFile = _context.Server.MapPath(_requestedFile);
                    }
                    if (string.IsNullOrEmpty(_mediaFile) || !File.Exists(_mediaFile))
                    {
                        WriteNotFoundResponse();
                        return;
                    }
                    _mediaFileInfo = new FileInfo(_mediaFile);
                }

                //Convert to jpg (or png if cutout is used) UNLESS overruled by config
                if (!_isExternalFile || new Uri(_requestedFile, UriKind.RelativeOrAbsolute).IsFile)
                {
                    var ext = Path.GetExtension(_requestedFile);
                    if (_actions.Contains("cutout") && ext != ".png")
                    {
                        _convertTo = System.Drawing.Imaging.ImageFormat.Png;
                    }
                    else if (ext != ".jpg" && ext != ".jpeg" && !Settings.NoConversion)
                    {
                        _convertTo = System.Drawing.Imaging.ImageFormat.Jpeg;
                    }
                }

                //Determine the cachefile
                _cacheFile = GetCacheFile();

                if (_enableCache)
                {
                    // Is this request cached on the client?
                    if (CheckHttpCache())
                    { return; }

                    // Do we have the requested file in cache?
                    //media = GetFromCache();
                    if (CheckDiskCache())
                    { return; }
                }

                // Not in cache it is so loading media file
                ImageTransformer media;
                if (_isExternalFile)
                {
                    media = new ImageTransformer(_requestedFile, _quality);
                }
                else
                {
                    media = new ImageTransformer(_mediaFile, _quality);
                }

                //Convert if needed
                if (_convertTo != null)
                {
                    media.ConvertToImageFormat(_convertTo);
                }

                // Executing actions
                // Maximum amount of actions is 5, to prevent memory issues
                if (_actions != null && _actions.Length > 0 && _actions.Length <= 5)
                {
                    foreach (String action in _actions)
                    {
                        switch (action)
                        {
                            case "resize":
                                media.Resize(new System.Drawing.Size(_rW, _rH), _constrainProportions, _noUpSizing, _mW, _mH);
                                break;
                            case "crop":
                                media.Crop(new System.Drawing.Rectangle(new System.Drawing.Point(_cX, _cY), new System.Drawing.Size(_cW, _cH)));
                                break;
                            case "fit":
                                media.Fit(new System.Drawing.Size(_fW, _fH), _noUpSizing, _mW, _mH);
                                break;
                            case "box":
                                System.Drawing.Color bgColor;
                                if (_bColor == "transparent") bgColor = System.Drawing.Color.Transparent;
                                else bgColor = System.Drawing.ColorTranslator.FromHtml("#" + _bColor);
                                media.Box(new System.Drawing.Size(_bW, _bH), bgColor, _noUpSizing, _mW, _mH);
                                break;
                            case "grayscale":
                                media.Grayscale();
                                break;
                            case "sepia":
                                media.Sepia();
                                break;
                        }
                    }
                }
                // Cache it!
                ToCache(media);
                media.Dispose();
                // Serve it!
                ServeCacheFile();
            }
            catch (System.IO.FileNotFoundException ex)
            {
                WriteNotFoundResponse();
                return;
            }
        }
Exemplo n.º 40
0
 public FormatDescr( System.Drawing.Imaging.ImageFormat format, string ext, string descr )
 {
     this.format = format;
     this.ext = ext;
     this.descr = descr;
 }
Exemplo n.º 41
0
        private void SelectFormatMenuItem_Click(object sender, EventArgs e)
        {
            foreach (var imageFormatItem in _imageFormatItems)
                imageFormatItem.Checked = false;
            ((ToolStripMenuItem)sender).Checked = true;
            System.Reflection.PropertyInfo propertyinfo = typeof(System.Drawing.Imaging.ImageFormat).GetProperty(sender.ToString());
            _imageFormat = (System.Drawing.Imaging.ImageFormat)propertyinfo.GetValue(null, null);
            //switch (sender.ToString())
            //{
            //    case "BMP":
            //        _bmpMenuItem.Checked = true;
            //        _jpegMenuItem.Checked = false;
            //        _imageFormat = System.Drawing.Imaging.ImageFormat.Bmp;
            //        break;
            //    case "JPEG":
            //    default:
            //        _jpegMenuItem.Checked = true;
            //        _bmpMenuItem.Checked = false;
            //        _imageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
            //        break;

            //}
        }
Exemplo n.º 42
0
        private void InitializeComponent()
        {
            backgroundWorker = new System.ComponentModel.BackgroundWorker();
            backgroundWorker.WorkerReportsProgress = true;
            backgroundWorker.DoWork += backgroundWorker_DoWork;
            backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;

            _trayIcon = new NotifyIcon
            {
                BalloonTipIcon = ToolTipIcon.Info,
                BalloonTipText = "Background refreshed",
                BalloonTipTitle = "Unsplasher",
                Icon = Resources.TrayIconWhite
            };

            _trayIconContextMenu = new ContextMenuStrip();
            _closeMenuItem = new ToolStripMenuItem();
            _refreshMenuItem = new ToolStripMenuItem();
            _jpegMenuItem = new ToolStripMenuItem();
            _bmpMenuItem = new ToolStripMenuItem();
            _30minIntervalMenuItem = new ToolStripMenuItem();
            _60minIntervalMenuItem = new ToolStripMenuItem();
            _4hourIntervalMenuItem = new ToolStripMenuItem();
            _2hourIntervalMenuItem = new ToolStripMenuItem();
            _startUpIntervalMenuItem = new ToolStripMenuItem();
            _trayIconContextMenu.SuspendLayout();

            _imageFormatItems = new ToolStripMenuItem[]
            {
                _bmpMenuItem,
                _jpegMenuItem

            };

            _intervalItems = new ToolStripMenuItem[]
            {
                _30minIntervalMenuItem,
                _60minIntervalMenuItem,
                _2hourIntervalMenuItem,
                _4hourIntervalMenuItem,
                _startUpIntervalMenuItem
            };

            _imageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
            _source = new List<string>();

            _trayIconContextMenu.Items.AddRange(_imageFormatItems);
            _trayIconContextMenu.Items.Add(new ToolStripSeparator());
            _trayIconContextMenu.Items.AddRange(_intervalItems);
            _trayIconContextMenu.Items.Add(new ToolStripSeparator());
            _trayIconContextMenu.Items.Add(_refreshMenuItem);
            _trayIconContextMenu.Items.Add(_closeMenuItem);

            _trayIconContextMenu.Name = "_trayIconContextMenu";
            //_trayIconContextMenu.Size = new Size(161, 200);

            _closeMenuItem.Name = "_closeMenuItem";
            _closeMenuItem.Size = new Size(161, 50);
            _closeMenuItem.Text = "Exit";
            _closeMenuItem.Click += CloseMenuItem_Click;

            _refreshMenuItem.Name = "Refresh";
            _refreshMenuItem.Size = new Size(161, 50);
            _refreshMenuItem.Text = "Refresh";
            _refreshMenuItem.Click += RefreshMenuItemClick;

            _bmpMenuItem.Name = "_bmpMenuItem";
            _bmpMenuItem.Size = new Size(161, 50);
            _bmpMenuItem.Text = "Bmp";
            _bmpMenuItem.Click += SelectFormatMenuItem_Click;

            _jpegMenuItem.Name = "_jpegMenuItem";
            _jpegMenuItem.Size = new Size(161, 50);
            _jpegMenuItem.Text = "Jpeg";
            _jpegMenuItem.Checked = true;
            _jpegMenuItem.Click += SelectFormatMenuItem_Click;

            _30minIntervalMenuItem.Name = "_30minIntervalMenuItem";
            _30minIntervalMenuItem.Size = new Size(161, 50);
            _30minIntervalMenuItem.Text = "30 Min";
            _30minIntervalMenuItem.Checked = true;
            _30minIntervalMenuItem.Click += SelectIntervalMenuItem_Click;

            _60minIntervalMenuItem.Name = "_60minIntervalMenuItem";
            _60minIntervalMenuItem.Size = new Size(161, 50);
            _60minIntervalMenuItem.Text = "60 Min";
            _60minIntervalMenuItem.Click += SelectIntervalMenuItem_Click;

            _2hourIntervalMenuItem.Name = "_2hourIntervalMenuItem";
            _2hourIntervalMenuItem.Size = new Size(161, 50);
            _2hourIntervalMenuItem.Text = "2 Hour";
            _2hourIntervalMenuItem.Click += SelectIntervalMenuItem_Click;

            _4hourIntervalMenuItem.Name = "_4hourIntervalMenuItem";
            _4hourIntervalMenuItem.Size = new Size(161, 50);
            _4hourIntervalMenuItem.Text = "4 Hour";
            _4hourIntervalMenuItem.Click += SelectIntervalMenuItem_Click;

            _startUpIntervalMenuItem.Name = "_startUpIntervalMenuItem";
            _startUpIntervalMenuItem.Size = new Size(161, 50);
            _startUpIntervalMenuItem.Text = "Login";
            _startUpIntervalMenuItem.Click += SelectIntervalMenuItem_Click;

            _trayIconContextMenu.ResumeLayout(false);
            _trayIcon.ContextMenuStrip = _trayIconContextMenu;
        }
Exemplo n.º 43
0
        public void SaveBitmap()
        {
            bSaveDone = false;
            if (OutputImage != null)
            {
                SaveFileDialog saveDlg = new SaveFileDialog();
                saveDlg.Title = "Save Image";
                saveDlg.Filter = "Bitmap files (*.bmp)|*.bmp|JPEG files (*.jpg)|*.jpg|" +
                    "GIF files (*.gif)|*.gif|Icon files (*.ico)|*.ico|PNG files (*.png)|*.png|" +
                    "TIFF files (*.tif)|*.tif|WMF files (*.wmf)|*.wmf|EMF files (*.emf)|*.emf|" +
                    "EXIF files (*.exif)|*.exif|Memory Bitmap files (*.psd)|*.psd|All files (*.*)|*.*";
                string FileName = "";
                int FileTypeIndex = 0;
                System.Drawing.Imaging.ImageFormat[] ImgFormat = new System.Drawing.Imaging.ImageFormat[10];

                ImgFormat[0] = System.Drawing.Imaging.ImageFormat.Bmp;
                ImgFormat[1] = System.Drawing.Imaging.ImageFormat.Jpeg;
                ImgFormat[2] = System.Drawing.Imaging.ImageFormat.Gif;
                ImgFormat[3] = System.Drawing.Imaging.ImageFormat.Icon;
                ImgFormat[4] = System.Drawing.Imaging.ImageFormat.Png;
                ImgFormat[5] = System.Drawing.Imaging.ImageFormat.Tiff;
                ImgFormat[6] = System.Drawing.Imaging.ImageFormat.Wmf;
                ImgFormat[7] = System.Drawing.Imaging.ImageFormat.Emf;
                ImgFormat[8] = System.Drawing.Imaging.ImageFormat.Exif;
                ImgFormat[9] = System.Drawing.Imaging.ImageFormat.MemoryBmp;

                if (saveDlg.ShowDialog() == DialogResult.OK)
                {
                    FileName = saveDlg.FileName;
                    FileTypeIndex = saveDlg.FilterIndex - 1;
                }
                if (FileName != "")
                {
                    if (FileTypeIndex < ImgFormat.Length)
                        OutputImage.Save(FileName, ImgFormat[FileTypeIndex]);
                    else
                        OutputImage.Save(FileName);
                }
            }
            bSaveDone = true;
        }
Exemplo n.º 44
0
        private void LoadConfigure()
        {
            if (System.IO.File.Exists("config.json"))
            {
                string json = System.IO.File.ReadAllText("config.json");
                try
                {
                    string[] keyValueArray = json.Replace("{", string.Empty).Replace("}", string.Empty).Replace("\"", string.Empty).Split(',');
                    Dictionary<string, string> conf = keyValueArray.ToDictionary(item => item.Split(':')[0], item => item.Split(':')[1]);
                    timer.Interval = Convert.ToInt32(conf["interval"]);
                    System.Reflection.PropertyInfo propertyinfo = typeof(System.Drawing.Imaging.ImageFormat).GetProperty(conf["type"]);
                    _imageFormat = (System.Drawing.Imaging.ImageFormat)propertyinfo.GetValue(null, null);

                }
                catch
                {
                    ;
                }
            }
            //throw new NotImplementedException();
        }