Inheritance: Image
Example #1
3
 private void TakeSnapshot()
 {
     var stamp = DateTime.Now.ToString("yyyy-MM-dd-HH-mm");
     Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
     Graphics.FromImage(bmp).CopyFromScreen(0, 0, 0, 0, bmp.Size);
     bmp.Save(@"C:\Temp\" + stamp + ".jpg", ImageFormat.Jpeg);
 }
        public Image Mark( Image image, string waterMarkText )
        {
            WatermarkText = waterMarkText;

            Bitmap originalBmp = (Bitmap)image;

            // avoid "A Graphics object cannot be created from an image that has an indexed pixel format." exception
            Bitmap tempBitmap = new Bitmap(originalBmp.Width, originalBmp.Height);
            // From this bitmap, the graphics can be obtained, because it has the right PixelFormat
            Graphics g = Graphics.FromImage(tempBitmap);

            using (Graphics graphics = Graphics.FromImage(tempBitmap))
            {
                // Draw the original bitmap onto the graphics of the new bitmap
                g.DrawImage(originalBmp, 0, 0);
                var size =
                    graphics.MeasureString(WatermarkText, Font);
                var brush =
                    new SolidBrush(Color.FromArgb(255, Color));
                graphics.DrawString
                    (WatermarkText, Font, brush,
                    GetTextPosition(image, size));
            }

            return tempBitmap as Image;
        }
Example #3
2
        public override void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode)
        {
            Rectangle applyRect = ImageHelper.CreateIntersectRectangle(applyBitmap.Size, rect, Invert);

            if (applyRect.Width == 0 || applyRect.Height == 0)
            {
                // nothing to do
                return;
            }
            GraphicsState state = graphics.Save();
            if (Invert)
            {
                graphics.SetClip(applyRect);
                graphics.ExcludeClip(rect);
            }
            ColorMatrix grayscaleMatrix = new ColorMatrix(new[] {
                new[] {.3f, .3f, .3f, 0, 0},
                new[] {.59f, .59f, .59f, 0, 0},
                new[] {.11f, .11f, .11f, 0, 0},
                new float[] {0, 0, 0, 1, 0},
                new float[] {0, 0, 0, 0, 1}
            });
            using (ImageAttributes ia = new ImageAttributes())
            {
                ia.SetColorMatrix(grayscaleMatrix);
                graphics.DrawImage(applyBitmap, applyRect, applyRect.X, applyRect.Y, applyRect.Width, applyRect.Height, GraphicsUnit.Pixel, ia);
            }
            graphics.Restore(state);
        }
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            //g.DrawLine(pen, new Point(1, 1), new Point(300, 100));
            //g.DrawLine(pen, new Point(100, 1), new Point(300, 100));
            //g.DrawRectangle(pen, new Rectangle(50, 50, 100, 100));
             
            //g.DrawString("Hello! 你好!", font, brush, new PointF(150.0F, 150.0F));
            //g.DrawEllipse(pen, 
            g.FillEllipse(brush, 30, 30, 200, 200);
            g.FillEllipse(brush, 130, 130, 200, 200);
            g.FillEllipse(new SolidBrush(Color.FromArgb(153, 23, 153, 155)), 220, 230, 150, 150);
            g.FillEllipse(new SolidBrush(Color.FromArgb(153, 23, 153, 55)), 200, 30, 150, 150);
            g.FillEllipse(new SolidBrush(Color.FromArgb(153, 93, 53, 55)), 40, 230, 250, 250);
            
            //Image image = Image.FromFile("../../MonaLisa.jpg");
            //g.DrawImage(image, new Point(200, 200));

            // Create a Bitmap object from an image file.
            Bitmap bitmap = new Bitmap("../../MonaLisa.jpg");

            // Get the color of a pixel within myBitmap.
            Color pixelColor = bitmap.GetPixel(50, 50);
            // RGB value : pixelColor.R, pixelColor.G, pixelColor.B

            g.DrawImage(bitmap, new Point(200, 200));
        }
Example #5
2
        protected override void OnPaint(PaintEventArgs e)
        {
            //base.OnPaint(e);
            var myImg = new Bitmap("C:\\Users\\phil.SONOCINE\\Pictures\\MyTest.jpg");

            //byte[] bytes = ImageReading.pixels(myImg);

            this.pictureBox1.Image = ImageReading.pixels(myImg); ;
            //grayscale
            //var gsBytes = new List<byte>();
            //for (int i = 0; i < bytes.Length; i+=3)
            //{
            //    var R = bytes[i];
            //    var G = bytes[i+1];
            //    var B = bytes[i+2];
            //    byte gs = (byte)(0.2989 * R + 0.5870 * G + 0.1140 * B);
            //    gsBytes.Add(gs);
            //}

            //using (var ms = new MemoryStream(bytes))
            //{
            //    try
            //    {
            //        ms.Seek(0, SeekOrigin.Begin);
            //        var bmp = Image.FromStream(ms);
            //        e.Graphics.DrawImage(bmp, 0, 0);
            //    }
            //    catch(Exception ex)
            //    {
            //        Console.WriteLine(ex.Message);
            //    }
            //}
        }
Example #6
1
        public Bitmap Binariz(Bitmap bm)
        {
            int x = bm.Width;
            int y = bm.Height;

            Bitmap result = new Bitmap(x, y);

            for (int pixX = 0; pixX < x; pixX++)
                for (int pixY = 0; pixY < y; pixY++)
                {

                    int rd, gr, bl;

                    if (bm.GetPixel(pixX, pixY).R  < 100)
                        rd = 0;
                    else
                        rd = 255;

                    if (bm.GetPixel(pixX, pixY).G  < 100)
                        gr = 0;
                    else
                        gr = 255;

                    if (bm.GetPixel(pixX, pixY).B  < 100)
                        bl = 0;
                    else
                        bl = 255;

                    result.SetPixel(pixX, pixY, Color.FromArgb((byte)rd, (byte)gr, (byte)bl));
                }

            return result;
        }
 public ToolBarDeleteButton()
 {
     Bitmap button = new Bitmap(Properties.Resources.DeleteButton, new Size(50, 50));
     Bitmap buttonPressed = new Bitmap(Properties.Resources.DeleteButtonPressed, new Size(50, 50));
     this.BackgroundImage = button;
     this.PressedImage = buttonPressed;
 }
 public void PasteIconWithScale(byte[] bytes, int x, int y, double scale)
 {
     using (Bitmap icon = new Bitmap(new MemoryStream(bytes), false))
     {
         PasteIcon(icon, x, y, scale);
     }
 }
Example #9
1
		public void Setup()
		{
			Bitmap bmp = new Bitmap(200, 100);
			m_graphics = Graphics.FromImage(bmp);

			m_gm = new GraphicsManager(null, m_graphics);
		}
        public Preferences()
            : base()
        {
            InitializeComponent();

            Text = String.Concat(Locale.Current.Preferences.WindowTitle, " - ", Program.MainForm.Text);
            Icon = Program.MainForm.Icon;
            TopMost = true;

            _iconApps = Utilities.ResourceHelper.GetImage("gmail-limon.png");
            _iconStandard = Utilities.ResourceHelper.GetImage("gmail-bleu.png");

            _rendererListLarge = Shellscape.UI.VisualStyles.ControlPanel.GetRenderer(Shellscape.UI.VisualStyles.ControlPanel.ControlPanelPart.MessageText, 0, true);
            _rendererListSmall = Shellscape.UI.VisualStyles.ControlPanel.GetRenderer(Shellscape.UI.VisualStyles.ControlPanel.ControlPanelPart.BodyText, 0, true);
            _titleElement = Shellscape.UI.VisualStyles.ControlPanel.GetElement(
                Shellscape.UI.VisualStyles.ControlPanel.ControlPanelPart.Title,
                0,
                true
            );

            InitNavigation();
            InitGeneralPanel();
            InitAccountsPanel();
            InitAccountPanel();

            if (Config.Current.FirstRun) {
                InitFirstRun();
            }

            HidePanels();
            _PanelGeneral.Visible = true;
        }
Example #11
1
		// From http://edu.cnzz.cn/show_3281.html
		public static GraphicsPath CalculateGraphicsPathFromBitmap(Bitmap bitmap, Color colorTransparent) 
		{ 
			GraphicsPath graphicsPath = new GraphicsPath(); 
			if (colorTransparent == Color.Empty)
				colorTransparent = bitmap.GetPixel(0, 0); 

			for(int row = 0; row < bitmap.Height; row ++) 
			{ 
				int colOpaquePixel = 0;
				for(int col = 0; col < bitmap.Width; col ++) 
				{ 
					if(bitmap.GetPixel(col, row) != colorTransparent) 
					{ 
						colOpaquePixel = col; 
						int colNext = col; 
						for(colNext = colOpaquePixel; colNext < bitmap.Width; colNext ++) 
							if(bitmap.GetPixel(colNext, row) == colorTransparent) 
								break;
 
						graphicsPath.AddRectangle(new Rectangle(colOpaquePixel, row, colNext - colOpaquePixel, 1)); 
						col = colNext; 
					} 
				} 
			} 
			return graphicsPath; 
		} 
Example #12
1
 private void button3_Click(object sender, EventArgs e)
 {
     if (listView1.SelectedItems.Count != 1)
         return;
     OpenFileDialog od = new OpenFileDialog();
     od.Filter = "Bitmap file (*.bmp)|*.bmp";
     od.FilterIndex = 0;
     if (od.ShowDialog() == DialogResult.OK)
     {
         Section s = listView1.SelectedItems[0].Tag as Section;
         try
         {
             Bitmap bmp = new Bitmap(od.FileName);
             s.import(bmp);
             bmp.Dispose();
             pictureBox1.Image = s.image();
             listView1.SelectedItems[0].SubItems[3].Text = s.cnt.ToString();
             button4.Enabled = true;
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         }
     }
 }
Example #13
1
        /// <summary>
        /// Combine image of WallpaperConfiguration into one big image.
        /// 
        /// </summary>
        /// <returns></returns>
        protected string GenerateWallpaper()
        {
            string path = Path.GetTempFileName();

            // create an image for virtual screen
            Image image = new Bitmap(Configuration.VirtualScreenBounds.Width,
                Configuration.VirtualScreenBounds.Height);
            Graphics gs = Graphics.FromImage(image);

            // generate an image based on the described configuration
            foreach (ScreenConfiguration wallConf in Configuration.Screens)
            {
                // draw image
                IDrawer drawer = Drawers[wallConf.Style];
                drawer.Draw(gs, wallConf);
                gs.Flush();
            }
            image.Save(path, ImageFormat.Jpeg);

            // clean up
            image.Dispose();
            gs.Dispose();

            return path;
        }
Example #14
1
        public void AddImage(BackgroundImageClass image)
        {
            var imageBytes = webClientWrapper.DownloadBytes(image.ImageUrl);
            Bitmap bitmap = null;
            using (var originalBitmap = new Bitmap(new MemoryStream(imageBytes)))
            {
                using (var writer = new SpriteWriter(image.Width ?? originalBitmap.Width, image.Height ?? originalBitmap.Height))
                {
                    var width = image.Width ?? originalBitmap.Width;
                    if (width > originalBitmap.Width)
                        width = originalBitmap.Width;
                    var height = image.Height ?? originalBitmap.Height;
                    if (height > originalBitmap.Height)
                        height = originalBitmap.Height;
                    var x = image.XOffset.Offset < 0 ? Math.Abs(image.XOffset.Offset) : 0;
                    var y = image.YOffset.Offset < 0 ? Math.Abs(image.YOffset.Offset) : 0;

                    writer.WriteImage(originalBitmap.Clone(new Rectangle(x, y, width, height), originalBitmap.PixelFormat));
                    bitmap = writer.SpriteImage;
                    if ((originalBitmap.Width * originalBitmap.Height) > (bitmap.Width * bitmap.Height))
                        Size += writer.GetBytes("image/png").Length;
                    else
                        Size += imageBytes.Length;
                }
            }
            images.Add(bitmap);
            Width += bitmap.Width;
            if (Height < bitmap.Height) Height = bitmap.Height;
        }
Example #15
1
        /// <summary>
        /// Returns Exif rotation in degrees. Returns 0 if the metadata 
        /// does not exist or could not be read. A negative value means
        /// the image needs to be mirrored about the vertical axis.
        /// </summary>
        /// <param name="img">Image.</param>
        public static int GetRotation(Bitmap img)
        {
            try
            {
                foreach (PropertyItem prop in img.PropertyItems)
                {
                    if (prop.Id == TAG_ORIENTATION)
                    {
                        ushort orientationFlag = BitConverter.ToUInt16(prop.Value, 0);
                        if (orientationFlag == 1)
                            return 0;
                        else if (orientationFlag == 2)
                            return -360;
                        else if (orientationFlag == 3)
                            return 180;
                        else if (orientationFlag == 4)
                            return -180;
                        else if (orientationFlag == 5)
                            return -90;
                        else if (orientationFlag == 6)
                            return 90;
                        else if (orientationFlag == 7)
                            return -270;
                        else if (orientationFlag == 8)
                            return 270;
                    }
                }
            }
            catch
            {
                ;
            }

            return 0;
        }
