Clone() публичный Метод

Creates a copy of the section of this Bitmap defined by Rectangle structure and with a specified PixelFormat enumeration.
public Clone ( Rectangle rect, PixelFormat pixelFormat ) : Bitmap
rect Rectangle Rect.
pixelFormat PixelFormat Pixel format.
Результат Bitmap
Пример #1
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;
        }
Пример #2
0
 public unsafe Bitmap GenerateGrayScale(Bitmap src_bmp, float type)
 {
     try
     {
         frames = int.Parse(Settings.SettingsCache.getConfig("RefreshDelay"));
     }
     catch (Exception ex)
     {
         Environment.Exit(ex.GetHashCode());
     }
     Bitmap dst_bmp = new Bitmap(src_bmp);
     UpdateStatus(0, (Bitmap)dst_bmp.Clone());
     for (int y = 0; y < dst_bmp.Height; y++) {
         delay++;
         if (delay >= frames)
         {
             UpdateStatus((y * 100) / dst_bmp.Height, (Bitmap)dst_bmp.Clone());
             delay = 0;
         }
         else
         {
             UpdateStatus((y * 100) / dst_bmp.Height, null);
         }
         for (int x = 0; x < dst_bmp.Width; x++)
         {
             Color c = dst_bmp.GetPixel(x, y);
             int rgb = (int)((c.R + c.G + c.B) / 3);
             dst_bmp.SetPixel(x, y, Color.FromArgb(rgb, rgb, rgb));
         }
     }
     UpdateStatus(100, (Bitmap)dst_bmp.Clone());
     return dst_bmp;
 }
Пример #3
0
        public HandMask( Bitmap Otsu)
        {
            //resmin kendisi

               // this.img = (Bitmap)bmp.Clone();

            _LOCK = new object();

            bmp1 = (Bitmap)Otsu.Clone();
            bmp2 = (Bitmap)Otsu.Clone();
            bmp3 = (Bitmap)Otsu.Clone();
            bmp4 = (Bitmap)Otsu.Clone();

            LeftHis = new int[Otsu.Width];
            RightHis = new int[Otsu.Width];
            DownHis = new int[Otsu.Height];
            UpHis = new int[Otsu.Height];

            Koordinat = new int[4];

            Array.Clear(LeftHis, 0, LeftHis.Length);
            Array.Clear(DownHis, 0, DownHis.Length);
            Array.Clear(RightHis, 0, RightHis.Length);
            Array.Clear(UpHis, 0, UpHis.Length);

            setoff_bilek = Otsu.Width / 20;
            setoff_y = Otsu.Height / 100;
            setoff_x = Otsu.Width / 100;
        }
        public override Bitmap RealizarTrabalho(Bitmap imagem)
        {
            Bitmap final;
            Bitmap processamento = new Bitmap((Image)imagem.Clone());

			/* Verifica-se todos os pixels da imagem, eliminando
			* as cores de fundo
			*/
            for (int y = 0; y < processamento.Height && !cancelado; y+= 1)
				for (int x = 0; x < processamento.Width && !cancelado; x+= 1)
				{
					Color cor = processamento.GetPixel(x, y);
                    Color fundo = this.fundo.GetPixel(x, y);
                    float diferença;

                    diferença = (Math.Abs(cor.R - fundo.R)
                        + Math.Abs(cor.G - fundo.G)
                        + Math.Abs(cor.B - fundo.B)) / 3f;

                    if (diferença <= tolerância)
						processamento.SetPixel(x, y, Color.FromArgb(0, cor));
				}

            if (cancelado)
                return null;

			// Suavizar transparência
            final = SuavizarTransparência(processamento);
			
            final.Tag = imagem.Clone();

			return final;
        }
 public frmGrayscalePreview(Bitmap image)
 {
     InitializeComponent();
     pbxOrg.Image = (Bitmap)image.Clone();
     pbxPreview.Image = (Bitmap)image.Clone();
     libImage.GrayScale((Bitmap)pbxPreview.Image);
 }
        protected void btn_submit_Click(object sender, EventArgs e)
        {
            org = System.Drawing.Image.FromStream(fileUpload_Steg.PostedFile.InputStream);
            OriginalImage = (Bitmap)org;

            // Copy the original message.
            EncodedImage = (Bitmap)OriginalImage.Clone();
            MarkedImage = (Bitmap)OriginalImage.Clone();

            // Encode.
            try
            {
                string fileName = fileUpload_Steg.PostedFile.FileName;
                EncodeMessageInImage(EncodedImage, MarkedImage,
                    tb_pw.Text, tb_textToHide.Text);

                afterEncode = (System.Drawing.Image)EncodedImage;
                afterEncode.Save(Path.Combine(Server.MapPath(null), fileName));

                fileName = Path.Combine(Server.MapPath(null), fileName);
                //string fileName = img_userImage.ImageUrl;

                Response.ContentType = "image/JPEG";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + "watermarked_" + fileName.Remove(0, 15));

                Response.TransmitFile(fileName);
                Response.End();

            }
            catch (Exception ex)
            {

            }
        }
Пример #7
0
        public void Process(Bitmap fullScreenshot)
        {
            Mode mode = Form.CurrentMode;
            Bitmap field = fullScreenshot.Clone(mode.GetField(), fullScreenshot.PixelFormat);
            if (Form.CurrentMode.GetType() == typeof(DiamondMine))
            {
                Bitmap cleared = fullScreenshot.Clone(new Rectangle(582, 788, 875, 6), fullScreenshot.PixelFormat);
                Color averageColor = Histograms.GetAverageColor(cleared);
                if (averageColor.R >= 200 && averageColor.G >= 200)
                {
                    DiamondMineCleared = true;
                    DiamondMineLastCleared = DateTime.Now;
                }
                else
                {
                    if (DiamondMineLastCleared.AddSeconds(1) < DateTime.Now)
                    {
                        DiamondMineCleared = false;
                    }
                }
                cleared.Dispose();
            }
            
            
            // Update Grid from image
            for (int x = 0; x < 8; x++)
            {
                for (int y= 0;y <8;y++)
                {
                    Bitmap thisGem = field.Clone(new Rectangle(x * 112, y * 112, 112, 112), field.PixelFormat);
                    Grid[x, y] = new Gem(GemColor.Unrecognized, thisGem, x, y);
                }
            }

            // Recognize
            for (int x = 0; x < 8; x++)
            {
                for (int y = 0; y < 8; y++)
                {
                    Grid[x, y].GemColor = Form.RecognitionStrategy.GetColor(Grid[x, y]);
                }
            }

            // Find options
            Predictor.Predict(Grid);

            // Update Field Image
            if (Form.pictureBoxField.Image != null)
            {
                Form.pictureBoxField.Image.Dispose();
            }
            Form.pictureBoxField.Image = field;
            // Update Grid based on Grid
            Action a = () =>
            {
                Form.pictureBoxGrid.Refresh();
            };
            Form.pictureBoxGrid.Invoke(a);
            
        }
 public static Bitmap copyPartOfBitmap(Bitmap bmp, Rectangle cloneRect)
 {
     System.Drawing.Imaging.PixelFormat format = bmp.PixelFormat;
     Bitmap result;
     if (cloneRect.Width <= 0 || cloneRect.Height <= 0)
         result = (Bitmap)bmp.Clone();
     else
         result = bmp.Clone(cloneRect, format);
     return result;
 }