Example #16
1
 private Bitmap ResizeBitmap(Bitmap bmp)
 {
     ResizeBilinear resizer = new ResizeBilinear(pb_loaded.Width, pb_loaded.Height);
     bmp = resizer.Apply(bmp);
     //bmp.Save(fileNameCounter+"resized.png");
     return bmp;
 }
 public void PasteFromBinaryScaledImageToTile(int zoom, double Lon, double Lat, int xTile, int yTile, double scale, byte[] bytes)
 {
     using (Bitmap iconImage = new Bitmap(new MemoryStream(bytes), false))
     {
         PasteScaledBitmapImageToTileByLatLon(zoom, Lon, Lat, xTile, yTile, scale, iconImage);
     }
 }
		public static int LoadTexture(string filename)
		{
			var bitmap = new Bitmap (filename);

			int id = GL.GenTexture ();

			BitmapData bmpData = bitmap.LockBits (
				new Rectangle (0, 0, bitmap.Width, bitmap.Height),
				ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

			GL.BindTexture (TextureTarget.Texture2D, id);

			GL.TexImage2D (TextureTarget.Texture2D, 0,
				PixelInternalFormat.Rgba,
				bitmap.Width, bitmap.Height, 0,
				OpenTK.Graphics.OpenGL.PixelFormat.Bgra,
				PixelType.UnsignedByte,
				bmpData.Scan0);

			bitmap.UnlockBits (bmpData);

			GL.TexParameter (TextureTarget.Texture2D,
				TextureParameterName.TextureMinFilter, 
				(int)TextureMinFilter.Linear);

			GL.TexParameter (TextureTarget.Texture2D,
				TextureParameterName.TextureMagFilter, 
				(int)TextureMagFilter.Linear);

			return id;
		}
 public Bitmap DrawBitmap(int theight, int twidth)
 {
     Bitmap bitmap3;
     Bitmap bitmap = new Bitmap(this.Width, this.Height);
     Rectangle targetBounds = new Rectangle(0, 0, this.Width, this.Height);
     this.MyBrowser.DrawToBitmap(bitmap, targetBounds);
     Image image = bitmap;
     Bitmap bitmap2 = new Bitmap(twidth, theight, image.PixelFormat);
     Graphics graphics = Graphics.FromImage(bitmap2);
     graphics.CompositingQuality = CompositingQuality.HighSpeed;
     graphics.SmoothingMode = SmoothingMode.HighSpeed;
     graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;
     Rectangle rect = new Rectangle(0, 0, twidth, theight);
     graphics.DrawImage(image, rect);
     try
     {
         bitmap3 = bitmap2;
     }
     catch
     {
         bitmap3 = null;
     }
     finally
     {
         image.Dispose();
         image = null;
         this.MyBrowser.Dispose();
         this.MyBrowser = null;
     }
     return bitmap3;
 }
Example #20
1
 public Image<Gray, byte> byteArrayToImage(byte[] byteArrayIn)
 {
     MemoryStream ms = new MemoryStream(byteArrayIn);
     Image i = Image.FromStream(ms);
     Bitmap b = new Bitmap(i);
     return new Image<Gray, byte>(b);
 }
Example #21
1
 public void LoadContent()
 {
     tiles = new Bitmap[2];
     tiles[0] = new Bitmap(@"Assets/Tiles/unpassable.png");
     tiles[1] = new Bitmap(@"Assets/Tiles/dirt.png");
     player = new Bitmap(@"Assets/avatar.png");
 }
        /// <summary>The quantize.</summary>
        /// <param name="image">The image.</param>
        /// <param name="pixelFormat">The pixel format.</param>
        /// <param name="useDither">The use dither.</param>
        /// <returns>The quantized image with the recalculated color palette.</returns>
        public static Bitmap Quantize(Image image, PixelFormat pixelFormat, bool useDither)
        {
            Bitmap tryBitmap = image as Bitmap;

            if (tryBitmap != null && tryBitmap.PixelFormat == PixelFormat.Format32bppArgb)
            {
                // The image passed to us is ALREADY a bitmap in the right format. No need to create
                // a copy and work from there.
                return DoQuantize(tryBitmap, pixelFormat, useDither);
            }

            // We use these values a lot
            int width = image.Width;
            int height = image.Height;
            Rectangle sourceRect = Rectangle.FromLTRB(0, 0, width, height);

            // Create a 24-bit rgb version of the source image
            using (Bitmap bitmapSource = new Bitmap(width, height, PixelFormat.Format32bppArgb))
            {
                using (Graphics grfx = Graphics.FromImage(bitmapSource))
                {
                    grfx.DrawImage(image, sourceRect, 0, 0, width, height, GraphicsUnit.Pixel);
                }

                return DoQuantize(bitmapSource, pixelFormat, useDither);
            }
        }
 public ContextMenuModel(IScreen owner, string name, string displayName, Bitmap image = null)
 {
     Owner = owner;
     Name = name;
     DisplayName = displayName;
     Image = image;
 }
 public CusCtlTellPanelChar(Liplis.MainSystem.Liplis lips, ObjSetting os, string url, string title, string discription, int newsEmotion, int newsPoint, Bitmap charBody, EventHandler enter, IContainer components)
 {
     this.lips = lips;
     this.os = os;
     initCms(components);
     initDataPanelNonThum(url, title, discription, newsEmotion, newsPoint, charBody, enter);
 }
Example #25
1
        private void DrawDebugInfo(Bitmap frame, VisionResults results)
        {
            using (var g = Graphics.FromImage(frame))
            {
                /*{
                    var thresholdString = string.Format("Threshold: {0}", HoughTransform.CannyThreshold);
                    var linkingString = string.Format("Linking: {0}", HoughTransform.CannyThresholdLinking);

                    g.FillRectangle(Brushes.White, 5, 5, 100, 50);
                    g.DrawString(thresholdString, SystemFonts.DefaultFont, Brushes.Crimson, new PointF(10, 10));
                    g.DrawString(linkingString, SystemFonts.DefaultFont, Brushes.Crimson, new PointF(10, 30));
                }*/

                if (showCircles)
                    foreach (var circle in results.Circles)
                    {
                        g.DrawEllipse(ellipsePen, circle.X - circle.Radius, circle.Y - circle.Radius, circle.Radius * 2, circle.Radius * 2);
                        g.DrawString(circle.Intensity.ToString(), SystemFonts.DefaultFont, Brushes.Orange, circle.X, circle.Y);
                    }

                if (showLines)
                    foreach (var line in results.Lines)
                    {
                        g.DrawLine(linePen, line.P1, line.P2);
                        g.DrawString(line.Length.ToString("0.00"), SystemFonts.DefaultFont, Brushes.OrangeRed, line.P2);
                    }

                if (results.TrackingBall)
                {
                    g.DrawRectangle(camshiftPen, results.TrackWindow);
                    g.DrawLine(camshiftPen, results.TrackCenter, Point.Add(results.TrackCenter, new Size(1, 1)));
                }
            }
        }
        /// <summary>
        /// Размещает иконку на тайле
        /// </summary>
        /// <param name="zoom"></param>
        /// <param name="Lon"></param>
        /// <param name="Lat"></param>
        /// <param name="xTile"></param>
        /// <param name="yTile"></param>
        /// <param name="iconImage"></param>
        public void PasteImageToTileByLatLon(int zoom, double Lon, double Lat, int xTile, int yTile, Bitmap iconImage)
        {
            int width = iconImage.Width;
            int height = iconImage.Height;

            CopyRegionIntoImage(iconImage, new Rectangle(0, 0, width, height),  GetTargetBound(zoom, Lon, Lat, xTile, yTile, width, height));
        }
        public static Bitmap LoadPicture(string url)
        {
            System.Net.HttpWebRequest wreq;
            System.Net.HttpWebResponse wresp;
            Stream mystream;
            Bitmap bmp;

            bmp = null;
            mystream = null;
            wresp = null;
            try
            {
                wreq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
                wreq.AllowWriteStreamBuffering = true;

                wresp = (System.Net.HttpWebResponse)wreq.GetResponse();

                if ((mystream = wresp.GetResponseStream()) != null)
                    bmp = new Bitmap(mystream);
            }
            catch
            {
                // Do nothing...
            }
            finally
            {
                if (mystream != null)
                    mystream.Close();

                if (wresp != null)
                    wresp.Close();
            }

            return (bmp);
        }
Example #28
0
        public static Image CopyTextureToBitmap(D3D.Texture2D texture)
        {
            int width = texture.Description.Width;
            if (width % 16 != 0)
                width = MathExtensions.Round(width, 16) + 16;
            Bitmap bmp = new Bitmap(texture.Description.Width, texture.Description.Height, PixelFormat.Format32bppArgb);
            BitmapData bData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat);
            using (DataStream stream = new DataStream(bData.Scan0, bData.Stride * bData.Height, false, true))
            {
                DataRectangle rect = texture.Map(0, D3D.MapMode.Read, D3D.MapFlags.None);
                using (DataStream texStream = rect.Data)
                {
                    for (int y = 0; y < texture.Description.Height; y++)
                        for (int x = 0; x < rect.Pitch; x+=4)
                        {
                            byte[] bytes = texStream.ReadRange<byte>(4);
                            if (x < bmp.Width*4)
                            {
                                stream.Write<byte>(bytes[2]);	// DXGI format is BGRA, GDI format is RGBA.
                                stream.Write<byte>(bytes[1]);
                                stream.Write<byte>(bytes[0]);
                                stream.Write<byte>(255);
                            }
                        }
                }
            }

            bmp.UnlockBits(bData);
            return bmp;
        }
Example #29
0
 public static byte[] decodeBinary(Bitmap bmp)
 {
     byte[] bytes = null;
     try
     {
         int wSize = bmp.Width, hSize = bmp.Height;
         MemoryStream stream = new MemoryStream();
         for (int w = 0; w < wSize; w++)
         {
             for (int h = 0; h < hSize; h++)
             {
                 Color color = bmp.GetPixel(w, h);
                 if (color.R == 0 && color.G == 0 && color.B == 0) stream.WriteByte(color.A);
                 else break;
             }
         }
         bytes = stream.ToArray();
         stream = null;
     }
     catch (Exception e)
     {
         bytes = null;
     }
     return bytes;
 }
Example #30
0
        public static System.Drawing.Bitmap Crop(this System.Drawing.Bitmap bmp, int width, int?height)
        {
            height = height ?? (int)(bmp.Height * ((double)width / (double)bmp.Width));

            System.Drawing.Bitmap   retVal = new Drawing.Bitmap(width, height.Value);
            System.Drawing.Graphics g      = System.Drawing.Graphics.FromImage(retVal);

            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            g.DrawImage(bmp, 0, 0, width, height.Value);

            return(retVal);
        }
Example #31
0
        private void OnSynthetic(object sender, System.EventArgs e)
        {
            List <ABC> des    = new List <ABC>();
            List <ABC> predic = new List <ABC>();

            int im = 0;

            if (im == 0)
            {
                string[]   arrdic  = new String[] { "田", "字", "奉", "膂", "雪", "こ", "や", "至", "一", "だ", "ほ", "’", "ん", "と" };
                Bitmap[]   br      = new Bitmap[arrdic.Length];
                Bitmap[]   brcop   = new Bitmap[arrdic.Length];
                List <ABC> listABC = new List <ABC>();

                for (int i = 0; i < arrdic.Length; i++)
                {
                    br[i] = (Bitmap)FontMethods.Render(arrdic[i]);
                    BitmapFilter.GrayToBlack(br[i], BRIGHT);
                    brcop[i] = (Bitmap)br[i].Clone();
                    brcop[i] = FontMethods.BoundCore(brcop[i]);
                    int[] fra = FontMethods.Fragment(brcop[i]);

                    //FontMethods.ImageToBackBone(br[i]);
                    br[i] = FontMethods.BoundCore(br[i]);
                    double[]   d      = FontMethods.AverageSquare(br[i]);
                    double[][] ad     = FontMethods.Margin(br[i]);
                    ABC        strABC = new ABC();
                    strABC.KEY              = arrdic[i];
                    strABC.AverageSquare    = d;
                    strABC.ProportionSquare = strABC.AverageSquare[1] == 0 ? 0 : strABC.AverageSquare[0] / strABC.AverageSquare[1];
                    strABC.Margin           = ad;
                    strABC.Fragment         = fra;
                    listABC.Add(strABC);
                }
                predic = listABC;
            }

            im = 1;
            if (im == 1)
            {
                m_Undo = (Bitmap)m_Bitmap.Clone();
                BitmapFilter.GrayToBlack(m_Bitmap, BRIGHT);
                Bitmap[]   arr = FontMethods.ImageToTextR1(m_Bitmap);
                Bitmap[][] br  = new Bitmap[arr.Length][];
                Bitmap[]   cr  = new Bitmap[arr.Length];
                for (int i = 0; i < arr.Length; i++)
                {
                    br[i] = FontMethods.ImageToTextR2(arr[i]);
                    cr[i] = FontMethods.JoinBitmap(br[i]);
                }
                m_Bitmap               = FontMethods.JoinBitmapH(cr);
                this.AutoScroll        = true;
                this.AutoScrollMinSize = new Size((int)(m_Bitmap.Width * Zoom), (int)(m_Bitmap.Height * Zoom));
                this.Invalidate();

                Bitmap[][] brcop   = new Bitmap[arr.Length][];
                List <ABC> listABC = new List <ABC>();
                for (int i = 0; i < arr.Length; i++)
                {
                    Bitmap[] bbcop = new Bitmap[br[i].Length];
                    for (int j = 0; j < br[i].Length; j++)
                    {
                        bbcop[j] = (Bitmap)br[i][j].Clone();
                        bbcop[j] = FontMethods.BoundCore(bbcop[j]);
                        int[] fra = FontMethods.Fragment(bbcop[j]);

                        //FontMethods.ImageToBackBone(br[i][j]);
                        br[i][j] = FontMethods.BoundCore(br[i][j]);
                        double[]   d      = FontMethods.AverageSquare(br[i][j]);
                        double[][] ad     = FontMethods.Margin(br[i][j]);
                        ABC        strABC = new ABC();
                        strABC.AverageSquare    = d;
                        strABC.ProportionSquare = strABC.AverageSquare[1] == 0 ? 0 : strABC.AverageSquare[0] / strABC.AverageSquare[1];
                        strABC.Margin           = ad;
                        strABC.Fragment         = fra;
                        listABC.Add(strABC);
                    }
                }
                des = listABC;
            }
            FncSynthetic(des, predic);
        }