Пример #9
0
        private void buttonOpenImage_Click(object sender, EventArgs e)
        {
            var dialogResult = _openFileDialog.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                var image = new Bitmap(_openFileDialog.FileName);
                _pictureBox.Image = image.Clone() as Image;

                _sourceImage = image.Clone() as Bitmap;
                buttonHistogram.Enabled = true;
            }
        }
Пример #10
0
        public Bitmap Apply(Bitmap original)
        {
            GrayscaleEffect.Grasycale gray = new GrayscaleEffect.Grasycale();
            if (!notGray) original = gray.Apply(original);

            FilterProcessor processor = new FilterProcessor();

            processor.SetMatrix(new double[][] { new double[] { 1, 2, 1 }, new double[] { 0, 0, 0 }, new double[] { -1, -2, -1 } });
            Bitmap Gx = processor.Process((Bitmap)original.Clone());

            processor.SetMatrix(new double[][] { new double[] { 1, 0, -1 }, new double[] { 2, 0, -2 }, new double[] { 1, 0, -1 } });
            Bitmap Gy = processor.Process((Bitmap)original.Clone());

            Rectangle rect = new Rectangle(0, 0, original.Width, original.Height);

            #region Initialization
            System.Drawing.Imaging.BitmapData bmpDataX = Gx.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            IntPtr ptrX = bmpDataX.Scan0;
            int bytesX = Math.Abs(bmpDataX.Stride) * bmpDataX.Height;
            byte[] valuesGx = new byte[bytesX];
            System.Runtime.InteropServices.Marshal.Copy(ptrX, valuesGx, 0, bytesX);
            Gx.UnlockBits(bmpDataX);

            System.Drawing.Imaging.BitmapData bmpDataY = Gy.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            IntPtr ptrY = bmpDataY.Scan0;
            int bytesY = Math.Abs(bmpDataY.Stride) * bmpDataY.Height;
            byte[] valuesGy = new byte[bytesY];
            System.Runtime.InteropServices.Marshal.Copy(ptrY, valuesGy, 0, bytesY);
            Gy.UnlockBits(bmpDataY);

            System.Drawing.Imaging.BitmapData bmpData = original.LockBits(rect, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            IntPtr ptr = bmpData.Scan0;
            int bytes = Math.Abs(bmpData.Stride) * bmpData.Height;
            byte[] values = new byte[bytes];
            System.Runtime.InteropServices.Marshal.Copy(ptr, values, 0, bytes);
            #endregion

            for (int i = 0; i < values.Length; i += 3)
            {
                if (i + 2 >= values.Length) break;
                double r = Math.Sqrt((double)valuesGx[i + 2] * (double)valuesGx[i + 2] + (double)valuesGy[i + 2] * (double)valuesGy[i + 2]);
                double g = Math.Sqrt((double)valuesGx[i + 1] * (double)valuesGx[i + 1] + (double)valuesGy[i + 1] * (double)valuesGy[i + 1]);
                double b = Math.Sqrt((double)valuesGx[i + 0] * (double)valuesGx[i + 0] + (double)valuesGy[i + 0] * (double)valuesGy[i + 0]);
                values[i + 0] = (byte)(r / Math.Sqrt(2));
                values[i + 1] = (byte)(g / Math.Sqrt(2));
                values[i + 2] = (byte)(b / Math.Sqrt(2));
            }

            System.Runtime.InteropServices.Marshal.Copy(values, 0, ptr, bytes);
            original.UnlockBits(bmpData);
            return original;
        }
        private static List<Bitmap> SeparateNumbersWithWhiteColumnsAsDelimiter(Bitmap img, List<Tuple<bool, int>> whiteColumns)
        {
            List<Bitmap> result = new List<Bitmap>
            {
                img.Clone(Rectangle.FromLTRB(0, 0, whiteColumns[1].Item2, img.Height), img.PixelFormat)
            };

            for (int i = 1; i < whiteColumns.Count - 1; i++)
            {
                result.Add(img.Clone(Rectangle.FromLTRB(whiteColumns[i].Item2, 0, whiteColumns[i + 1].Item2, img.Height),
                    img.PixelFormat));
            }
            return result;
        }
Пример #12
0
 private void Form1_MouseUp(object sender, MouseEventArgs e)
 {
     Image i1 = Properties.Resources.background;
     Bitmap bmp = new Bitmap(Properties.Resources.cha);
     Rectangle r = new Rectangle(0,0, 64,64);
     Rectangle r2 = new Rectangle(64, 0, 64, 64);
     Bitmap bmp2 = bmp.Clone(r, bmp.PixelFormat);
     Bitmap bmp3 = bmp.Clone(r2, bmp.PixelFormat);
     Graphics g = this.CreateGraphics();
     g.DrawImage(i1, 0, 0);
     g.DrawImage(bmp2, Width/2, Height/2);
     g.DrawImage(bmp3, Width / 2 +100, Height / 2);
     g.Dispose();
 }
Пример #13
0
        protected override void OnPaint(PaintEventArgs e)
        {
            Bitmap b = new Bitmap(Width, Height);
            Graphics g = Graphics.FromImage(b);

            g.Clear(Color.Gainsboro);

            for (int i = 0; i < this.TabCount; i++)
            {
                Rectangle tabRect = GetTabRect(i);
                if (i == this.SelectedIndex)
                {
                    g.FillRectangle(Brushes.Red, tabRect);
                }
                else
                {
                    g.FillRectangle(Brushes.AliceBlue, tabRect);
                }

                g.DrawString(this.TabPages[i].Text, this.Font, Brushes.White, tabRect, new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center });
            }

            e.Graphics.DrawImage((Bitmap)b.Clone(), 0, 0);

            g.Dispose();
            b.Dispose();
            base.OnPaint(e);
        }
Пример #14
0
        public List<double[]> extract(Bitmap image, string detector)
        {
            SCD_Descriptor scdLocal = new SCD_Descriptor();
            Bitmap bmpImage = new Bitmap(image);

            createPoints pointsCreator = new createPoints();
            List<Keypoint> keypointsList = null;
            if (detector == "SURF")
                keypointsList = pointsCreator.usingSurf(image);
            else if (detector == "SIFT")
                keypointsList = pointsCreator.usingSift(image);
            else
                throw new Exception("Cannot recognize Detector");

            #region SCD_Local
            Rectangle cloneRect;
            Bitmap bmpCrop;
            double[] scdDescriptor = new double[256];
            List<double[]> tilesDescriptors = new List<double[]>();

            foreach (Keypoint myKeypoint in keypointsList)
            {
                cloneRect = new Rectangle((int)(myKeypoint.X - (int)myKeypoint.Size / 2), (int)(myKeypoint.Y - (int)myKeypoint.Size / 2), (int)myKeypoint.Size, (int)myKeypoint.Size);
                bmpCrop = new Bitmap(bmpImage.Clone(cloneRect, bmpImage.PixelFormat));

                scdLocal.Apply(new Bitmap(bmpCrop), 256, 0);
                scdDescriptor = scdLocal.Norm4BitHistogram;
                tilesDescriptors.Add(scdDescriptor);
            }
            #endregion

            return tilesDescriptors;
        }