Example #32
0
        public static bool IsImage(this IFormFile postedFile)
        {
            //-------------------------------------------
            //  Check the image mime types
            //-------------------------------------------
            if (postedFile.ContentType.ToLower() != "image/jpg" &&
                postedFile.ContentType.ToLower() != "image/jpeg" &&
                postedFile.ContentType.ToLower() != "image/pjpeg" &&
                postedFile.ContentType.ToLower() != "image/gif" &&
                postedFile.ContentType.ToLower() != "image/x-png" &&
                postedFile.ContentType.ToLower() != "image/png")
            {
                return(false);
            }

            //-------------------------------------------
            //  Check the image extension
            //-------------------------------------------
            if (Path.GetExtension(postedFile.FileName).ToLower() != ".jpg" &&
                Path.GetExtension(postedFile.FileName).ToLower() != ".png" &&
                Path.GetExtension(postedFile.FileName).ToLower() != ".gif" &&
                Path.GetExtension(postedFile.FileName).ToLower() != ".jpeg")
            {
                return(false);
            }

            //-------------------------------------------
            //  Attempt to read the file and check the first bytes
            //-------------------------------------------
            try
            {
                if (!postedFile.OpenReadStream().CanRead)
                {
                    return(false);
                }
                //------------------------------------------
                //check whether the image size exceeding the limit or not
                //------------------------------------------
                if (postedFile.Length < ImageMinimumBytes)
                {
                    return(false);
                }

                byte[] buffer = new byte[ImageMinimumBytes];
                postedFile.OpenReadStream().Read(buffer, 0, ImageMinimumBytes);
                string content = System.Text.Encoding.UTF8.GetString(buffer);
                if (Regex.IsMatch(content, @"<script|<html|<head|<title|<body|<pre|<table|<a\s+href|<img|<plaintext|<cross\-domain\-policy",
                                  RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline))
                {
                    return(false);
                }
            }
            catch (Exception)
            {
                return(false);
            }

            //-------------------------------------------
            //  Try to instantiate new Bitmap, if .NET will throw exception
            //  we can assume that it's not a valid image
            //-------------------------------------------

            try
            {
                using (var bitmap = new System.Drawing.Bitmap(postedFile.OpenReadStream()))
                {
                }
            }
            catch (Exception)
            {
                return(false);
            }
            finally
            {
                postedFile.OpenReadStream().Position = 0;
            }

            return(true);
        }
Example #33
0
        public Bitmap CreateImageCode(string code)
        {
            int fSize  = FontSize;
            int fWidth = FWidth + Padding;

            int imageWidth  = (int)(code.Length * fWidth) + 4 + Padding * 2;
            int imageHeight = FWidth * 2 + Padding;

            System.Drawing.Bitmap image = new System.Drawing.Bitmap(imageWidth, imageHeight);

            Graphics g = Graphics.FromImage(image);

            g.Clear(BackgroundColor);

            Random rand = new Random();

            //给背景添加随机生成的燥点
            if (this.Chaos)
            {
                Pen pen = new Pen(ChaosColor, 0);
                int c   = Length * 10;

                for (int i = 0; i < c; i++)
                {
                    int x = rand.Next(image.Width);
                    int y = rand.Next(image.Height);

                    g.DrawRectangle(pen, x, y, 1, 1);
                }
            }

            int top1 = 1, top2 = 1;

            int n1 = (imageHeight - FontSize - Padding * 2);
            int n2 = n1 / 4;

            top1 = n2;
            top2 = n2 * 2;

            //随机字体和颜色的验证码字符
            for (int i = 0; i < code.Length; i++)
            {
                var cindex = rand.Next(Colors.Length - 1);
                var findex = rand.Next(Fonts.Length - 1);

                Font  f = new System.Drawing.Font(Fonts[findex], fSize, System.Drawing.FontStyle.Bold);
                Brush b = new System.Drawing.SolidBrush(Colors[cindex]);

                var top = i % 2 == 1 ? top2 : top1;

                var left = i * fWidth;

                g.DrawString(code.Substring(i, 1), f, b, left, top);
            }

            //画一个边框 边框颜色为Color.Gainsboro
            g.DrawRectangle(new Pen(Color.Gainsboro, 0), 0, 0, image.Width - 1, image.Height - 1);
            g.Dispose();

            //产生波形(Add By 51aspx.com)
            image = TwistImage(image, true, 10, 4);

            return(image);
        }
Example #34
0
        public override void drawAttack(int x, int y, int targetx, int targety, ref System.Drawing.Bitmap bmap, System.Media.SoundPlayer player, ref PictureBox pictureMap, ref System.Drawing.Bitmap bmBackground, ref System.Drawing.Bitmap bmFull)
        {
            System.Threading.Thread.Sleep(150);
            player.SoundLocation = @"Sounds/iongun2.wav";

            Graphics  g = Graphics.FromImage(bmap);
            Rectangle rect;     //  --- размер изображения
            Bitmap    oldImage; //  --- переменная, в которую его засунем

            player.Play();

            SolidBrush brush1 = new SolidBrush(Color.CadetBlue);
            SolidBrush brush  = new SolidBrush(Color.CornflowerBlue);

            int dx, dy;

            dx = (targetx - x) / 10;
            dy = (targety - y) / 10;

            for (int i = 0; i < 10; i++)
            {
                // --- 1) находим размер изображения
                rect = new Rectangle(0, 0, bmap.Width, bmap.Height);
                // --- 2) клонируем наш битмап
                oldImage = bmap.Clone(rect, bmap.PixelFormat);

                g.FillEllipse(brush, x - 5 + dx * i, y - 5 + dy * i, 10, 10);
                g.FillEllipse(brush1, x - 3 + dx * i, y - 3 + dy * i, 6, 6);

                pictureMap.Image = bmap;
                pictureMap.Refresh();

                // --- 3) отрисовываем тот битмам, который сохранили выше
                g.DrawImage(oldImage, 0, 0);

                //System.Threading.Thread.Sleep(15);
            }
        }
Example #35
0
        private void CaptureDevice_NewFrameAvailableEvent(string deviceType, int deviceIndex, System.Drawing.Bitmap bmp)
        {
            Action displayFrame = delegate
            {
                if (chb_FlipFrame.IsChecked == true)
                {
                    bmp.RotateFlip(RotateFlipType.RotateNoneFlipX);
                }
                img_Preview.Source = Utilities.ToBitmapImage(bmp, ImageFormat.Jpeg);
                Bitmap buf = new Bitmap(bmp);

                if (isVideoRecording)
                {
                    videoWriter.WriteVideoFrame(buf);
                }
            };

            img_Preview.Dispatcher.Invoke(displayFrame);
            currentFrame = bmp;
        }
    protected void btnUpdateSettings_Click(object sender, EventArgs e)
    {
        try
        {
            string fileName  = Path.GetFileName(FUpimg.PostedFile.FileName);
            string extension = Path.GetExtension(FUpimg.PostedFile.FileName);

            if (txtCompanyName.Text == string.Empty || txtCompanyAddress.Text == string.Empty)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Please Update the information below')", true);
            }
            else
            {
                SqlConnection cn  = new SqlConnection(ConnectionString);
                SqlCommand    cmd = new SqlCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "Update dbo.[tbl_settings] set CompanyAddress = @CompanyAddress, CompanyName = @CompanyName,Location=@Location,  Phone =	@Phone,	[EmailAddress] = @EmailAddress , [WebAddress] = @WebAddress ,[VatRate] = @VatRate , [VATRegistration] = @VATRegistration,	[Footermsg] =  @Footermsg , LastUpdate =  GETDATE() , LastUpdateBy =	@LastUpdateBy, [Currency] = @Currency where ID =' "+ TextBox2.Text + "' ";
                cmd.Connection  = cn;
                cn.Open();


                cmd.Parameters.AddWithValue("@CompanyName", txtCompanyName.Text);
                cmd.Parameters.AddWithValue("@CompanyAddress", txtCompanyAddress.Text);
                cmd.Parameters.AddWithValue("@Location", TextBox1.Text);
                cmd.Parameters.AddWithValue("@Phone", txtPhone.Text);
                cmd.Parameters.AddWithValue("@EmailAddress", txtEmailAddress.Text);
                cmd.Parameters.AddWithValue("@WebAddress", txtWebAddress.Text);
                cmd.Parameters.AddWithValue("@VatRate", txtVatRate.Text);
                cmd.Parameters.AddWithValue("@VATRegistration", txtvatRegiNo.Text);
                cmd.Parameters.AddWithValue("@Currency", txtCurrency.Text);
                //cmd.Parameters.AddWithValue("@CompanyLogo",     imgUser.ImageUrl);
                cmd.Parameters.AddWithValue("@Footermsg", txtFooterMessage.Text);
                cmd.Parameters.AddWithValue("@LastUpdateBy", Request.Cookies["InventMgtCookies"]["UserID"].ToString());


                if (FUpimg.HasFile)
                {
                    if (extension == ".png" || extension == ".jpg" || extension == ".PNG" || extension == ".JPG")
                    {
                        cmd.Parameters.AddWithValue("@CompanyLogo", "~/Logo/" + lblUID.Text + extension);

                        string SaveLocation = Server.MapPath("../Logo/") + lblUID.Text + extension;

                        string fileExtention = FUpimg.PostedFile.ContentType;
                        int    fileLenght    = FUpimg.PostedFile.ContentLength;
                        System.Drawing.Bitmap bmpPostedImage = new System.Drawing.Bitmap(FUpimg.PostedFile.InputStream);
                        System.Drawing.Image  objImage       = ScaleImage(bmpPostedImage, 128);
                        // Saving image in jpeg format
                        objImage.Save(SaveLocation, ImageFormat.Png);
                        //   FUpimg.SaveAs(strPath);
                        imgUser.ImageUrl = "~/Logo/" + lblUID.Text + extension;
                    }
                    else
                    {
                        lblmsg.Visible = true;
                        lblmsg.Text    = ".jpg and .Png Format can be support";
                    }
                }
                else
                {
                    cmd.Parameters.AddWithValue("@CompanyLogo", imgUser.ImageUrl);
                }
                cmd.ExecuteNonQuery();
                cn.Close();
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Updated')", true);

                UpdateBindUpdate();
            }

            // company Logo Upload
        }

        catch
        {
        }
    }
        private void InitTexture()
        {
            System.Drawing.Bitmap contentBitmap = ManifestResourceLoader.LoadBitmap("DemoSimplePointSpriteElement.png");

            // step 4: get texture's size
            int targetTextureWidth;

            {
                //	Get the maximum texture size supported by OpenGL.
                int[] textureMaxSize = { 0 };
                GL.GetInteger(GetTarget.MaxTextureSize, textureMaxSize);

                //	Find the target width and height sizes, which is just the highest
                //	posible power of two that'll fit into the image.

                targetTextureWidth = textureMaxSize[0];

                int scaledWidth = contentBitmap.Width;

                for (int size = 1; size <= textureMaxSize[0]; size *= 2)
                {
                    if (scaledWidth < size)
                    {
                        targetTextureWidth = size / 2;
                        break;
                    }
                    if (scaledWidth == size)
                    {
                        targetTextureWidth = size;
                    }
                }
            }

            // step 5: scale contentBitmap to right size
            System.Drawing.Bitmap targetImage = contentBitmap;
            if (contentBitmap.Width != targetTextureWidth || contentBitmap.Height != targetTextureWidth)
            {
                //  Resize the image.
                targetImage = (System.Drawing.Bitmap)contentBitmap.GetThumbnailImage(targetTextureWidth, targetTextureWidth, null, IntPtr.Zero);
            }

            // step 6: generate texture
            {
                //  Lock the image bits (so that we can pass them to OGL).
                BitmapData bitmapData = targetImage.LockBits(new Rectangle(0, 0, targetImage.Width, targetImage.Height),
                                                             ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
                //GL.ActiveTexture(GL.GL_TEXTURE0);
                GL.GenTextures(1, texture);
                GL.BindTexture(GL.GL_TEXTURE_2D, texture[0]);
                GL.TexImage2D(GL.GL_TEXTURE_2D, 0, (int)GL.GL_RGBA,
                              targetImage.Width, targetImage.Height, 0, GL.GL_BGRA, GL.GL_UNSIGNED_BYTE,
                              bitmapData.Scan0);
                //  Unlock the image.
                targetImage.UnlockBits(bitmapData);
                /* We require 1 byte alignment when uploading texture data */
                //GL.PixelStorei(GL.GL_UNPACK_ALIGNMENT, 1);
                /* Clamping to edges is important to prevent artifacts when scaling */
                GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, (int)GL.GL_CLAMP_TO_EDGE);
                GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, (int)GL.GL_CLAMP_TO_EDGE);
                /* Linear filtering usually looks best for text */
                GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, (int)GL.GL_LINEAR);
                GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, (int)GL.GL_LINEAR);
            }

            // step 7: release images
            {
                //targetImage.Save("PointSpriteFontElement-TargetImage.png");
                if (targetImage != contentBitmap)
                {
                    targetImage.Dispose();
                }

                contentBitmap.Dispose();
            }
        }
        static void ConvertPixelFormat(System.Drawing.Bitmap bitmap, out PixelLayout to)
        {
            System.Drawing.Imaging.PixelFormat from = bitmap.PixelFormat;
            int flags = bitmap.Flags;

            bool sRGB = false;

#if false
            foreach (System.Drawing.Imaging.PropertyItem exifProperty in bitmap.PropertyItems)
            {
                switch (exifProperty.Id)
                {
                case ImageCodecPlugin.ExifTagColorSpace:
                    ImageCodecPlugin.ExifColorSpace value = (ImageCodecPlugin.ExifColorSpace)BitConverter.ToUInt16(exifProperty.Value, 0);

                    switch (value)
                    {
                    case ImageCodecPlugin.ExifColorSpace.sRGB:
                        sRGB = true;
                        break;

                    default:
                        break;
                    }
                    break;

                case ImageCodecPlugin.ExifTagGamma:
                    UInt32 a1    = BitConverter.ToUInt32(exifProperty.Value, 0);
                    UInt32 a2    = BitConverter.ToUInt32(exifProperty.Value, 4);
                    Double gamma = (Double)a1 / (Double)a2;


                    break;
                }
            }
#endif

            if ((flags & (int)ImageFlags.ColorSpaceRgb) != 0)
            {
                ConvertPixelFormatRgb(from, out to, sRGB);
            }
            else if ((flags & (int)ImageFlags.ColorSpaceGray) != 0)
            {
                switch (from)
                {
                case System.Drawing.Imaging.PixelFormat.Format1bppIndexed:
                case System.Drawing.Imaging.PixelFormat.Format4bppIndexed:
                case System.Drawing.Imaging.PixelFormat.Format8bppIndexed:
                    to = PixelLayout.R8;
                    break;

                case System.Drawing.Imaging.PixelFormat.Format16bppGrayScale:
                    to = PixelLayout.R16;
                    break;

                case System.Drawing.Imaging.PixelFormat.Format32bppArgb:
                    to = PixelLayout.BGRA32;
                    break;

                default:
                    throw new ArgumentException(String.Format("GRAY pixel format {0} not supported", from));
                }
            }
            else if ((flags & (int)ImageFlags.ColorSpaceYcck) != 0)
            {
                throw new ArgumentException(String.Format("YCCK pixel format {0} not supported", from));
            }
            else if ((flags & (int)ImageFlags.ColorSpaceYcbcr) != 0)
            {
                ConvertPixelFormatRgb(from, out to, sRGB);
            }
            else if ((flags & (int)ImageFlags.ColorSpaceCmyk) != 0)
            {
                throw new ArgumentException(String.Format("CMYK pixel format {0} not supported", from));
            }
            else
            {
                ConvertPixelFormatNoFlags(from, out to, sRGB);
            }
        }