Пример #15
0
        public void Crop()
        {
            try
            {
                Bitmap postedImage = new Bitmap(_image.InputStream);

                Rectangle cropArea = new Rectangle { X = _x, Y = _y, Width = _width, Height = _height };

                Bitmap newCroppedImage = postedImage.Clone(cropArea, postedImage.PixelFormat);

                Guid fileName = Guid.NewGuid();

                ImageUrl = fileName + ".jpg";

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                    newCroppedImage.Save(path + fileName + ".jpg", ImageFormat.Jpeg);
                }
                else
                {
                    newCroppedImage.Save(path + fileName + ".jpg", ImageFormat.Jpeg);
                }
            }
            catch (OutOfMemoryException ex)
            {
                throw new OutOfMemoryException("Crazy Error", ex);
            }
            
        }
Пример #16
0
 public static Image CropImage(Image img, Rectangle cropArea)
 {
     Bitmap bmpImage = new Bitmap(img);
     Bitmap bmpCrop = bmpImage.Clone(cropArea,
     bmpImage.PixelFormat);
     return (Image)(bmpCrop);
 }
Пример #17
0
        public void Crop()
        {
            Bitmap image = new Bitmap(_image.Image.InputStream);

            Rectangle cropArea = new Rectangle();
            cropArea.X = _x;
            cropArea.Y = _y;
            cropArea.Width = _width;
            cropArea.Height = _height;

            Bitmap newImage = image.Clone(cropArea, image.PixelFormat);

            //Create unique name for new image
            string path = @"C:\Images\ProfilePictures\";
            Guid fileName = Guid.NewGuid();

            ImageUrl = path + fileName + ".jpg";

            if (!Directory.Exists(path))
	        {
		        Directory.CreateDirectory(path);
                newImage.Save(path + fileName + ".jpg", ImageFormat.Jpeg);
	        }
            else
            {
                newImage.Save(path + fileName + ".jpg", ImageFormat.Jpeg);
            }            
        }   
Пример #18
0
        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop, false);
            int fileCount = files.Count();
            if( fileCount > 6 )
            {
                fileCount = 6;
            }
            Bitmap henseiBitmap = new Bitmap(488 * 2, 376 * 3, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            Graphics henseiGraphics = Graphics.FromImage(henseiBitmap);

            List<String> fl = LoadFilePath(files);
            fl.Sort();
            for (int i = 0; i < fileCount; i++)
            {
                Console.WriteLine(fl[i]);
                Bitmap orig = new Bitmap(fl[i].ToString());
                Bitmap copy = orig.Clone(new Rectangle(312, 94, 488, 376), orig.PixelFormat);
                henseiGraphics.DrawImage(copy, henseiPosition[i, 0], henseiPosition[i, 1], copy.Width, copy.Height);
                orig.Dispose();

            }
            henseiGraphics.Dispose();
            String outPath = Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "hensei.png");
            henseiBitmap.Save(outPath);
            System.Diagnostics.Process p = System.Diagnostics.Process.Start(outPath);
        }
Пример #19
0
        private void buttonSend_Click(object sender, EventArgs e)
        {
            this.buttonSend.Enabled = false;
            IList<byte[]> imageSlices = new List<byte[]>();
            Bitmap bmp = new Bitmap(this._imageSource);
            double width = (double)bmp.Width / 5;
            double height = (double)bmp.Height / 5;
            for (int y = 0; y < 5; y++)
            {
                for (int x = 0; x < 5; x++)
                {
                    Rectangle rect = new Rectangle(Convert.ToInt32(x * width), Convert.ToInt32(y * height),
                        Convert.ToInt32(width), Convert.ToInt32(height));

                    byte[] data = BitmapToBytes(bmp.Clone(rect, PixelFormat.DontCare));
                    imageSlices.Add(data);
                }
            }

            IImageTransfer proxy = GetProxy();
            proxy.Erase();
            for (int i = 0; i < imageSlices.Count; i++)
            {
                proxy.Transfer(imageSlices[i]);
            }
            this.buttonSend.Enabled = true;
        }
Пример #20
0
        WaveGenerator wave; // The decrypted audio file.

        #endregion Fields

        #region Constructors

        public Encrypted(Bitmap encryptedImage)
        {
            InitializeComponent();
            fileName = "";

            // Convert pixel format
            encryptedImage = encryptedImage.Clone(new Rectangle(0, 0, encryptedImage.Width, encryptedImage.Height), PixelFormat.Format32bppArgb);

            encryptedImageBox.Image = encryptedImage;
            encryptedImageBox.Size = encryptedImage.Size;

            // Resize window
            int newWidth = Math.Max(this.PreferredSize.Width, 305);
            int newHeight = this.PreferredSize.Height;
            newWidth = Math.Min(newWidth, Screen.PrimaryScreen.Bounds.Width * 2 / 3);
            newHeight = Math.Min(newHeight, Screen.PrimaryScreen.Bounds.Height * 2 / 3);
            this.Size = new Size(newWidth, newHeight);

            // Enable buttons
            foreach (Control c in this.Controls)
            {
                if (c is Button)
                    c.Enabled = true;
            }
        }
Пример #21
0
        public Stroke(Bitmap bitmap,Color color,float a,float b,float c,float soft,bool flat,bool square)
        {
            //Create shape
            shape=(Bitmap)bitmap.Clone();
            for(int i=0;i<shape.Width;i++)
            {
                for(int j=0;j<shape.Height;j++)
                {
                    float x=(float)(i-shape.Width/2);
                    float y=(float)(j-shape.Height/2);
                    float len2=x*x+y*y;
                    float r=Math.Min(shape.Width/2,shape.Height/2);
                    float r2=r*r;
                    if(square||len2<=r2)
                    {
                        Color col=shape.GetPixel(i,j);
                        float ii=(((float)(col.R+col.G+col.B))/3f)/255f;
                        int aa=(int)(((a*ii*ii+b*ii+c)*(((float)color.A)/255f)*255f));
                        if(aa<0)
                            aa=0;
                        if(aa>255)
                            aa=255;
                        float sa=1f;
                        if(soft>0f)
                        {
                            sa=1f-(len2/r2)*soft;
                            if(sa<0f)
                                sa=0f;
                            if(sa>1f)
                                sa=1f;
                        }
                        if(flat)
                            shape.SetPixel(i,j,Color.FromArgb((int)(((float)aa)*sa),color));
                        else
                        {
                            Color cc=shape.GetPixel(i,j);
                            int rr=(int)((((float)cc.R)/255f)*(((float)color.R)/255f)*255f);
                            if(rr<0)
                                rr=0;
                            if(rr>255)
                                rr=255;
                            int gg=(int)((((float)cc.G)/255f)*(((float)color.G)/255f)*255f);
                            if(gg<0)
                                gg=0;
                            if(gg>255)
                                gg=255;
                            int bb=(int)((((float)cc.B)/255f)*(((float)color.B)/255f)*255f);
                            if(bb<0)
                                bb=0;
                            if(bb>255)
                                bb=255;
                            shape.SetPixel(i,j,Color.FromArgb((int)(((float)aa)*sa),rr,gg,bb));
                        }

                    }
                    else
                        shape.SetPixel(i,j,Color.FromArgb(0,0,0,0));
                }
            }
        }
Пример #22
0
        public void getScreenshots()
        {
            List<Image> screenshots = new List<Image>();
            for (int i = 0; i < Screen.AllScreens.Length; i++)
            {
                Screen screen = Screen.AllScreens[i];
                using (Bitmap bmpScreenCapture = new Bitmap(screen.Bounds.Width,
                                                screen.Bounds.Height))
                {
                    using (Graphics g = Graphics.FromImage(bmpScreenCapture))
                    {
                        g.CopyFromScreen(screen.Bounds.X,
                                         screen.Bounds.Y,
                                         0, 0,
                                         bmpScreenCapture.Size,
                                         CopyPixelOperation.SourceCopy);
                    }
                    screenshots.Add((Image)bmpScreenCapture.Clone());
                }
            }

            for (int i = 0; i < pictureboxes.Count; i++)
            {
                pictureboxes[i].Image = screenshots[i];
            }
        }
Пример #23
0
        public void UpdateImage(Bitmap bmp, bool cloneBitmap = false)
        {
            try
            {
                CountFps();
                picDesktop.Invoke((MethodInvoker) delegate
                {
                    // get old image to dispose it correctly
                    var oldImage = picDesktop.Image;

                    picDesktop.Image = cloneBitmap ? (Bitmap) bmp.Clone() : bmp;

                    if (oldImage != null)
                        oldImage.Dispose();
                });
            }
            catch (InvalidOperationException)
            {
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    string.Format(
                        "An unexpected error occurred: {0}\n\nPlease report this as fast as possible here:\\https://github.com/MaxXor/xRAT/issues",
                        ex.Message), "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Пример #24
0
 private static Image AmazonCut(Image image)
 {
     if (image.Width != image.Height)
         return image;
     var bmp = new Bitmap(image);
     int size = image.Height;
     int white = System.Drawing.Color.FromKnownColor(KnownColor.White).ToArgb();
     int i = 0;
     while (i < size/2)
     {
         if (bmp.GetPixel(i, i).ToArgb() != white)
             break;
         if (bmp.GetPixel(i, size - 1 - i).ToArgb() != white)
             break;
         if (bmp.GetPixel(size - 1 - i, i).ToArgb() != white)
             break;
         if (bmp.GetPixel(size - 1 - i, size - 1 - i).ToArgb() != white)
             break;
         i++;
     }
     if (i > 0)
     {
         i += 8;
         var zone = new Rectangle(i, i, size - 2*i, size - 2*i);
         return bmp.Clone(zone, System.Drawing.Imaging.PixelFormat.DontCare);
     }
     return bmp;
 }
Пример #25
0
        public static GameData.Image GetImage(string imageValue)
        {
            try
            {
                string[] cloumns = imageValue.Split(':');
                if (cloumns.Length != 2)
                    return null;

                string imagesetName = cloumns[0];
                string imageName = cloumns[1];

                Imageset imageset = ImagesetManager.Instance.Get(imagesetName);
                if (imageset == null)
                    return null;

                GameData.Image image = imageset.Get(imageName);
                if (image.Tag == null)
                {
                    System.Drawing.Image texture = System.Drawing.Image.FromFile(imageset.FileName);
                    Bitmap srcBitmap = new Bitmap(texture);

                    Rectangle rect = new Rectangle(image.X, image.Y, image.Width, image.Height);
                    image.Tag = srcBitmap.Clone(rect, srcBitmap.PixelFormat);
                }

                return image;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }
Пример #26
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                //Открываем файл картинки...
                System.IO.FileStream fs = new System.IO.FileStream(openFileDialog1.FileName, System.IO.FileMode.Open);
                System.Drawing.Image img = System.Drawing.Image.FromStream(fs);
                fs.Close();
                //Помещаем исходное изображение в PictureBox1
                pictureBox1.Image = img;

                var bmp = new Bitmap(img);
                label1.Text = "";
                label1.Text = label1.Text + DateTime.Now.Second.ToString() + "." + DateTime.Now.Millisecond.ToString() + " - "; //Время начала обработки (секунды и миллисекунды).
                //Преобразуем картинку
                MakeGray(bmp);
                //Crop(bmp, new Rectangle(0, 0, bmp.Height, bmp.Width));
                Bitmap cropBmp = bmp.Clone(new Rectangle(0, 0, bmp.Width / 2, bmp.Height / 2), bmp.PixelFormat);
                label1.Text = label1.Text + DateTime.Now.Second.ToString() + "." + DateTime.Now.Millisecond.ToString(); //Время окончания обработки (секунды и миллисекунды).
                //Помещаем преобразованное изображение в PictureBox2
                pictureBox2.Image = cropBmp;
                Bitmap cropcloneBmp = cropBmp.Clone(new Rectangle(0, 0, cropBmp.Width, cropBmp.Height), cropBmp.PixelFormat);
                MakeGray(cropcloneBmp);
                //Crop(bmp, new Rectangle(0, 0, bmp.Height, bmp.Width));
                Bitmap cropnewBmp = cropcloneBmp.Clone(new Rectangle(0, 0, cropcloneBmp.Width / 2, cropcloneBmp.Height / 2), cropcloneBmp.PixelFormat);
                label1.Text = label1.Text + DateTime.Now.Second.ToString() + "." + DateTime.Now.Millisecond.ToString(); //Время окончания обработки (секунды и миллисекунды).
                //Помещаем преобразованное изображение в PictureBox2
                pictureBox3.Image = cropnewBmp;
            }

        }
Пример #27
0
        /// <summary>
        /// Crops the specified raw image.
        /// </summary>
        /// <param name="rawImage">The raw image.</param>
        /// <param name="topLeft">The top left.</param>
        /// <param name="newSize">The new size.</param>
        /// <returns>Image.</returns>
        public Image Crop(Image rawImage, Point topLeft, Size newSize)
        {
            try
            {
                if (rawImage.Width < (topLeft.X + newSize.Width))
                {
                    newSize.Width = rawImage.Width - topLeft.X;
                }

                if (rawImage.Height < (topLeft.Y + newSize.Height))
                {
                    newSize.Height = rawImage.Height - topLeft.Y;
                }

                Bitmap clippedImage = new Bitmap(rawImage);

                clippedImage = clippedImage.Clone(new Rectangle(topLeft.X, topLeft.Y, newSize.Width, newSize.Height),
                    rawImage.PixelFormat);

                return clippedImage;
            }
            catch (Exception ex)
            {
                return new Bitmap(ImageFactory.Draw(ex.Message));
            }
        }
Пример #28
0
 public Card(string frontFilename, string backFilename)
 {
     Front = new Bitmap(frontFilename);
     Back = new Bitmap(backFilename);
     FrontOriginal = (Bitmap)Front.Clone();
     BackOriginal = (Bitmap)Back.Clone();
 }
Пример #29
0
 public static void LoadSprites()
 {
     SpriteList.Clear();
     Stream stream;
     if (File.Exists("sprites.png"))
     {
         stream = File.OpenRead("sprites.png");
     }
     else
     {
         var assembly = Assembly.GetExecutingAssembly();
         stream = assembly.GetManifestResourceStream("scmpoo.resources.sprites.png");
     }
     Bitmap loadedfile = new Bitmap(Image.FromStream(stream));
     int count = loadedfile.Width / loadedfile.Height;
     for (int n = 0; n < count; n++)
     {
         SpriteList.Add(loadedfile.Clone(new Rectangle(n * loadedfile.Height, 0, loadedfile.Height, loadedfile.Height), loadedfile.PixelFormat));
     }
     for (int n = 0; n < count; n++)
     {
         Bitmap b = (Bitmap)SpriteList[n].Clone();
         b.RotateFlip(RotateFlipType.RotateNoneFlipX);
         SpriteList.Add(b);
     }
 }
Пример #30
0
        /// <summary>
        /// Crop an image in the given rectangle.
        /// </summary>
        /// <param name="img"></param>
        /// <param name="cropArea"></param>
        /// <returns></returns>
        public static Image Crop(Image image, Rectangle cropArea)
        {
            Bitmap bmpImage = new Bitmap(image);
            Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);

            return bmpCrop;
        }