Example #39
0
        private void btnstart_Click(object sender, EventArgs e)
        {
            int m = Convert.ToInt32(txtm.Text);

            if (oribitmap == null)
            {
                MessageBox.Show("请先加载图片", "出错", MessageBoxButtons.OK, MessageBoxIcon.Warning); return;
            }
            int h = oribitmap.Height, w = oribitmap.Width;

            bitmap = new Bitmap(w, h);

            Rectangle rect1 = new Rectangle(0, 0, w, h);

            System.Drawing.Imaging.BitmapData bmpdata1 = oribitmap.LockBits(rect1, System.Drawing.Imaging.ImageLockMode.ReadWrite, oribitmap.PixelFormat);
            IntPtr ptr1   = bmpdata1.Scan0;
            int    bytes1 = bmpdata1.Stride * bmpdata1.Height;

            byte[] rgbvalues1 = new byte[bytes1];
            System.Runtime.InteropServices.Marshal.Copy(ptr1, rgbvalues1, 0, bytes1); //copy pixel

            Rectangle rect2 = new Rectangle(0, 0, w, h);

            System.Drawing.Imaging.BitmapData bmpdata2 = bitmap.LockBits(rect2, System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat);
            IntPtr ptr2   = bmpdata2.Scan0;
            int    bytes2 = bmpdata2.Stride * bmpdata2.Height;

            byte[] rgbvalues2 = new byte[bytes2];
            for (int x = 0; x < h; x++)
            {
                for (int y = 0; y < w * 4; y += 4)
                {
                    int sumR = 0, sumG = 0, sumB = 0;
                    for (int a = -(m - 1) / 2; a <= (m - 1) / 2; a++)
                    {
                        for (int b = -(m - 1) / 2; b <= (m - 1) / 2; b++)
                        {
                            int u = x + a, v = y / 4 + b, pR, pG, pB;
                            if (u >= h || u < 0 || v >= w || v < 0)
                            {
                                pR = pG = pB = 0;
                            }
                            else
                            {
                                pR = rgbvalues1[u * bmpdata1.Stride + v * 4 + 2];
                                pG = rgbvalues1[u * bmpdata1.Stride + v * 4 + 1];
                                pB = rgbvalues1[u * bmpdata1.Stride + v * 4 + 0];
                            }
                            sumR += pR; sumG += pG; sumB += pB;
                        }
                    }
                    sumR = (int)((double)sumR / (double)(m * m) + 0.5);
                    sumG = (int)((double)sumG / (double)(m * m) + 0.5);
                    sumB = (int)((double)sumB / (double)(m * m) + 0.5);
                    int Al = rgbvalues1[x * bmpdata1.Stride + y + 3];
                    rgbvalues2[x * bmpdata2.Stride + y + 3] = (byte)Al;
                    rgbvalues2[x * bmpdata2.Stride + y + 2] = (byte)sumR;
                    rgbvalues2[x * bmpdata2.Stride + y + 1] = (byte)sumG;
                    rgbvalues2[x * bmpdata2.Stride + y + 0] = (byte)sumB;
                }
            }
            //NEW RECTANGLE;
            oribitmap.UnlockBits(bmpdata1);
            System.Runtime.InteropServices.Marshal.Copy(rgbvalues2, 0, ptr2, bytes2);
            bitmap.UnlockBits(bmpdata2);
            pictureBox2.Image = bitmap;
        }
Example #40
0
        private void btnmiddle_Click(object sender, EventArgs e)
        {
            int m = Convert.ToInt32(txtm.Text);

            if (oribitmap == null)
            {
                MessageBox.Show("请先加载图片", "出错", MessageBoxButtons.OK, MessageBoxIcon.Warning); return;
            }
            int h = oribitmap.Height, w = oribitmap.Width;

            bitmap = new Bitmap(w, h);

            Rectangle rect1 = new Rectangle(0, 0, w, h);

            System.Drawing.Imaging.BitmapData bmpdata1 = oribitmap.LockBits(rect1, System.Drawing.Imaging.ImageLockMode.ReadWrite, oribitmap.PixelFormat);
            IntPtr ptr1   = bmpdata1.Scan0;
            int    bytes1 = bmpdata1.Stride * bmpdata1.Height;

            byte[] rgbvalues1 = new byte[bytes1];
            System.Runtime.InteropServices.Marshal.Copy(ptr1, rgbvalues1, 0, bytes1); //copy pixel

            Rectangle rect2 = new Rectangle(0, 0, w, h);

            System.Drawing.Imaging.BitmapData bmpdata2 = bitmap.LockBits(rect2, System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat);
            IntPtr ptr2   = bmpdata2.Scan0;
            int    bytes2 = bmpdata2.Stride * bmpdata2.Height;

            byte[] rgbvalues2 = new byte[bytes2];
            for (int x = 0; x < h; x++)
            {
                for (int y = 0; y < w * 4; y += 4)
                {
                    int[] R  = new int[m * m];
                    int[] G  = new int[m * m];
                    int[] B  = new int[m * m];
                    int   id = 0;
                    for (int a = -(m - 1) / 2; a <= (m - 1) / 2; a++)
                    {
                        for (int b = -(m - 1) / 2; b <= (m - 1) / 2; b++)
                        {
                            int u = x + a, v = y / 4 + b;
                            if (u >= h || u < 0 || v >= w || v < 0)
                            {
                                R[id] = G[id] = B[id] = 0;
                            }
                            else
                            {
                                R[id] = rgbvalues1[u * bmpdata1.Stride + v * 4 + 2];
                                G[id] = rgbvalues1[u * bmpdata1.Stride + v * 4 + 1];
                                B[id] = rgbvalues1[u * bmpdata1.Stride + v * 4 + 0];
                            }
                            id++;
                        }
                    }
                    Array.Sort(R);
                    Array.Sort(G);
                    Array.Sort(B);
                    int Al = rgbvalues1[x * bmpdata1.Stride + y + 3];
                    rgbvalues2[x * bmpdata2.Stride + y + 3] = (byte)Al;
                    rgbvalues2[x * bmpdata2.Stride + y + 2] = (byte)R[(m * m + 1) / 2];
                    rgbvalues2[x * bmpdata2.Stride + y + 1] = (byte)G[(m * m + 1) / 2];
                    rgbvalues2[x * bmpdata2.Stride + y + 0] = (byte)B[(m * m + 1) / 2];
                }
            }
            //NEW RECTANGLE;
            oribitmap.UnlockBits(bmpdata1);
            System.Runtime.InteropServices.Marshal.Copy(rgbvalues2, 0, ptr2, bytes2);
            bitmap.UnlockBits(bmpdata2);
            pictureBox2.Image = bitmap;
        }
Example #41
0
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径(物理路径)</param>
        /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

            int towidth  = width;
            int toheight = height;

            int x  = 0;
            int y  = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
            case "HW":      //指定高宽缩放(可能变形)
                break;

            case "W":       //指定宽,高按比例
                toheight = originalImage.Height * width / originalImage.Width;
                break;

            case "H":       //指定高,宽按比例
                towidth = originalImage.Width * height / originalImage.Height;
                break;

            case "Cut":     //指定高宽裁减(不变形)
                if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                {
                    oh = originalImage.Height;
                    ow = originalImage.Height * towidth / toheight;
                    y  = 0;
                    x  = (originalImage.Width - ow) / 2;
                }
                else
                {
                    ow = originalImage.Width;
                    oh = originalImage.Width * height / towidth;
                    x  = 0;
                    y  = (originalImage.Height - oh) / 2;
                }
                break;

            default:
                break;
            }

            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);

            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
        /// <summary>
        /// Draw Reflection
        /// </summary>
        /// <param name="img">Set Image</param>
        /// <param name="toBG">Set Color of Background</param>
        /// <param name="toBG1">Set Color of Background</param>
        /// <param name="drawMode">Set the Draw Mode. Default value is Solid</param>
        /// <param name="RotateFlipType">Set Rotation. Default value is Rotate180FlipX</param>
        /// <param name="LinearGradientMode">Set Gradient Mode. Default value is Vertical</param>
        /// <param name="Length">Set the length. Default value is 100</param>
        /// <returns></returns>
        public static Image DrawReflection(Image img, Color toBG,
                                           Color toBG1, drawMode drawMode        = drawMode.Solid,
                                           RotateFlipType RotateFlipType         = RotateFlipType.Rotate180FlipX,
                                           LinearGradientMode LinearGradientMode = LinearGradientMode.Vertical,
                                           int Length = 100) // img is the original image.
        {
            //This is the static function that generates the reflection...
            int height = img.Height + Length;                                                                       //Added height from the original height of the image.

            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(img.Width, height, PixelFormat.Format64bppPArgb); //A new bitmap.


            Brush brsh = null;//The Brush that generates the fading effect to a specific color of your background.

            switch (drawMode)
            {
            case drawMode.Solid:
                brsh = new LinearGradientBrush(new Rectangle(0, 0, img.Width + 10, height), Color.Transparent, toBG, LinearGradientMode);    //The Brush that generates the fading effect to a specific color of your background.
                break;

            case drawMode.Gradient:
                brsh = new LinearGradientBrush(new Rectangle(0, 0, img.Width + 10, height), Color.Transparent, toBG, LinearGradientMode);    //The Brush that generates the fading effect to a specific color of your background.
                break;

            case drawMode.Hatch:
                brsh = new LinearGradientBrush(new Rectangle(0, 0, img.Width + 10, height), toBG1, toBG, LinearGradientMode);    //The Brush that generates the fading effect to a specific color of your background.
                break;

            case drawMode.None:
                break;

            default:
                break;
            }

            bmp.SetResolution(img.HorizontalResolution, img.VerticalResolution);          //Sets the new bitmap's resolution.
            using (System.Drawing.Graphics grfx = System.Drawing.Graphics.FromImage(bmp)) //A graphics to be generated from an image (here, the new Bitmap we've created (bmp)).
            {
                System.Drawing.Bitmap bm = (System.Drawing.Bitmap)img;                    //Generates a bitmap from the original image (img).
                grfx.DrawImage(bm, 0, 0, img.Width, img.Height);                          //Draws the generated bitmap (bm) to the new bitmap (bmp).
                System.Drawing.Bitmap bm1 = (System.Drawing.Bitmap)img;                   //Generates a bitmap again from the original image (img).
                bm1.RotateFlip(RotateFlipType);                                           //Flips and rotates the image (bm1).
                grfx.DrawImage(bm1, 0, img.Height);                                       //Draws (bm1) below (bm) so it serves as the reflection image.
                Rectangle rt = new Rectangle(0, img.Height, img.Width, Length);           //A new rectangle to paint our gradient effect.

                switch (drawMode)
                {
                case drawMode.Solid:
                    grfx.FillRectangle(brsh, rt);     //Brushes the gradient on (rt).
                    break;

                case drawMode.Gradient:
                    grfx.FillRectangle(brsh, rt);     //Brushes the gradient on (rt).
                    break;

                case drawMode.Hatch:
                    grfx.FillRectangle(brsh, rt);     //Brushes the gradient on (rt).
                    break;

                case drawMode.None:
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(drawMode), drawMode, null);
                }
            }

            return(bmp); //Returns the (bmp) with the generated image.
        }
Example #43
0
        /// <summary>
        /// Writes the given bitmap to the desktop.
        /// </summary>
        /// <param name="bitmap">The bitmap to write to the desktop.</param>
        /// <param name="fileName">The target file name.</param>
        public static void DumpToDesktop(this GDI.Bitmap bitmap, string fileName)
        {
            string desktopDir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

            bitmap.Save(Path.Combine(desktopDir, fileName));
        }
Example #44
0
    /// <summary>
    /// 生成缩略图
    /// </summary>
    /// <param name="orginalImagePat">原图片地址</param>
    /// <param name="thumNailPath">缩略图地址</param>
    /// <param name="width">缩略图宽度</param>
    /// <param name="height">缩略图高度</param>
    /// <param name="model">生成缩略的模式</param>
    public static void MakeThumNail(string originalImagePath, string thumNailPath, int width, int height, string model)
    {
        System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

        int thumWidth = width;      //缩略图的宽度
        int thumHeight = height;    //缩略图的高度

        int x = 0;
        int y = 0;

        int originalWidth = originalImage.Width;    //原始图片的宽度
        int originalHeight = originalImage.Height;  //原始图片的高度

        switch (model)
        {
            case "HW":      //指定高宽缩放,可能变形
                break;
            case "W":       //指定宽度,高度按照比例缩放
                thumHeight = originalImage.Height * width / originalImage.Width;
                break;
            case "H":       //指定高度,宽度按照等比例缩放
                thumWidth = originalImage.Width * height / originalImage.Height;
                break;
            case "Cut":
                if ((double)originalImage.Width / (double)originalImage.Height > (double)thumWidth / (double)thumHeight)
                {
                    originalHeight = originalImage.Height;
                    originalWidth = originalImage.Height * thumWidth / thumHeight;
                    y = 0;
                    x = (originalImage.Width - originalWidth) / 2;
                }
                else
                {
                    originalWidth = originalImage.Width;
                    originalHeight = originalWidth * height / thumWidth;
                    x = 0;
                    y = (originalImage.Height - originalHeight) / 2;
                }
                break;
            default:
                break;
        }

        //新建一个bmp图片
        System.Drawing.Image bitmap = new System.Drawing.Bitmap(thumWidth, thumHeight);

        //新建一个画板
        System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(bitmap);

        //设置高质量查值法
        graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

        //设置高质量,低速度呈现平滑程度
        graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        //清空画布并以透明背景色填充
        graphic.Clear(System.Drawing.Color.Transparent);

        //在指定位置并且按指定大小绘制原图片的指定部分
        graphic.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, thumWidth, thumHeight), new System.Drawing.Rectangle(x, y, originalWidth, originalHeight), System.Drawing.GraphicsUnit.Pixel);

        try
        {
            bitmap.Save(thumNailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch (Exception ex)
        {

            throw ex;
        }
        finally
        {
            originalImage.Dispose();
            bitmap.Dispose();
            graphic.Dispose();
        }

    }
Example #45
0
        private void FillData()
        {
            try
            {
                int length;

                IDC_FLAG = true;

                // 照片保存在当前目录
                String szXPPath          = "zp.bmp";
                System.Drawing.Image img = System.Drawing.Image.FromFile(szXPPath);
                System.Drawing.Image bmp = new System.Drawing.Bitmap(img);
                img.Dispose();
                pictureEdit1.Image = bmp;


                byte[] name = new byte[128];
                length = 128;
                CVRSDK.GetPeopleName(ref name[0], ref length);

                byte[] cnName = new byte[128];
                length = 128;
                CVRSDK.GetPeopleChineseName(ref cnName[0], ref length);

                byte[] number = new byte[128];
                length = 128;
                CVRSDK.GetPeopleIDCode(ref number[0], ref length);

                byte[] peopleNation = new byte[128];
                length = 128;
                CVRSDK.GetPeopleNation(ref peopleNation[0], ref length);

                byte[] peopleNationCode = new byte[128];
                length = 128;
                CVRSDK.GetNationCode(ref peopleNationCode[0], ref length);

                byte[] validtermOfStart = new byte[128];
                length = 128;
                CVRSDK.GetStartDate(ref validtermOfStart[0], ref length);

                byte[] birthday = new byte[128];
                length = 128;
                CVRSDK.GetPeopleBirthday(ref birthday[0], ref length);

                byte[] address = new byte[128];
                length = 128;
                CVRSDK.GetPeopleAddress(ref address[0], ref length);

                byte[] validtermOfEnd = new byte[128];
                length = 128;
                CVRSDK.GetEndDate(ref validtermOfEnd[0], ref length);

                byte[] signdate = new byte[128];
                length = 128;
                CVRSDK.GetDepartment(ref signdate[0], ref length);

                byte[] sex = new byte[128];
                length = 128;
                CVRSDK.GetPeopleSex(ref sex[0], ref length);

                byte[] Uid = new byte[128];
                length = 128;

                //CVRSDK.GetIDCardUID(ref Uid[0], 128);

                bool   bCivic   = true;
                byte[] certType = new byte[32];
                length = 32;
                CVRSDK.GetCertType(ref certType[0], ref length);

                string strType = System.Text.Encoding.ASCII.GetString(certType);
                int    nStart  = strType.IndexOf("I");
                if (nStart != -1)
                {
                    bCivic = false;
                }

                if (ic01 == null)
                {
                    ic01       = new Ic01();
                    ic01.ic001 = Tools.GetEntityPK("IC01");
                }

                ic01.ic000 = "0";                                                               //0-逝者 1-家属
                ic01.ic003 = System.Text.Encoding.GetEncoding("GB2312").GetString(name).Trim(); //姓名
                ic01.ic002 = System.Text.Encoding.GetEncoding("GB2312").GetString(sex).Replace("\0", "").Trim() == "男" ? "0" : "1";

                //出生日期
                string s_birth = System.Text.Encoding.GetEncoding("GB2312").GetString(birthday).Replace("\0", "").Trim();
                ic01.ic004 = Convert.ToDateTime(s_birth.Substring(0, 4) + "-" + s_birth.Substring(4, 2) + "-" + s_birth.Substring(6));

                //身份证号
                ic01.ic014 = System.Text.Encoding.GetEncoding("GB2312").GetString(number).Replace("\0", "").Trim();

                //地址
                ic01.ic016 = System.Text.Encoding.GetEncoding("GB2312").GetString(address).Replace("\0", "").Trim();

                //签发机关
                ic01.ic017 = System.Text.Encoding.GetEncoding("GB2312").GetString(signdate).Replace("\0", "").Trim();

                //有效期限
                ic01.ic018 = System.Text.Encoding.GetEncoding("GB2312").GetString(validtermOfStart).Replace("\0", "").Trim() + "-" + System.Text.Encoding.GetEncoding("GB2312").GetString(validtermOfEnd).Replace("\0", "").Trim();

                txtEdit_ac003.EditValue = ic01.ic003.Trim();
                rg_ac002.EditValue      = ic01.ic002;

                txtEdit_ac004.EditValue = MiscAction.Calc_Age_Via_Birth(ic01.ic004.ToString("yyyy-MM-dd"));
                txtEdit_ac008.EditValue = ic01.ic016.Trim();
                txtedit_ac014.EditValue = ic01.ic014.Trim();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.ToString(), "读卡错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// Load media from stream.
        /// </summary>
        /// <param name="stream">
        /// A <see cref="Stream"/> where the media data is stored.
        /// </param>
        /// <param name="criteria">
        /// A <see cref="MediaCodecCriteria"/> that specify parameters for loading an media stream.
        /// </param>
        /// <returns>
        /// An <see cref="Image"/> holding the media data.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// Exception thrown if <paramref name="stream"/> or <paramref name="criteria"/> is null.
        /// </exception>
        public Image Load(Stream stream, ImageCodecCriteria criteria)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (criteria == null)
            {
                throw new ArgumentNullException("criteria");
            }

            using (System.Drawing.Bitmap iBitmap = new System.Drawing.Bitmap(stream)) {
                Image       image;
                PixelLayout pType, pConvType;

                // Allocate image raster
                ConvertPixelFormat(iBitmap, out pType);

                // Check for hardware/software support
                if (pType.IsSupportedInternalFormat() == false)
                {
                    if (criteria.IsSet(ImageCodecCriteria.SoftwareSupport) && (bool)criteria[ImageCodecCriteria.SoftwareSupport])
                    {
                        // Pixel type not directly supported by hardware... try to guess suitable software conversion
                        pConvType = Pixel.GuessBestSupportedConvertion(pType);
                        if (pConvType == PixelLayout.None)
                        {
                            throw new InvalidOperationException("pixel type " + pType.ToString() + " is not supported by hardware neither software");
                        }
                    }
                    else
                    {
                        throw new InvalidOperationException("pixel type " + pType.ToString() + " is not supported by hardware");
                    }
                }
                else
                {
                    pConvType = pType;
                }

                image = new Image();
                image.Create(pType, (uint)iBitmap.Width, (uint)iBitmap.Height);

                switch (iBitmap.PixelFormat)
                {
                case System.Drawing.Imaging.PixelFormat.Format1bppIndexed:
                case System.Drawing.Imaging.PixelFormat.Format4bppIndexed:
                case System.Drawing.Imaging.PixelFormat.Format8bppIndexed:
                    if (Platform.RunningMono)
                    {
                        // Bug 676362 - Bitmap Clone does not format return image to requested PixelFormat
                        // https://bugzilla.novell.com/show_bug.cgi?id=676362
                        //
                        // ATM no mono version has resolved the bug; current workaround is performing image
                        // sampling pixel by pixel, using internal conversion routines, even if it is very slow

                        LoadBitmapByPixel(iBitmap, image);
                    }
                    else
                    {
                        LoadBitmapByClone(iBitmap, image);
                    }
                    break;

                default:
                    LoadBitmapByLockBits(iBitmap, image);
                    break;
                }

                // ConvertItemType image to supported format, if necessary
                if ((pConvType != PixelLayout.None) && (pConvType != pType))
                {
                    image = image.Convert(pConvType);
                }

                return(image);
            }
        }
Example #47
0
        // This method will run on a thread other than the UI thread.
        // Be sure not to manipulate any Windows Forms controls created
        // on the UI thread from this method.
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            backgroundWorker.ReportProgress(0, "Memulai...");

            filteredImage = (Bitmap)pictureBox1.Image.Clone();
            int    numClusters   = (int)numericUpDown2.Value;
            int    maxIterations = (int)numericUpDown3.Value;
            double accuracy      = (double)numericUpDown4.Value;



            List <ClusterPoint> points = new List <ClusterPoint>();


            for (int row = 0; row < originalImage.Width; ++row)
            {
                for (int col = 0; col < originalImage.Height; ++col)
                {
                    Color c2 = originalImage.GetPixel(row, col);
                    points.Add(new ClusterPoint(row, col, c2));
                }
            }



            List <ClusterCentroid> centroids = new List <ClusterCentroid>();

            //Create random points to use a the cluster centroids
            Random random = new Random();

            for (int i = 0; i < numClusters; i++)
            {
                int randomNumber1 = random.Next(sourceImage.Width);
                int randomNumber2 = random.Next(sourceImage.Height);
                centroids.Add(new ClusterCentroid(randomNumber1, randomNumber2, filteredImage.GetPixel(randomNumber1, randomNumber2)));
            }
            FCM alg = new FCM(points, centroids, 2, filteredImage, (int)numericUpDown2.Value);


            int k = 0;

            do
            {
                if ((backgroundWorker.CancellationPending == true))
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    k++;
                    alg.J = alg.CalculateObjectiveFunction();
                    alg.CalculateClusterCentroids();
                    alg.Step();
                    double Jnew = alg.CalculateObjectiveFunction();
                    Console.WriteLine("Run method i={0} accuracy = {1} delta={2}", k, alg.J, Math.Abs(alg.J - Jnew));
                    toolStripStatusLabel2.Text = "Precision " + Math.Abs(alg.J - Jnew);

                    // Format and display the TimeSpan value.
                    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", stopWatch.Elapsed.Hours, stopWatch.Elapsed.Minutes, stopWatch.Elapsed.Seconds, stopWatch.Elapsed.Milliseconds / 10);
                    toolStripStatusLabel3.Text = "Durasi: " + elapsedTime;

                    pictureBox2.Image = (Bitmap)alg.getProcessedImage;
                    backgroundWorker.ReportProgress((100 * k) / maxIterations, "Iterasi " + k);

                    if (Math.Abs(alg.J - Jnew) < accuracy)
                    {
                        break;
                    }
                }
            }while (maxIterations > k);
            Console.WriteLine("Done.");

            stopWatch.Stop();
            // Get the elapsed time as a TimeSpan value.
            TimeSpan ts = stopWatch.Elapsed;

            // Save the segmented image
            pictureBox2.Image = (Bitmap)alg.getProcessedImage.Clone();
            alg.getProcessedImage.Save("segmented.png");

            // Create a new image for each cluster in order to extract the features from the original image
            double[,] Matrix = alg.U;
            Bitmap[] bmapArray = new Bitmap[centroids.Count];
            for (int i = 0; i < centroids.Count; i++)
            {
                bmapArray[i] = new Bitmap(sourceImage.Width, sourceImage.Height, PixelFormat.Format32bppRgb);
            }

            for (int j = 0; j < points.Count; j++)
            {
                for (int i = 0; i < centroids.Count; i++)
                {
                    ClusterPoint p = points[j];
                    if (Matrix[j, i] == p.ClusterIndex)
                    {
                        bmapArray[i].SetPixel((int)p.X, (int)p.Y, p.OriginalPixelColor);
                    }
                }
            }

            // Save the image for each segmented cluster
            for (int i = 0; i < centroids.Count; i++)
            {
                bmapArray[i].Save("Cluster" + i + ".png");
            }


            // Resource cleanup...more work to do here to avoid memory problems!!!
            backgroundWorker.ReportProgress(100, "Done in " + k + " iterasi.");
            ////alg.Dispose();
            for (int i = 0; i < points.Count; i++)
            {
                points[i] = null;
            }
            for (int i = 0; i < centroids.Count; i++)
            {
                centroids[i] = null;
            }
            alg = null;
            //centroids.Clear();
            //points.Clear();
        }