Пример #31
0
        private static Bitmap ApplyAlphaOnNonIndexedBitmap(Bitmap bitmapImage, IEnumerable <Color> colors)
        {
            const int bytesPerPixel = 4;

            var bmp        = (Bitmap)bitmapImage.Clone();
            var bmpData    = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
            var numBytes   = bmp.Width * bmp.Height * bytesPerPixel;
            var argbValues = new byte[numBytes];
            var ptr        = bmpData.Scan0;

            Marshal.Copy(ptr, argbValues, 0, numBytes);

            var filterValues = new List <byte[]>();

            foreach (var color in colors)
            {
                var bt = new byte[4];
                bt[0] = color.A;
                bt[1] = color.R;
                bt[2] = color.G;
                bt[3] = color.B;
                filterValues.Add(bt);
            }

            for (var counter = 0; counter < argbValues.Length; counter += bytesPerPixel)
            {
                // If 100% transparent, skip pixel
                if (argbValues[counter + bytesPerPixel - 1] == 0)
                {
                    continue;
                }

                var b = argbValues[counter];
                var g = argbValues[counter + 1];
                var r = argbValues[counter + 2];
                var a = argbValues[counter + 3];

                var found = filterValues.Any(
                    filterValue => filterValue[0] == a &&
                    filterValue[1] == r && filterValue[2] == g &&
                    filterValue[3] == b);

                if (found)
                {
                    argbValues[counter + 3] = 0;
                }
            }

            Marshal.Copy(argbValues, 0, ptr, numBytes);
            bmp.UnlockBits(bmpData);

            return(bmp);
        }
Пример #32
0
        private static unsafe void _LoadTextureRawXNA(GraphicsDevice gd, Stream stream, out int w, out int h, out byte[] data, out IntPtr dataPtr, bool gc)
        {
            using (SD.Bitmap bmp = new SD.Bitmap(stream)) {
                w = bmp.Width;
                h = bmp.Height;
                int depth = SD.Image.GetPixelFormatSize(bmp.PixelFormat);

                SD.Bitmap copy = null;
                if (depth != 32)
                {
                    copy = bmp.Clone(new SD.Rectangle(0, 0, w, h), SDI.PixelFormat.Format32bppArgb);
                }
                using (copy) {
                    SD.Bitmap src = copy ?? bmp;

                    SDI.BitmapData srcData = src.LockBits(
                        new SD.Rectangle(0, 0, w, h),
                        SDI.ImageLockMode.ReadOnly,
                        src.PixelFormat
                        );

                    int length = w * h * 4;
                    if (gc)
                    {
                        data    = new byte[length];
                        dataPtr = IntPtr.Zero;
                    }
                    else
                    {
                        data    = new byte[0];
                        dataPtr = Marshal.AllocHGlobal(length);
                    }

                    byte *from = (byte *)srcData.Scan0;
                    fixed(byte *dataPin = data)
                    {
                        byte *to = gc ? dataPin : (byte *)dataPtr;

                        for (int i = length - 1 - 3; i > -1; i -= 4)
                        {
                            to[i + 0] = from[i + 2];
                            to[i + 1] = from[i + 1];
                            to[i + 2] = from[i + 0];
                            to[i + 3] = from[i + 3];
                        }
                    }

                    src.UnlockBits(srcData);
                }
            }
        }
Пример #33
0
 private void RefreshExemplo()
 {
     System.Drawing.Graphics graf;
     System.Drawing.Pen      caneta;
     System.Drawing.Bitmap   imagem = new System.Drawing.Bitmap(m_pnExemplo.Width, m_pnExemplo.Height);
     graf             = System.Drawing.Graphics.FromImage(imagem);
     caneta           = new System.Drawing.Pen(m_corCaneta, m_nEspessura);
     caneta.DashStyle = m_styEstilo;
     graf.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.White), 0, 0, m_pnExemplo.Width, m_pnExemplo.Height);
     graf.DrawLine(caneta, 5, ((int)m_pnExemplo.Height / 2), ((int)m_pnExemplo.Width - 10), ((int)m_pnExemplo.Height / 2));
     graf = null;
     m_pnExemplo.BackgroundImage = (System.Drawing.Image)imagem.Clone();
     imagem = null;
 }
Пример #34
0
        private void button1_Click(object sender, EventArgs e)
        {
            m_Undo = (Bitmap)m_Bitmap.Clone();
            if (GaussianBlurr(m_Bitmap, 4))
            {
                this.Invalidate();
            }

            pictureBox1.Image = m_Bitmap;
            SaveFileDialog saveFileDialog = new SaveFileDialog();


            m_Bitmap.Save("C:\\Users\\MehmetCan\\Desktop\\Blurr.png");
        }
Пример #35
0
 private void Light_reduction_Click(object sender, EventArgs e)
 {
     try
     {
         if (curBitmap != null)
         {
             Color pixel;
             int   red, green, blue;
             for (int x = 0; x < curBitmap.Width; x++)
             {
                 for (int y = 0; y < curBitmap.Height; y++)
                 {
                     pixel = curBitmap.GetPixel(x, y);
                     red   = (int)(pixel.R * 0.6);
                     green = (int)(pixel.G * 0.6);
                     blue  = (int)(pixel.B * 0.6);
                     curBitmap.SetPixel(x, y, Color.FromArgb(red, green, blue));
                 }
             }
             pB.Image = curBitmap.Clone() as Image;
         }
     }
     catch (Exception ex) { MessageBox.Show(ex.Message, "信息提示"); }
 }
Пример #36
0
 public static void pastebackground()
 {
     if (background != null)
     {
         Graph.bitmap.SysDraw = (System.Drawing.Bitmap)background.Clone();
         if (Graph.imediateDrawing)
         {
             delay(0);
         }
     }
     else
     {
         throw new Exception("No background is copied!");
     }
 }
Пример #37
0
        private void ChangePosition(int x_rel, int y_rel, int w = 88, int h = 88, int pxs = 8)
        {
            int lt = (w / pxs) / 2; int rb = (h / pxs) / 2;
            var p = new System.Windows.Point(x_rel, y_rel);

            var rpos = p - new System.Windows.Point((int)lt, (int)rb);

            cp.Location = p;
            cp.Zoom     = pxs;
            var image = bmp.Clone() as System.Drawing.Bitmap;
            var clr   = image.GetPixel(x_rel, y_rel);

            cp.Color = System.Windows.Media.Color.FromRgb(clr.R, clr.G, clr.B);
            var _bmp = new System.Drawing.Bitmap(w, h);

            for (int x = (int)rpos.X; x <= rpos.X + (int)lt * 2; x++)
            {
                for (int y = (int)rpos.Y; y <= rpos.Y + (int)rb * 2; y++)
                {
                    if (x < 0 || y < 0 || x >= image.Width || y >= image.Height)
                    {
                        _bmp.SetPixel(Math.Abs((x - (int)rpos.X) * pxs), Math.Abs((y - (int)rpos.Y) * pxs), System.Drawing.Color.Black);
                    }
                    else
                    {
                        for (int i = (x - (int)rpos.X) * pxs; i < (x - rpos.X) * pxs + pxs; i++)
                        {
                            for (int j = (y - (int)rpos.Y) * pxs; j < (y - rpos.Y) * pxs + pxs; j++)
                            {
                                try {
                                    _bmp.SetPixel(i, j, image.GetPixel(x, y));
                                } catch { }
                            }
                        }
                    }
                }
            }
            BitmapImage bmpI = new BitmapImage();

            bmpI.BeginInit();
            MemoryStream memoryStream = new MemoryStream();

            _bmp.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
            memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
            bmpI.StreamSource = memoryStream;
            bmpI.EndInit();
            cp.Source = bmpI;
        }
Пример #38
0
        static public System.Drawing.Bitmap Crop(System.Drawing.Bitmap bitmap, Rectangle croparea)
        {
            // Definitions
            Bitmap result = null;

//			try
//			{
            // Crop image.
            result = bitmap.Clone(croparea, bitmap.PixelFormat);
//			}
//			catch
//			{}

            // Finish
            return(result);
        }
Пример #39
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/laser1.wav";

            int xmin, ymin, xmax, ymax;

            if (x <= targetx)
            {
                xmin = x - 5; xmax = targetx + 5;
            }
            else
            {
                xmin = targetx - 5; xmax = x + 3;
            }
            if (y <= targety)
            {
                ymin = y - 5; ymax = targety + 5;
            }
            else
            {
                ymin = targety - 5; ymax = y + 5;
            }

            Graphics  g = Graphics.FromImage(bmFull);
            Rectangle rect;
            Image     oldImage;

            rect = new Rectangle(xmin, ymin, xmax - xmin, ymax - ymin);

            oldImage = bmFull.Clone(rect, bmFull.PixelFormat);

            Pen laserPen1 = new Pen(Color.GreenYellow, 2);

            player.Play();
            for (int i = 0; i < 5; i++)
            {
                g.DrawLine(laserPen1, new Point(x, y), new Point(targetx + i, targety));

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

                System.Threading.Thread.Sleep(35);
            }
            g.DrawImage(oldImage, xmin, ymin);
            pictureMap.Refresh();
        }
Пример #40
0
        public static void DrawLegacyArmL(int scale, bool legacy, bool slim, Graphics g, System.Drawing.Bitmap skin, bool HatLayer = false)
        {
            int preview_x = (slim ? 1 : 0);
            int preview_y = 8;

            int source_x      = (HatLayer ? 44 : 44);
            int source_y      = (HatLayer ? 36 : 20);
            int source_width  = (slim ? 3 : 4);
            int source_height = 12;

            var    clip = new Rectangle(source_x * scale, source_y * scale, source_width * scale, source_height * scale);
            Bitmap part = skin.Clone(clip, skin.PixelFormat);

            part.RotateFlip(RotateFlipType.RotateNoneFlipX);
            g.DrawImage(part, new Rectangle(preview_x * scale, preview_y * scale, source_width * scale, source_height * scale));
            part.Dispose();
        }
Пример #41
0
        /// <summary>
        /// Dumps this BitmapBuffer to a new System.Drawing.Bitmap
        /// </summary>
        public unsafe Bitmap ToSysdrawingBitmap()
        {
            if (WrappedBitmap != null)
            {
                return((Bitmap)WrappedBitmap.Clone());
            }
            var pf = PixelFormat.Format32bppArgb;

            if (!HasAlpha)
            {
                pf = PixelFormat.Format24bppRgb;
            }
            Bitmap bmp = new Bitmap(Width, Height, pf);

            ToSysdrawingBitmap(bmp);
            return(bmp);
        }
Пример #42
0
        /// <summary>
        /// Convertir a escala de grises, es necesario optimizarlo con LockBitmap
        /// </summary>
        /// <param name="Bitmap"></param>
        /// <returns></returns>
        public static Bitmap GrayScale(System.Drawing.Bitmap Bitmap)
        {
            System.Drawing.Bitmap
                bitmap = (System.Drawing.Bitmap)Bitmap.Clone();

            System.Drawing.Color color;

            for (System.Int32 i = 0; i < bitmap.Width; i++)
            {
                for (System.Int32 j = 0; j < bitmap.Height; j++)
                {
                    color = bitmap.GetPixel(i, j);
                    color = ColorToGrey(color);
                    Bitmap.SetPixel(i, j, color);
                }
            }
            return(Bitmap);
        }
        /// <summary>
        /// Sets the provided cardBox image equal to the card provided and makes the cardBox visible.
        /// </summary>
        /// <param name="card"></param>
        /// <param name="cardBox"></param>
        /// <returns></returns>
        private void setCard(byte card, System.Windows.Forms.PictureBox cardBox)
        {
            if (card != 0)
            {
                System.Drawing.Bitmap allCards = global::PokerBot.CacheMonitor.Properties.Resources.compactCards1;

                int xStart = (((int)(card - 1) / 4) * 52) + 2;
                int yStart = ((card - 1) % 4 * 70) + 1;

                cardBox.Image    = (System.Drawing.Bitmap)allCards.Clone(new System.Drawing.Rectangle(xStart, yStart, 49, 68), allCards.PixelFormat);
                cardBox.SizeMode = PictureBoxSizeMode.StretchImage;
                cardBox.Visible  = true;
            }
            else
            {
                blankCard(cardBox);
            }
        }
Пример #44
0
        /// <summary>
        /// 居中裁剪
        /// </summary>
        public void CutForSquare(Size size)
        {
            this.SacleTo(size, ScaleMode.Fill_XY_Center);

            var initImage = this.bitmap;
            //原始图片的宽、高
            int initWidth  = initImage.Width;
            int initHeight = initImage.Height;

            //对象实例化
            var pickedImage = new System.Drawing.Bitmap(initHeight, initHeight);
            var pickedG     = System.Drawing.Graphics.FromImage(pickedImage);

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

            if (initWidth > initHeight)
            {
                var x = (initWidth - size.Width) / 2;
                //定位
                Rectangle fromR = new Rectangle(x, 0, size.Width, size.Height);
                Rectangle toR   = new Rectangle(0, 0, initHeight, initHeight);
                //画图
                pickedG.DrawImage(initImage, toR, fromR, GraphicsUnit.Pixel);
            }
            else
            {
                var y = (initHeight - size.Height) / 2;
                //定位
                Rectangle fromR = new Rectangle(0, y, size.Width, size.Height);
                Rectangle toR   = new Rectangle(0, 0, initHeight, initHeight);
                pickedG.DrawImage(initImage, toR, fromR, GraphicsUnit.Pixel);
            }

            initImage = (System.Drawing.Bitmap)pickedImage.Clone();
            var img = new Bitmap(initImage, size);

            this.bitmap = img;

            //释放截图资源
            pickedG.Dispose();
            pickedImage.Dispose();
        }