Example #48
0
        private void CreateCheckCodeImage(string checkCode)
        {  //将验证码生成图片显示
            if (checkCode == null || checkCode.Trim() == String.Empty)
            {
                return;
            }

            System.Drawing.Bitmap image = new System.Drawing.Bitmap(imgWidth, imgheight);
            Graphics g = Graphics.FromImage(image);

            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            try
            {
                //生成随机生成器
                Random random = new Random();

                //清空图片背景色
                g.Clear(Color.White);

                StringFormat sf = new StringFormat(StringFormatFlags.NoClip);
                sf.Alignment     = StringAlignment.Center;
                sf.LineAlignment = StringAlignment.Center;


                //List<FontStyle> a = GetRndColor(checkCode.Length);
                FontStyle fontcolor = GetColorList[random.Next(0, GetColorList.Count)];
                //画文字
                int charX, CharY, charSize, charFontSize;

                //移除宽度
                int delwidth = 0;
                //旋转角度
                int    rotatefont = 0;
                Matrix mat        = new Matrix();
                for (int i = 0; i < checkCode.Length; i++)
                {
                    if (i != 0)
                    {
                        delwidth = rnd.Next(fontsize / 4, fontsize / 3);
                    }
                    rotatefont   = random.Next(-30, 30);
                    charFontSize = rnd.Next(fontsize - 5, fontsize);
                    charSize     = (imgWidth - 5) / checkCode.Length;
                    charX        = charSize * (i) + rnd.Next(2, 15);
                    CharY        = rnd.Next(1, imgheight - (charFontSize)) - 7;

                    mat.RotateAt(rotatefont, new PointF(charX, fontsize));
                    g.Transform = mat;

                    g.DrawString(checkCode[i].ToString(), new System.Drawing.Font("garamond", charFontSize, (System.Drawing.FontStyle.Bold)), new SolidBrush(fontcolor.FontColor), charX - delwidth, CharY);

                    mat.RotateAt(rotatefont * -1, new PointF(charX, fontsize));
                    g.Transform = mat;
                }

                g.Transform = new Matrix();

                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                Response.ClearContent();
                Response.ContentType = "image/x-png";
                Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
Example #49
0
        /// <summary>
        /// 指定长宽裁剪
        /// 按模版比例最大范围的裁剪图片并缩放至模版尺寸
        /// </summary>
        /// <remarks>汪磊 2012-08-08</remarks>
        /// <param name="fromFile">原图Stream对象</param>
        /// <param name="fileSaveUrl">保存路径</param>
        /// <param name="maxWidth">最大宽(单位:px)</param>
        /// <param name="maxHeight">最大高(单位:px)</param>
        /// <param name="quality">质量(范围0-100)</param>
        public static void CutForCustom(System.IO.Stream fromFile, string fileSaveUrl, int maxWidth, int maxHeight, int quality)
        {
            //从文件获取原始图片,并使用流中嵌入的颜色管理信息
            System.Drawing.Image initImage = System.Drawing.Image.FromStream(fromFile, true);

            //原图宽高均小于模版,不作处理,直接保存
            if (initImage.Width <= maxWidth && initImage.Height <= maxHeight)
            {
                initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            else
            {
                //模版的宽高比例
                double templateRate = (double)maxWidth / maxHeight;
                //原图片的宽高比例
                double initRate = (double)initImage.Width / initImage.Height;

                //原图与模版比例相等,直接缩放
                if (templateRate == initRate)
                {
                    //按模版大小生成最终图片
                    System.Drawing.Image    templateImage = new System.Drawing.Bitmap(maxWidth, maxHeight);
                    System.Drawing.Graphics templateG     = System.Drawing.Graphics.FromImage(templateImage);
                    templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    templateG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    templateG.Clear(Color.White);
                    templateG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel);
                    templateImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                //原图与模版比例不等,裁剪后缩放
                else
                {
                    //裁剪对象
                    System.Drawing.Image    pickedImage = null;
                    System.Drawing.Graphics pickedG     = null;

                    //定位
                    Rectangle fromR = new Rectangle(0, 0, 0, 0); //原图裁剪定位
                    Rectangle toR   = new Rectangle(0, 0, 0, 0); //目标定位

                    //宽为标准进行裁剪
                    if (templateRate > initRate)
                    {
                        //裁剪对象实例化
                        pickedImage = new System.Drawing.Bitmap(initImage.Width, (int)System.Math.Floor(initImage.Width / templateRate));
                        pickedG     = System.Drawing.Graphics.FromImage(pickedImage);

                        //裁剪源定位
                        fromR.X      = 0;
                        fromR.Y      = (int)System.Math.Floor((initImage.Height - initImage.Width / templateRate) / 2);
                        fromR.Width  = initImage.Width;
                        fromR.Height = (int)System.Math.Floor(initImage.Width / templateRate);

                        //裁剪目标定位
                        toR.X      = 0;
                        toR.Y      = 0;
                        toR.Width  = initImage.Width;
                        toR.Height = (int)System.Math.Floor(initImage.Width / templateRate);
                    }
                    //高为标准进行裁剪
                    else
                    {
                        pickedImage = new System.Drawing.Bitmap((int)System.Math.Floor(initImage.Height * templateRate), initImage.Height);
                        pickedG     = System.Drawing.Graphics.FromImage(pickedImage);

                        fromR.X      = (int)System.Math.Floor((initImage.Width - initImage.Height * templateRate) / 2);
                        fromR.Y      = 0;
                        fromR.Width  = (int)System.Math.Floor(initImage.Height * templateRate);
                        fromR.Height = initImage.Height;

                        toR.X      = 0;
                        toR.Y      = 0;
                        toR.Width  = (int)System.Math.Floor(initImage.Height * templateRate);
                        toR.Height = initImage.Height;
                    }

                    //设置质量
                    pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    pickedG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                    //裁剪
                    pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);

                    //按模版大小生成最终图片
                    System.Drawing.Image    templateImage = new System.Drawing.Bitmap(maxWidth, maxHeight);
                    System.Drawing.Graphics templateG     = System.Drawing.Graphics.FromImage(templateImage);
                    templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    templateG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    templateG.Clear(Color.White);
                    templateG.DrawImage(pickedImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, pickedImage.Width, pickedImage.Height), System.Drawing.GraphicsUnit.Pixel);

                    //关键质量控制
                    //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff
                    ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
                    ImageCodecInfo   ici  = null;
                    foreach (ImageCodecInfo i in icis)
                    {
                        if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif")
                        {
                            ici = i;
                        }
                    }
                    EncoderParameters ep = new EncoderParameters(1);
                    ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);

                    //保存缩略图
                    templateImage.Save(fileSaveUrl, ici, ep);
                    //templateImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);

                    //释放资源
                    templateG.Dispose();
                    templateImage.Dispose();

                    pickedG.Dispose();
                    pickedImage.Dispose();
                }
            }

            //释放资源
            initImage.Dispose();
        }
Example #50
0
 public EasyDraw(System.Drawing.Bitmap bitmap, bool addCollider = true) : base(bitmap, addCollider)
 {
     Initialize();
 }
Example #51
0
        public Form1()
        {
            InitializeComponent();

            m_Bitmap = new Bitmap(2, 2);
        }
Example #52
0
        /// <summary>
        /// 图片等比缩放
        /// </summary>
        /// <remarks>汪磊 2012-08-08</remarks>
        /// <param name="fromFile">原图Stream对象</param>
        /// <param name="savePath">缩略图存放地址</param>
        /// <param name="targetWidth">指定的最大宽度</param>
        /// <param name="targetHeight">指定的最大高度</param>
        /// <param name="watermarkText">水印文字(为""表示不使用水印)</param>
        /// <param name="watermarkImage">水印图片路径(为""表示不使用水印)</param>
        public static void ZoomAuto(System.IO.Stream fromFile, string savePath, System.Double targetWidth, System.Double targetHeight, string watermarkText, string watermarkImage)
        {
            //创建目录
            string dir = Path.GetDirectoryName(savePath);

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

            //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)
            System.Drawing.Image initImage = System.Drawing.Image.FromStream(fromFile, true);

            //原图宽高均小于模版,不作处理,直接保存
            if (initImage.Width <= targetWidth && initImage.Height <= targetHeight)
            {
                //文字水印
                if (watermarkText != "")
                {
                    using (System.Drawing.Graphics gWater = System.Drawing.Graphics.FromImage(initImage))
                    {
                        System.Drawing.Font  fontWater  = new Font("黑体", 10);
                        System.Drawing.Brush brushWater = new SolidBrush(Color.White);
                        gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
                        gWater.Dispose();
                    }
                }

                //透明图片水印
                if (watermarkImage != "")
                {
                    if (File.Exists(watermarkImage))
                    {
                        //获取水印图片
                        using (System.Drawing.Image wrImage = System.Drawing.Image.FromFile(watermarkImage))
                        {
                            //水印绘制条件:原始图片宽高均大于或等于水印图片
                            if (initImage.Width >= wrImage.Width && initImage.Height >= wrImage.Height)
                            {
                                Graphics gWater = Graphics.FromImage(initImage);

                                //透明属性
                                ImageAttributes imgAttributes = new ImageAttributes();
                                ColorMap        colorMap      = new ColorMap();
                                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                                ColorMap[] remapTable = { colorMap };
                                imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                                float[][] colorMatrixElements =
                                {
                                    new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f },
                                    new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f },
                                    new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f },
                                    new float[] { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f },//透明度:0.5
                                    new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }
                                };

                                ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
                                imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                                gWater.DrawImage(wrImage, new Rectangle(initImage.Width - wrImage.Width, initImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);

                                gWater.Dispose();
                            }
                            wrImage.Dispose();
                        }
                    }
                }

                //保存
                initImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            else
            {
                //缩略图宽、高计算
                double newWidth  = initImage.Width;
                double newHeight = initImage.Height;

                //宽大于高或宽等于高(横图或正方)
                if (initImage.Width > initImage.Height || initImage.Width == initImage.Height)
                {
                    //如果宽大于模版
                    if (initImage.Width > targetWidth)
                    {
                        //宽按模版,高按比例缩放
                        newWidth  = targetWidth;
                        newHeight = initImage.Height * (targetWidth / initImage.Width);
                    }
                }
                //高大于宽(竖图)
                else
                {
                    //如果高大于模版
                    if (initImage.Height > targetHeight)
                    {
                        //高按模版,宽按比例缩放
                        newHeight = targetHeight;
                        newWidth  = initImage.Width * (targetHeight / initImage.Height);
                    }
                }

                //生成新图
                //新建一个bmp图片
                System.Drawing.Image newImage = new System.Drawing.Bitmap((int)newWidth, (int)newHeight);
                //新建一个画板
                System.Drawing.Graphics newG = System.Drawing.Graphics.FromImage(newImage);

                //设置质量
                newG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                newG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                //置背景色
                newG.Clear(Color.White);
                //画图
                newG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, newImage.Width, newImage.Height), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel);

                //文字水印
                if (watermarkText != "")
                {
                    using (System.Drawing.Graphics gWater = System.Drawing.Graphics.FromImage(newImage))
                    {
                        System.Drawing.Font  fontWater  = new Font("宋体", 10);
                        System.Drawing.Brush brushWater = new SolidBrush(Color.White);
                        gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
                        gWater.Dispose();
                    }
                }

                //透明图片水印
                if (watermarkImage != "")
                {
                    if (File.Exists(watermarkImage))
                    {
                        //获取水印图片
                        using (System.Drawing.Image wrImage = System.Drawing.Image.FromFile(watermarkImage))
                        {
                            //水印绘制条件:原始图片宽高均大于或等于水印图片
                            if (newImage.Width >= wrImage.Width && newImage.Height >= wrImage.Height)
                            {
                                Graphics gWater = Graphics.FromImage(newImage);

                                //透明属性
                                ImageAttributes imgAttributes = new ImageAttributes();
                                ColorMap        colorMap      = new ColorMap();
                                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                                ColorMap[] remapTable = { colorMap };
                                imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                                float[][] colorMatrixElements =
                                {
                                    new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f },
                                    new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f },
                                    new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f },
                                    new float[] { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f },//透明度:0.5
                                    new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }
                                };

                                ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
                                imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                                gWater.DrawImage(wrImage, new Rectangle(newImage.Width - wrImage.Width, newImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);
                                gWater.Dispose();
                            }
                            wrImage.Dispose();
                        }
                    }
                }

                //保存缩略图
                newImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);

                //释放资源
                newG.Dispose();
                newImage.Dispose();
                initImage.Dispose();
            }
        }