Пример #45
0
        public void TakeScreenshot(string numer, IWebDriver driver, IWebElement element)
        {
            Byte[] byteArray = ((ITakesScreenshot)driver).GetScreenshot().AsByteArray;
            using (System.Drawing.Bitmap screenshot = new System.Drawing.Bitmap(new System.IO.MemoryStream(byteArray)))
            {
                Rectangle croppedImage = new Rectangle(element.Location.X, element.Location.Y, element.Size.Width, element.Size.Height);

                Rectangle all = new Rectangle(0, 0, screenshot.Width, screenshot.Height);

                croppedImage.Intersect(all);

                //croppedImage.Intersect(new Rectangle(0, 0, element.Size.Width, element.Size.Height));

                using (System.Drawing.Bitmap screenshot2 = screenshot.Clone(croppedImage, screenshot.PixelFormat))
                {
                    screenshot2.Save(sciezkaplikuJpg + numer + ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }
        }
Пример #46
0
        public static Bitmap getBitmap()
        {
            IDataObject ido = System.Windows.Forms.Clipboard.GetDataObject();

            if (ido == null)
            {
                return(null);
            }

            if (!ido.GetDataPresent("System.Drawing.Bitmap"))
            {
                return(null);
            }

            System.Drawing.Bitmap bmp = (System.Drawing.Bitmap)ido.GetData("System.Drawing.Bitmap");
            bmp = bmp.Clone(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            return(bmp);
        }
Пример #47
0
        /// <summary>
        /// 剪切图片,另存
        /// </summary>
        /// <param name="oldImgPath">原图片地址</param>
        /// <param name="newImgPath">新图片保存地址</param>
        /// <param name="newFileName">新图片名称</param>
        /// <param name="inputWidth">截取宽度</param>
        /// <param name="inputLength">截取长度</param>
        public static void ShearingImg(string oldImgPath, string newImgPath, string newFileName, int inputWidth = 100, int inputLength = 100)
        {
            //原图片路径
            String oldPath = oldImgPath;

            //新图片路径
            String newPath  = System.IO.Path.GetExtension(newImgPath);
            string fileName = Path.GetFileName(oldImgPath);

            string[] str = fileName.Split('.');

            //设置截取的坐标和大小
            int x = 0, y = 0, width = inputWidth, height = inputLength;

            //计算新的文件名
            newPath = newImgPath + newFileName + "." + str[1];
            //定义截取矩形
            System.Drawing.Rectangle cropArea = new System.Drawing.Rectangle(x, y, width, height); //要截取的区域大小

            //加载图片
            System.Drawing.Image img = System.Drawing.Image.FromStream(new System.IO.MemoryStream(System.IO.File.ReadAllBytes(oldPath)));

            //判断超出的位置否
            if ((img.Width < x + width) || img.Height < y + height)
            {
                //截取的区域超过了图片本身的高度、宽度.
                img.Dispose();
                return;
            }
            //定义Bitmap对象
            System.Drawing.Bitmap bmpImage = new System.Drawing.Bitmap(img);

            //进行裁剪
            System.Drawing.Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);

            //保存成新文件
            bmpCrop.Save(newPath);

            //释放对象
            img.Dispose();
            bmpCrop.Dispose();
        }
Пример #48
0
        /// <summary>
        /// 指定した Bitmap の色を反転します。
        /// </summary>
        /// <param name="source">反転前の画像を指定します。</param>
        /// <returns>反転後の画像を指定します。</returns>
        public static System.Drawing.Bitmap Invert(System.Drawing.Bitmap source)
        {
            System.Drawing.Bitmap    bmp  = (System.Drawing.Bitmap)source.Clone();
            System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height);
            Imaging.BitmapData       data = bmp.LockBits(rect, Imaging.ImageLockMode.ReadWrite, Imaging.PixelFormat.Format32bppArgb);

            System.IntPtr scan0 = data.Scan0;
            int           M     = bmp.Width * bmp.Height;

            unsafe {
                Color32Argb *p  = (Color32Argb *)(void *)scan0;
                Color32Argb *pM = p + M;
                while (p < pM)
                {
                    *p = ~*p; p++;
                }
            }
            bmp.UnlockBits(data);
            return(bmp);
        }
Пример #49
0
        /// <summary>
        /// Convert an IImage to a WPF BitmapSource. The result can be used in the Set Property of Image.Source
        /// </summary>
        /// <param name="bitmap">The Source Bitmap</param>
        /// <returns>The equivalent BitmapSource</returns>
        public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap bitmap)
        {
            if (bitmap == null)
            {
                return(null);
            }

            using var source = (System.Drawing.Bitmap)bitmap.Clone();
            var hBitmap = source.GetHbitmap(); //obtain the Hbitmap

            var bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                System.Windows.Int32Rect.Empty,
                System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());

            NativeMethods.DeleteObject(hBitmap); //release the HBitmap
            bs.Freeze();
            return(bs);
        }
Пример #50
0
        /// <summary>
        /// Loads the bitmap by cloning its data to a more compatible format.
        /// </summary>
        /// <param name="bitmap">
        /// A <see cref="Drawing.Bitmap"/> to be converted into an <see cref="Image"/> instance.
        /// </param>
        /// <param name='image'>
        /// A <see cref="Image"/> instance that will store <paramref name="bitmap"/> data.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// Exception thrown if <paramref name="bitmap"/> or <paramref name="image"/> is null.
        /// </exception>
        /// <remarks>
        /// <para>
        /// Cloning <paramref name="bitmap"/> is useful whenever the bitmap have a pixel format not directly portable
        /// to any well-known format (i.e. 1 bit pixel, palettized pixel, etc.).
        /// </para>
        /// <para>
        /// This method is very memory consuming, because cloning cause to use additionally memory.
        /// </para>
        /// </remarks>
        private static void LoadBitmapByClone(System.Drawing.Bitmap bitmap, Image image)
        {
            if (bitmap == null)
            {
                throw new ArgumentNullException("bitmap");
            }
            if (image == null)
            {
                throw new ArgumentNullException("image");
            }

            System.Drawing.Imaging.PixelFormat iBitmapFormat;
            int iBitmapFlags;

            // Determine the clone bitmap pixel format
            ConvertPixelFormat(image.PixelLayout, out iBitmapFormat, out iBitmapFlags);
            // Clone image converting the pixel format
            using (System.Drawing.Bitmap clonedBitmap = bitmap.Clone(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), iBitmapFormat)) {
                LoadBitmapByLockBits(clonedBitmap, image);
            }
        }
Пример #51
0
        private PageContent generatePageContent(System.Drawing.Bitmap bmp, int top,
                                                int bottom, double pageWidth, double PageHeight,
                                                System.Printing.PrintCapabilities capabilities)
        {
            FixedPage printDocumentPage = new FixedPage();

            printDocumentPage.Width  = pageWidth;
            printDocumentPage.Height = PageHeight;

            int newImageHeight = bottom - top;

            System.Drawing.Bitmap bmpPage = bmp.Clone(new System.Drawing.Rectangle(0, top,
                                                                                   bmp.Width, newImageHeight), System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            // Create a new bitmap for the contents of this page
            Image        pageImage = new Image();
            BitmapSource bmpSource =
                System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    bmpPage.GetHbitmap(),
                    IntPtr.Zero,
                    System.Windows.Int32Rect.Empty,
                    BitmapSizeOptions.FromWidthAndHeight(bmp.Width, newImageHeight));

            pageImage.Source            = bmpSource;
            pageImage.VerticalAlignment = VerticalAlignment.Top;

            // Place the bitmap on the page
            printDocumentPage.Children.Add(pageImage);

            PageContent pageContent = new PageContent();

            ((System.Windows.Markup.IAddChild)pageContent).AddChild(printDocumentPage);

            FixedPage.SetLeft(pageImage, capabilities.PageImageableArea.OriginWidth);
            FixedPage.SetTop(pageImage, capabilities.PageImageableArea.OriginHeight);

            pageImage.Width  = capabilities.PageImageableArea.ExtentWidth;
            pageImage.Height = capabilities.PageImageableArea.ExtentHeight;
            return(pageContent);
        }