Example #53
0
        /// <summary>
        /// 正方型裁剪
        /// 以图片中心为轴心,截取正方型,然后等比缩放
        /// 用于头像处理
        /// </summary>
        /// <remarks>汪磊 2012-08-08</remarks>
        /// <param name="fromFile">原图Stream对象</param>
        /// <param name="fileSaveUrl">缩略图存放地址</param>
        /// <param name="side">指定的边长(正方型)</param>
        /// <param name="quality">质量(范围0-100)</param>
        public static void CutForSquare(System.IO.Stream fromFile, string fileSaveUrl, int side, int quality)
        {
            //创建目录
            string dir = Path.GetDirectoryName(fileSaveUrl);

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

            //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)
            System.Drawing.Image initImage = System.Drawing.Image.FromStream(fromFile, true);

            //原图宽高均小于模版,不作处理,直接保存
            if (initImage.Width <= side && initImage.Height <= side)
            {
                initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            else
            {
                //原始图片的宽、高
                int initWidth  = initImage.Width;
                int initHeight = initImage.Height;

                //非正方型先裁剪为正方型
                if (initWidth != initHeight)
                {
                    //截图对象
                    System.Drawing.Image    pickedImage = null;
                    System.Drawing.Graphics pickedG     = null;

                    //宽大于高的横图
                    if (initWidth > initHeight)
                    {
                        //对象实例化
                        pickedImage = new System.Drawing.Bitmap(initHeight, initHeight);
                        pickedG     = System.Drawing.Graphics.FromImage(pickedImage);
                        //设置质量
                        pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        pickedG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        //定位
                        Rectangle fromR = new Rectangle((initWidth - initHeight) / 2, 0, initHeight, initHeight);
                        Rectangle toR   = new Rectangle(0, 0, initHeight, initHeight);
                        //画图
                        pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);
                        //重置宽
                        initWidth = initHeight;
                    }
                    //高大于宽的竖图
                    else
                    {
                        //对象实例化
                        pickedImage = new System.Drawing.Bitmap(initWidth, initWidth);
                        pickedG     = System.Drawing.Graphics.FromImage(pickedImage);
                        //设置质量
                        pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        pickedG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        //定位
                        Rectangle fromR = new Rectangle(0, (initHeight - initWidth) / 2, initWidth, initWidth);
                        Rectangle toR   = new Rectangle(0, 0, initWidth, initWidth);
                        //画图
                        pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);
                        //重置高
                        initHeight = initWidth;
                    }

                    //将截图对象赋给原图
                    initImage = (System.Drawing.Image)pickedImage.Clone();
                    //释放截图资源
                    pickedG.Dispose();
                    pickedImage.Dispose();
                }

                //缩略图对象
                System.Drawing.Image    resultImage = new System.Drawing.Bitmap(side, side);
                System.Drawing.Graphics resultG     = System.Drawing.Graphics.FromImage(resultImage);
                //设置质量
                resultG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                resultG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                //用指定背景色清空画布
                resultG.Clear(Color.White);
                //绘制缩略图
                resultG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, side, side), new System.Drawing.Rectangle(0, 0, initWidth, initHeight), System.Drawing.GraphicsUnit.Pixel);

                //关键质量控制
                //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff
                ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo   ici  = null;
                foreach (ImageCodecInfo i in icis)
                {
                    if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif")
                    {
                        ici = i;
                    }
                }
                EncoderParameters ep = new EncoderParameters(1);
                ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);

                //保存缩略图
                resultImage.Save(fileSaveUrl, ici, ep);

                //释放关键质量控制所用资源
                ep.Dispose();

                //释放缩略图资源
                resultG.Dispose();
                resultImage.Dispose();

                //释放原始图片资源
                initImage.Dispose();
            }
        }
        /// <summary>
        /// 生成校验码图片
        /// </summary>
        /// <param name="code">代码</param>
        /// <returns></returns>
        public Bitmap CreateImageCode(string code)
        {
            int fSize  = FontSize;
            int fWidth = fSize + Padding;

            int imageWidth  = (int)(code.Length * fWidth) + 4 + Padding * 2;
            int imageHeight = fSize * 2 + Padding;

            System.Drawing.Bitmap image = new System.Drawing.Bitmap(imageWidth, imageHeight);

            Graphics g = Graphics.FromImage(image);

            g.Clear(BackgroundColor);

            Random rand = new Random();

            //给背景添加随机生成的燥点
            if (this.Chaos)
            {
                Pen pen = new Pen(ChaosColor, 0);
                int c   = Length * 10;

                for (int i = 0; i < c; i++)
                {
                    int x = rand.Next(image.Width);
                    int y = rand.Next(image.Height);

                    g.DrawRectangle(pen, x, y, 1, 1);
                }
            }

            int left = 0, top = 0, top1 = 1, top2 = 1;

            int n1 = (imageHeight - FontSize - Padding * 2);
            int n2 = n1 / 4;

            top1 = n2;
            top2 = n2 * 2;

            Font  f;
            Brush b;

            int cindex, findex;

            //随机字体和颜色的验证码字符
            for (int i = 0; i < code.Length; i++)
            {
                cindex = rand.Next(Colors.Length - 1);
                findex = rand.Next(Fonts.Length - 1);

                f = new System.Drawing.Font(Fonts[findex], fSize, System.Drawing.FontStyle.Bold);
                b = new System.Drawing.SolidBrush(Colors[cindex]);

                if (i % 2 == 1)
                {
                    top = top2;
                }
                else
                {
                    top = top1;
                }

                left = i * fWidth;

                g.DrawString(code.Substring(i, 1), f, b, left, top);
            }

            #region 画边框
            //画一个边框 边框颜色为Color.Gainsboro
            //g.DrawRectangle(new Pen(Color.Gainsboro, 0), 0, 0, image.Width - 1, image.Height - 1);
            if (Border)
            {
                g.DrawRectangle(new Pen(BorderColor, BorderWidth), 0, 0, image.Width - 1, image.Height - 1);
            }
            #endregion ;
            g.Dispose();
            return(image);
        }
Example #55
0
        private System.Drawing.Bitmap DrawColorMode(int index)
        {
            System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(new System.Drawing.Point(2, 3), new System.Drawing.Size(this.picColorMode.Width - 4, this.picColorMode.Height - 6));
            System.Drawing.Bitmap    bitmap    = new System.Drawing.Bitmap(this.picColorMode.Width, this.picColorMode.Height);
            System.Drawing.Graphics  graphics  = System.Drawing.Graphics.FromImage(bitmap);
            graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
            switch (index)
            {
            case 0:
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Red), new System.Drawing.Rectangle(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height - 2));
                break;

            case 1:
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Red), new System.Drawing.Rectangle(rectangle.X, rectangle.Y, rectangle.Width / 2, rectangle.Height - 2));
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Green), new System.Drawing.Rectangle(rectangle.X + rectangle.Width / 2, rectangle.Y, rectangle.Width / 2, rectangle.Height - 2));
                break;

            case 2:
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Green), new System.Drawing.Rectangle(rectangle.X, rectangle.Y, rectangle.Width / 2, rectangle.Height - 2));
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Red), new System.Drawing.Rectangle(rectangle.X + rectangle.Width / 2, rectangle.Y, rectangle.Width / 2, rectangle.Height - 2));
                break;

            case 3:
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Red), new System.Drawing.Rectangle(rectangle.X, rectangle.Y, rectangle.Width / 3, rectangle.Height - 2));
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Green), new System.Drawing.Rectangle(rectangle.X + rectangle.Width / 3, rectangle.Y, rectangle.Width / 3, rectangle.Height - 2));
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Blue), new System.Drawing.Rectangle(rectangle.X + rectangle.Width * 2 / 3, rectangle.Y, rectangle.Width / 3, rectangle.Height - 2));
                break;

            case 4:
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Red), new System.Drawing.Rectangle(rectangle.X, rectangle.Y, rectangle.Width / 3, rectangle.Height - 2));
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Blue), new System.Drawing.Rectangle(rectangle.X + rectangle.Width / 3, rectangle.Y, rectangle.Width / 3, rectangle.Height - 2));
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Green), new System.Drawing.Rectangle(rectangle.X + rectangle.Width * 2 / 3, rectangle.Y, rectangle.Width / 3, rectangle.Height - 2));
                break;

            case 5:
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Green), new System.Drawing.Rectangle(rectangle.X, rectangle.Y, rectangle.Width / 3, rectangle.Height - 2));
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Red), new System.Drawing.Rectangle(rectangle.X + rectangle.Width / 3, rectangle.Y, rectangle.Width / 3, rectangle.Height - 2));
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Blue), new System.Drawing.Rectangle(rectangle.X + rectangle.Width * 2 / 3, rectangle.Y, rectangle.Width / 3, rectangle.Height - 2));
                break;

            case 6:
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Blue), new System.Drawing.Rectangle(rectangle.X, rectangle.Y, rectangle.Width / 3, rectangle.Height - 2));
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Red), new System.Drawing.Rectangle(rectangle.X + rectangle.Width / 3, rectangle.Y, rectangle.Width / 3, rectangle.Height - 2));
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Green), new System.Drawing.Rectangle(rectangle.X + rectangle.Width * 2 / 3, rectangle.Y, rectangle.Width / 3, rectangle.Height - 2));
                break;

            case 7:
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Green), new System.Drawing.Rectangle(rectangle.X, rectangle.Y, rectangle.Width / 3, rectangle.Height - 2));
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Blue), new System.Drawing.Rectangle(rectangle.X + rectangle.Width / 3, rectangle.Y, rectangle.Width / 3, rectangle.Height - 2));
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Red), new System.Drawing.Rectangle(rectangle.X + rectangle.Width * 2 / 3, rectangle.Y, rectangle.Width / 3, rectangle.Height - 2));
                break;

            case 8:
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Blue), new System.Drawing.Rectangle(rectangle.X, rectangle.Y, rectangle.Width / 3, rectangle.Height - 2));
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Green), new System.Drawing.Rectangle(rectangle.X + rectangle.Width / 3, rectangle.Y, rectangle.Width / 3, rectangle.Height - 2));
                graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Red), new System.Drawing.Rectangle(rectangle.X + rectangle.Width * 2 / 3, rectangle.Y, rectangle.Width / 3, rectangle.Height - 2));
                break;
            }
            graphics.Dispose();
            return(bitmap);
        }
Example #56
0
        /// <summary>
        /// Open Morphology Filter
        /// </summary>
        /// <param name="sourceBitmap">Set source Bitmap</param>
        /// <param name="matrixSize">Set matrix size</param>
        /// <param name="morphType">Set Morph Type</param>
        /// <param name="applyBlue">Apply Blue</param>
        /// <param name="applyGreen">Apply Green</param>
        /// <param name="applyRed">Apply Red</param>
        /// <returns></returns>
        public static System.Drawing.Bitmap DilateAndErodeFilter(this System.Drawing.Bitmap sourceBitmap,
                                                                 int matrixSize,
                                                                 MorphologyType morphType,
                                                                 bool applyBlue  = true,
                                                                 bool applyGreen = true,
                                                                 bool applyRed   = true)
        {
            BitmapData sourceData =
                sourceBitmap.LockBits(new Rectangle(0, 0,
                                                    sourceBitmap.Width, sourceBitmap.Height),
                                      ImageLockMode.ReadOnly,
                                      PixelFormat.Format32bppArgb);

            byte[] pixelBuffer = new byte[sourceData.Stride *
                                          sourceData.Height];

            byte[] resultBuffer = new byte[sourceData.Stride *
                                           sourceData.Height];

            Marshal.Copy(sourceData.Scan0, pixelBuffer, 0,
                         pixelBuffer.Length);

            sourceBitmap.UnlockBits(sourceData);

            int filterOffset = (matrixSize - 1) / 2;
            int calcOffset   = 0;

            int byteOffset = 0;

            byte blue  = 0;
            byte green = 0;
            byte red   = 0;

            byte morphResetValue = 0;

            if (morphType == MorphologyType.Erosion)
            {
                morphResetValue = 255;
            }

            for (int offsetY = filterOffset; offsetY <
                 sourceBitmap.Height - filterOffset; offsetY++)
            {
                for (int offsetX = filterOffset; offsetX <
                     sourceBitmap.Width - filterOffset; offsetX++)
                {
                    byteOffset = offsetY *
                                 sourceData.Stride +
                                 offsetX * 4;

                    blue  = morphResetValue;
                    green = morphResetValue;
                    red   = morphResetValue;

                    if (morphType == MorphologyType.Dilation)
                    {
                        for (int filterY = -filterOffset;
                             filterY <= filterOffset; filterY++)
                        {
                            for (int filterX = -filterOffset;
                                 filterX <= filterOffset; filterX++)
                            {
                                calcOffset = byteOffset +
                                             (filterX * 4) +
                                             (filterY * sourceData.Stride);

                                if (pixelBuffer[calcOffset] > blue)
                                {
                                    blue = pixelBuffer[calcOffset];
                                }

                                if (pixelBuffer[calcOffset + 1] > green)
                                {
                                    green = pixelBuffer[calcOffset + 1];
                                }

                                if (pixelBuffer[calcOffset + 2] > red)
                                {
                                    red = pixelBuffer[calcOffset + 2];
                                }
                            }
                        }
                    }
                    else if (morphType == MorphologyType.Erosion)
                    {
                        for (int filterY = -filterOffset;
                             filterY <= filterOffset; filterY++)
                        {
                            for (int filterX = -filterOffset;
                                 filterX <= filterOffset; filterX++)
                            {
                                calcOffset = byteOffset +
                                             (filterX * 4) +
                                             (filterY * sourceData.Stride);

                                if (pixelBuffer[calcOffset] < blue)
                                {
                                    blue = pixelBuffer[calcOffset];
                                }

                                if (pixelBuffer[calcOffset + 1] < green)
                                {
                                    green = pixelBuffer[calcOffset + 1];
                                }

                                if (pixelBuffer[calcOffset + 2] < red)
                                {
                                    red = pixelBuffer[calcOffset + 2];
                                }
                            }
                        }
                    }

                    if (applyBlue == false)
                    {
                        blue = pixelBuffer[byteOffset];
                    }

                    if (applyGreen == false)
                    {
                        green = pixelBuffer[byteOffset + 1];
                    }

                    if (applyRed == false)
                    {
                        red = pixelBuffer[byteOffset + 2];
                    }

                    resultBuffer[byteOffset]     = blue;
                    resultBuffer[byteOffset + 1] = green;
                    resultBuffer[byteOffset + 2] = red;
                    resultBuffer[byteOffset + 3] = 255;
                }
            }

            System.Drawing.Bitmap resultBitmap = new System.Drawing.Bitmap(sourceBitmap.Width,
                                                                           sourceBitmap.Height);

            BitmapData resultData =
                resultBitmap.LockBits(new Rectangle(0, 0,
                                                    resultBitmap.Width, resultBitmap.Height),
                                      ImageLockMode.WriteOnly,
                                      PixelFormat.Format32bppArgb);

            Marshal.Copy(resultBuffer, 0, resultData.Scan0,
                         resultBuffer.Length);

            resultBitmap.UnlockBits(resultData);

            return(resultBitmap);
        }
Example #57
0
        /// <summary>
        /// Resize the image to the specified width and height.
        /// 指定长宽裁剪
        /// 按模版比例最大范围的裁剪图片并缩放至模版尺寸
        /// </summary>
        /// <param name="image">The image to resize.</param>
        /// <param name="width">The width to resize to.</param>
        /// <param name="height">The height to resize to.</param>
        /// <returns>The resized image.</returns>
        public static System.Drawing.Bitmap CustomImage(System.Drawing.Image initImage, int maxWidth, int maxHeight)
        {
            //a holder for the result
            Bitmap result = new Bitmap(maxWidth, maxHeight);

            //set the resolutions the same to avoid cropping due to resolution differences
            result.SetResolution(initImage.HorizontalResolution, initImage.VerticalResolution);

            //use a graphics object to draw the resized image into the bitmap
            using (Graphics graphics = Graphics.FromImage(result))
            {
                //模版的宽高比例
                double templateRate = (double)maxWidth / maxHeight;
                //原图片的宽高比例
                double initRate = (double)initImage.Width / initImage.Height;
                //原图与模版比例相等,直接缩放
                if (templateRate == initRate)
                {
                    //按模版大小生成最终图片
                    graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    graphics.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    graphics.Clear(Color.White);
                    graphics.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel);
                }
                //原图与模版比例不等,裁剪后缩放
                else
                {
                    //裁剪对象
                    System.Drawing.Image    pickedImage = null;
                    System.Drawing.Graphics pickedG     = null;

                    //定位
                    Rectangle fromR = new Rectangle(0, 0, 0, 0); //原图裁剪定位
                    Rectangle toR   = new Rectangle(0, 0, 0, 0); //目标定位

                    //宽为标准进行裁剪
                    if (templateRate > initRate)
                    {
                        //裁剪对象实例化
                        pickedImage = new System.Drawing.Bitmap(initImage.Width, (int)System.Math.Floor(initImage.Width / templateRate));
                        pickedG     = System.Drawing.Graphics.FromImage(pickedImage);

                        //裁剪源定位
                        fromR.X      = 0;
                        fromR.Y      = (int)System.Math.Floor((initImage.Height - initImage.Width / templateRate) / 2);
                        fromR.Width  = initImage.Width;
                        fromR.Height = (int)System.Math.Floor(initImage.Width / templateRate);

                        //裁剪目标定位
                        toR.X      = 0;
                        toR.Y      = 0;
                        toR.Width  = initImage.Width;
                        toR.Height = (int)System.Math.Floor(initImage.Width / templateRate);
                    }
                    //高为标准进行裁剪
                    else
                    {
                        pickedImage = new System.Drawing.Bitmap((int)System.Math.Floor(initImage.Height * templateRate), initImage.Height);
                        pickedG     = System.Drawing.Graphics.FromImage(pickedImage);

                        fromR.X      = (int)System.Math.Floor((initImage.Width - initImage.Height * templateRate) / 2);
                        fromR.Y      = 0;
                        fromR.Width  = (int)System.Math.Floor(initImage.Height * templateRate);
                        fromR.Height = initImage.Height;

                        toR.X      = 0;
                        toR.Y      = 0;
                        toR.Width  = (int)System.Math.Floor(initImage.Height * templateRate);
                        toR.Height = initImage.Height;
                    }

                    //设置质量
                    pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    pickedG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                    //裁剪
                    pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);

                    //按模版大小生成最终图片
                    graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    graphics.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    graphics.Clear(Color.Transparent);
                    graphics.DrawImage(pickedImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, pickedImage.Width, pickedImage.Height), System.Drawing.GraphicsUnit.Pixel);

                    //释放资源
                    pickedImage.Dispose();
                    pickedG.Dispose();
                }
            }

            //return the resulting bitmap
            return(result);
        }
Example #58
0
        /// <summary>
        /// draw a bitmap at the given position;
        /// the current position is moved
        ///
        /// Either Width or WidthPercentage should be unequals 0, but only one should have a value.
        /// Same applies to Height
        /// </summary>
        public override void DrawBitmap(string APath,
                                        float AXPos,
                                        float AYPos,
                                        float AWidth,
                                        float AHeight,
                                        float AWidthPercentage,
                                        float AHeightPercentage)
        {
            if (!System.IO.File.Exists(APath))
            {
                throw new Exception("TGfxPrinter.DrawBitmap: cannot find image file " + APath);
            }

            Bitmap img;

            try
            {
                img = new System.Drawing.Bitmap(APath);
            }
            catch (Exception e)
            {
                TLogging.Log("Problem reading image for printing to PDF: " + APath);
                TLogging.Log(e.ToString());
                throw new Exception("Problem reading image for printing to PDF: " + APath);
            }

            float Height = img.Size.Height;

            if (AHeightPercentage != 0.0f)
            {
                Height = Height * AHeightPercentage;
            }
            else
            {
                Height = AHeight;
            }

            float Width = img.Size.Width;

            if (AHeightPercentage != 0.0f)
            {
                Width = Width * AWidthPercentage;
            }
            else
            {
                Width = AWidth;
            }

// there seem to be too many problems with this on Linux. On Linux, the size of the PDF is quite small anyway
#if DEACTIVATED
            if (false && (Width / img.Size.Width * 100 < 80))
            {
                // we should scale down the picture to make the result pdf smaller
                try
                {
                    Bitmap SmallerImg = new Bitmap(Convert.ToInt32(Width), Convert.ToInt32(Height));
                    using (Graphics g = Graphics.FromImage((Image)SmallerImg))
                    {
                        g.DrawImage(img, 0, 0, Convert.ToInt32(Width), Convert.ToInt32(Height));
                    }

                    // saving as PNG file because I get GDI+ status: InvalidParameter in Mono/XSP when trying to save to jpg
                    string ThumbPath = APath.Replace(Path.GetExtension(APath), "thumb.png");

                    ImageCodecInfo[] codecs        = ImageCodecInfo.GetImageDecoders();
                    ImageCodecInfo   jpegCodecInfo = codecs[0];

                    foreach (ImageCodecInfo codec in codecs)
                    {
                        if (codec.FormatID == ImageFormat.Png.Guid)
                        {
                            jpegCodecInfo = codec;
                        }
                    }

                    EncoderParameters codecParams = new EncoderParameters(1);
                    codecParams.Param[0] = new EncoderParameter(Encoder.Quality, 75);
                    SmallerImg.Save(ThumbPath, jpegCodecInfo, codecParams);
                    SmallerImg.Dispose();
                    img.Dispose();

                    File.Delete(ThumbPath);

                    img = new System.Drawing.Bitmap(ThumbPath);
                }
                catch (Exception)
                {
                }
            }
#endif

            DrawBitmapInternal(img, AXPos, AYPos, Width, Height);

            img.Dispose();
        }
Example #59
0
        /// <summary>
        /// Captures a Bitmap from the deviceContext on the specified areaToCopy.
        /// </summary>
        /// <param name="sourceDeviceContext">The device context to capture the region from.</param>
        /// <param name="rectangle">The rectangular bounds of the area to be captured.</param>
        /// <returns>A Bitmap representation of the region specified.</returns>
        static private Bitmap CaptureBitmap(IntPtr sourceDeviceContext, Rectangle rectangle)
        {
            //Empty rectangle semantic is undefined.
            if (rectangle.IsEmpty)
            {
                throw new ArgumentOutOfRangeException("rectangle");
            }

            IntPtr handleDeviceContextSrc         = sourceDeviceContext;
            IntPtr handleDeviceContextDestination = IntPtr.Zero;
            IntPtr handleBmp         = IntPtr.Zero;
            IntPtr handlePreviousObj = IntPtr.Zero;

            System.Drawing.Bitmap bmp = null;

            try
            {
                // Allocate memory for the bitmap
                handleBmp = NativeMethods.CreateCompatibleBitmap(handleDeviceContextSrc, rectangle.Width, rectangle.Height);
                if (handleBmp == IntPtr.Zero)
                {
                    throw new Win32Exception();
                }

                // Create destination DC
                handleDeviceContextDestination = NativeMethods.CreateCompatibleDC(handleDeviceContextSrc);
                if (handleDeviceContextDestination == IntPtr.Zero)
                {
                    throw new Win32Exception();
                }

                // copy screen to bitmap
                handlePreviousObj = NativeMethods.SelectObject(handleDeviceContextDestination, handleBmp);
                if (handlePreviousObj == IntPtr.Zero)
                {
                    throw new Win32Exception();
                }

                // Note : CAPTUREBLT is needed to capture layered windows
                bool result = NativeMethods.BitBlt(handleDeviceContextDestination, 0, 0, rectangle.Width, rectangle.Height, handleDeviceContextSrc, rectangle.Left, rectangle.Top, (Int32)(RasterOperationCodeEnum.SRCCOPY | RasterOperationCodeEnum.CAPTUREBLT));
                if (result == false)
                {
                    throw new Win32Exception();
                }

                //Convert Win32 Handle to Bitmap to a Winforms Bitmap
                bmp = Bitmap.FromHbitmap(handleBmp);
            }

            // Do Unmanaged cleanup
            finally
            {
                if (handlePreviousObj != IntPtr.Zero)
                {
                    NativeMethods.SelectObject(handleDeviceContextDestination, handlePreviousObj);
                    handlePreviousObj = IntPtr.Zero;
                }
                if (handleDeviceContextDestination != IntPtr.Zero)
                {
                    NativeMethods.DeleteDC(handleDeviceContextDestination);
                    handleDeviceContextDestination = IntPtr.Zero;
                }

                if (handleBmp != IntPtr.Zero)
                {
                    NativeMethods.DeleteObject(handleBmp);
                    handleBmp = IntPtr.Zero;
                }
            }
            return(bmp);
        }
Example #60
-12
        public static string Create(string src, int? width, int? height)
        {
            var sourcePath = HttpContext.Current.Server.MapPath(src);
            if (string.IsNullOrEmpty(sourcePath) || !File.Exists(sourcePath))
            {
                return string.Empty;
            }
            using (var srcBitmap = new Bitmap(sourcePath))
            {
                var w = width.HasValue ? width.Value : srcBitmap.Width;
                var h = height.HasValue ? height.Value : srcBitmap.Height;

                var imagePath = generatePath(sourcePath, w, h);
                var mappedImagePath = HttpContext.Current.Server.MapPath(imagePath);
                if (File.Exists(mappedImagePath))
                {
                    return imagePath;
                }

                using (var destBitmap = new Bitmap(srcBitmap, new Size(w, h)))
                {
                    destBitmap.Save(mappedImagePath);
                    return imagePath;
                }
            }
        }