Пример #52
0
        public System.Drawing.Bitmap Proccess(System.Drawing.Bitmap inBitmap, bool disposeOrigin)
        {
            if (inBitmap == null)
            {
                return(null);
            }
            Bitmap bitmap = (Bitmap)inBitmap.Clone();

            if (_isflipX)
            {
                bitmap.RotateFlip(RotateFlipType.Rotate180FlipX);
            }
            else
            {
                bitmap.RotateFlip(RotateFlipType.Rotate180FlipY);
            }
            if (disposeOrigin)
            {
                inBitmap.Dispose();
            }
            return(bitmap);
        }
Пример #53
0
        public System.Drawing.Bitmap Proccess(System.Drawing.Bitmap inBitmap, bool disposeOrigin)
        {
            if (inBitmap == null)
            {
                return(null);
            }
            Bitmap bitmap = null;

            if (_zoomToSize == SizeF.Empty)
            {
                bitmap = (Bitmap)inBitmap.Clone();
            }
            else
            {
                bitmap = new Bitmap(inBitmap, (int)_zoomToSize.Width, (int)_zoomToSize.Height);
            }
            if (disposeOrigin)
            {
                inBitmap.Dispose();
            }
            return(bitmap);
        }
Пример #54
0
        public static Bitmap[] BitmapToSixFortySeven(Bitmap bmp)
        {
            // Determine size of the output array
            int size = (bmp.Size.Width / 64) * (bmp.Size.Height / 96);

            Bitmap[] outputBitmaps = new Bitmap[size];

            int index = 0;

            for (var i = 0; i < bmp.Size.Height / 96; i++)
            {
                for (var j = 0; j < bmp.Size.Width / 64; j++)
                {
                    // each cell in a row
                    outputBitmaps[index] = bmp.Clone(new System.Drawing.Rectangle(j * 64, i * 96, 64, 96), PixelFormat.Format32bppArgb);
                    //outputBitmaps[index].Save("tempFile" + index + ".png", ImageFormat.Png);
                    index++;
                }
            }

            return(outputBitmaps);
        }
Пример #55
0
        /// <summary>
        /// 指定した色で指定した System.Drawing.Bitmap を塗りつぶして返します。
        /// 透明度は保持します。
        /// </summary>
        /// <param name="source">塗りつぶす前の画像を指定します。</param>
        /// <param name="color">塗り潰すのに使用する色を指定します。</param>
        /// <returns>塗り潰した結果の Bitmap を返します。</returns>
        public static System.Drawing.Bitmap ClearRGB(System.Drawing.Bitmap source, Color32Argb color)
        {
            System.Drawing.Bitmap    bmp  = (System.Drawing.Bitmap)source.Clone();
            System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height);
            Imaging.BitmapData       data = bmp.LockBits(rect, Imaging.ImageLockMode.ReadWrite, Imaging.PixelFormat.Format32bppArgb);

            System.IntPtr scan0 = data.Scan0;
            int           M     = bmp.Width * bmp.Height;

            unsafe {
                Color32Argb *p = (Color32Argb *)(void *)scan0;
                for (int cnt = 0; cnt < M; cnt++)
                {
                    p->R = color.R;
                    p->G = color.G;
                    p->B = color.B;
                    p++;
                }
            }
            bmp.UnlockBits(data);
            return(bmp);
        }
Пример #56
0
 /// <summary>
 /// Save generated graphic
 /// </summary>
 /// <param name="dispose">If done generating graphics, use to dispose of drawing objects</param>
 protected void Save(bool dispose)
 {
     try {
         if (dispose)
         {
             if (_format == ImageFormat.Jpeg && _jpegQuality < 100)
             {
                 // save compressed JPEG
                 Utility.SaveJpegWithCompression(_bitmap, _absolutePath, _jpegQuality);
             }
             else
             {
                 _bitmap.Save(_absolutePath, _format);
             }
             if (_borderPen != null)
             {
                 _borderPen.Dispose();
             }
             if (_foregroundBrush != null)
             {
                 _foregroundBrush.Dispose();
             }
             if (_graphic != null)
             {
                 _graphic.Dispose();
             }
             _bitmap.Dispose();
         }
         else
         {
             // save clone only so bitmap can be re-used
             Bitmap copy = (Bitmap)_bitmap.Clone();
             copy.Save(_absolutePath, _format);
         }
     } catch (System.Exception e) {
         Idaho.Exception.Log(e, Idaho.Exception.Types.FileSystem);
     }
 }
Пример #57
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);
            }
        }
Пример #58
0
        //显示关键点
        private void Point_show_btn(object sender, RoutedEventArgs e)
        {
            if (flag_source_1 == 0 || flag_source_2 == 0)
            {
                MessageBox.Show("请首先将两张图片上传", "提示");
                return;
            }
            if (flag_keypoints == 0)
            {
                int num = Source_point_1.row;
                //使用蓝点标出图像关键点
                Bitmap Image_face_1_clone = (Bitmap)Image_face_1.Clone();
                Bitmap Image_face_2_clone = (Bitmap)Image_face_2.Clone();

                for (int i = 0; i < num; i++)
                {
                    for (int j = -2; j < 3; j++)
                    {
                        for (int k = -2; k < 3; k++)
                        {
                            Image_face_1_clone.SetPixel((int)Source_point_2[i, 1] + j, (int)Source_point_2[i, 2] + k, System.Drawing.Color.FromArgb(0, 0, 255));
                            Image_face_2_clone.SetPixel((int)Source_point_1[i, 1] + j, (int)Source_point_1[i, 2] + k, System.Drawing.Color.FromArgb(0, 0, 255));
                        }
                    }
                }
                Image_face_ori2.Source = BitmaptoImage(Image_face_2_clone);
                Image_face_ori1.Source = BitmaptoImage(Image_face_1_clone);
                flag_keypoints         = 1;
            }
            else if (flag_keypoints == 1)
            {
                Image_face_ori2.Source = BitmaptoImage(Image_face_2);
                Image_face_ori1.Source = BitmaptoImage(Image_face_1);
                flag_keypoints         = 0;
            }
        }
Пример #59
0
        private string SolveCaptcha(Image img)
        {
            Bitmap imagem = new Bitmap(img);

            SetPixelColor(imagem, false);
            SetPixelColor(imagem, false);
            string filename = "test/" + Guid.NewGuid().ToString() + ".png";

            SetPixelColor(imagem, false);
            imagem = ProcessImage(imagem);
            imagem.Save(filename);

            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(filename);
            var imageClone = bitmap.Clone(new Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            Erosion        erosion    = new Erosion();
            Dilatation     dilatation = new Dilatation();
            Invert         inverter   = new Invert();
            ColorFiltering cor        = new ColorFiltering();

            cor.Red   = new AForge.IntRange(150, 255);
            cor.Green = new AForge.IntRange(150, 255);
            cor.Blue  = new AForge.IntRange(128, 255);
            Opening            open  = new Opening();
            BlobsFiltering     bc    = new BlobsFiltering();
            Closing            close = new Closing();
            GaussianSharpen    gs    = new GaussianSharpen();
            ContrastCorrection cc    = new ContrastCorrection();
            FiltersSequence    seq   = new FiltersSequence(cc, gs, inverter, cor, bc, cor, cc, cor, bc);

            var image   = seq.Apply(imageClone);
            var byteImg = ImageToByte(image);
            var result  = OCR(ByteToImage(byteImg));

            return(result);
        }
Пример #60
0
 public static System.Drawing.Bitmap cropImage(System.Drawing.Bitmap source, System.Drawing.Rectangle section)
 {
     return(source.Clone(section, source.PixelFormat));
 }