Csharp/C Sharp/GUI Windows Form/Bitmap

Материал из .Net Framework эксперт
Версия от 11:33, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Bitmap Color

/*
GDI+ Programming in C# and VB .NET
by Nick Symmonds
Publisher: Apress
ISBN: 159059035X
*/

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
namespace BitmapColor_c
{
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class BitmapColor : System.Windows.Forms.Form
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ruponentModel.Container components = null;
        public BitmapColor()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();
            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
      // 
      // Form1
      // 
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(292, 273);
      this.Name = "Form1";
      this.Text = "Form1";
      this.Load += new System.EventHandler(this.Form1_Load);
        }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main() 
        {
            Application.Run(new BitmapColor());
        }
    
        private void Form1_Load(object sender, System.EventArgs e)
        {
          ColorPalette cp;
          String s;
          Bitmap bmp = new Bitmap("crane.jpg");
    
          cp = bmp.Palette;
    
          foreach (Color c in cp.Entries)
          {
            s = c.ToString();
          }
    
    
        }
    
        protected override void OnPaint(PaintEventArgs e)
        {
          Bitmap bmp = new Bitmap("crane.jpg");
          Color c;
    
          e.Graphics.DrawImage( bmp, 10, 30 );
    
          for ( int x=0; x<bmp.Width-1; x++ )
          {
            for ( int y=0; y<bmp.Height-1; y++ )
            {
              c = bmp.GetPixel( x, y );
              c = Color.FromArgb( c.ToArgb() + 100 );
              bmp.SetPixel( x, y, c );
            }
          }
          e.Graphics.DrawImage( bmp, 150, 30 );
        }
    }
}

<A href="http://www.nfex.ru/Code/CSharpDownload/BitmapColor-c.zip">BitmapColor-c.zip( 7 k)</a>


Bitmap Demo

/*
GDI+ Programming in C# and VB .NET
by Nick Symmonds
Publisher: Apress
ISBN: 159059035X
*/
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
namespace BitMapExt_c
{
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class BitMapExt : System.Windows.Forms.Form
    {
    #region Class Local Variables
    private Bitmap WholeBMP;
    private Bitmap SaveBMP;
    private Bitmap TLBMP;
    private Bitmap TRBMP;
    private Bitmap BLBMP;
    private Bitmap BRBMP;
    private Rectangle DrawRect;
    private Point TLpt;
    private Point TRpt;
    private Point BLpt;
    private Point BRpt;
    private int Counter = 0;
    private ImageAttributes Ia;
    #endregion 
    private System.ruponentModel.IContainer components;
    private System.Windows.Forms.Timer T1;
    private System.Windows.Forms.Button cmdGo;

    public BitMapExt() {
            InitializeComponent();
      this.SetStyle(ControlStyles.DoubleBuffer, true);
      this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
      WholeBMP = new Bitmap("crane.jpg");
      DrawRect = new Rectangle(0, 0, WholeBMP.Width, WholeBMP.Height);
      DrawRect.X = this.Width/2 - WholeBMP.Width/2;
      DrawRect.Y = this.Height/2 - WholeBMP.Height/2;
      T1.Interval = 75;
      T1.Enabled = false;
    }
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
      if (WholeBMP != null)
        WholeBMP.Dispose();
      if (SaveBMP != null)
        SaveBMP.Dispose();
      if (TLBMP != null)
        TLBMP.Dispose();
      if (TRBMP != null)
        TRBMP.Dispose();
      if (BLBMP != null)
        BLBMP.Dispose();
      if (BRBMP != null)
        BRBMP.Dispose();
      if (Ia != null)
        Ia.Dispose();
            base.Dispose( disposing );
        }
        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
      this.ruponents = new System.ruponentModel.Container();
      this.cmdGo = new System.Windows.Forms.Button();
      this.T1 = new System.Windows.Forms.Timer(this.ruponents);
      this.SuspendLayout();
      // 
      // cmdGo
      // 
      this.cmdGo.Location = new System.Drawing.Point(328, 336);
      this.cmdGo.Name = "cmdGo";
      this.cmdGo.Size = new System.Drawing.Size(48, 24);
      this.cmdGo.TabIndex = 0;
      this.cmdGo.Text = "GO";
      this.cmdGo.Click += new System.EventHandler(this.Explode);
      // 
      // T1
      // 
      this.T1.Tick += new System.EventHandler(this.T1_Tick);
      // 
      // Form1
      // 
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(392, 373);
      this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                  this.cmdGo});
      this.MaximizeBox = false;
      this.MinimizeBox = false;
      this.Name = "Form1";
      this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
      this.Text = "Exploding Bitmap";
      this.Load += new System.EventHandler(this.Form1_Load);
      this.ResumeLayout(false);
    }
        #endregion
        [STAThread]
        static void Main() 
        {
            Application.Run(new BitMapExt());
        }
    private void Form1_Load(object sender, System.EventArgs e)
    {
    }
    protected override void OnPaint(PaintEventArgs e)
    {
      Graphics G = e.Graphics;
      if ( WholeBMP != null )    
      {
        G.DrawImage(WholeBMP, DrawRect);
        return;
      }
      
      if ( TLBMP != null )
        G.DrawImage( TLBMP, new Rectangle(TLpt, TLBMP.Size),
          0, 0,
          TLBMP.Width, TLBMP.Height,
          GraphicsUnit.Pixel, 
          Ia );
      if ( TRBMP != null )
        G.DrawImage( TRBMP, new Rectangle(TRpt, TRBMP.Size),
          0, 0,
          TRBMP.Width, TRBMP.Height,
          GraphicsUnit.Pixel, 
          Ia );
      
      if ( BLBMP != null )
        G.DrawImage( BLBMP, new Rectangle(BLpt, BLBMP.Size),
          0, 0,
          BLBMP.Width, BLBMP.Height,
          GraphicsUnit.Pixel, 
          Ia );
      
      if ( BRBMP != null )
        G.DrawImage( BRBMP, new Rectangle(BRpt, BRBMP.Size),
          0, 0,
          BRBMP.Width, BRBMP.Height,
          GraphicsUnit.Pixel, 
          Ia );
      }
    private void Explode(object sender, System.EventArgs e)
    {
      if ( WholeBMP != null )
      {
        cmdGo.Enabled = false;
        int L = 0;
        int T = 0;
        int Cx = (int)(WholeBMP.Width/2);
        int Cy = (int)(WholeBMP.Height/2);
        Rectangle R1 = new Rectangle( L, T, Cx, Cy );
        Rectangle R2 = new Rectangle( Cx, T, Cx, Cy );
        Rectangle R3 = new Rectangle( L, Cy, Cx, Cy );
        Rectangle R4 = new Rectangle( Cx, Cy, Cx, Cy );
        SaveBMP = WholeBMP;
        TLBMP = WholeBMP.Clone(new Rectangle( L, T, Cx, Cy ), 
                                WholeBMP.PixelFormat);
        TRBMP = WholeBMP.Clone(new Rectangle( Cx, T, Cx, Cy ), 
                                WholeBMP.PixelFormat);
        BLBMP = WholeBMP.Clone(new Rectangle( L, Cy, Cx, Cy ), 
                                WholeBMP.PixelFormat);
        BRBMP = WholeBMP.Clone(new Rectangle( Cx, Cy, Cx, Cy ), 
                                WholeBMP.PixelFormat);
        WholeBMP = null;
        
        int Gap = 10;
        TLpt = new Point( DrawRect.Left-Gap, DrawRect.Top-Gap );
        TRpt = new Point( DrawRect.Left+Cx+Gap, DrawRect.Top-Gap );
        BLpt = new Point( DrawRect.Left-Gap, DrawRect.Top+Cy+Gap );
        BRpt = new Point( DrawRect.Left+Cx+Gap, DrawRect.Top+Cy+Gap );
        T1.Enabled = true;
        Invalidate();
      }
    }
    private void T1_Tick(object sender, System.EventArgs e)
    {
      Counter += 1;
      if ( Counter == 62 )
      {
        Counter = 0;
        cmdGo.Enabled = true;
        T1.Enabled = false;
        WholeBMP = SaveBMP;
      }
      TLpt.X-=1;
      TLpt.Y-=1;
      TRpt.X+=1;
      TRpt.Y-=1;
      BLpt.X-=1;
      BLpt.Y+=1;
      BRpt.X+=1;
      BRpt.Y+=1;
      // Initialize a color matrix.
      //Set the alpha for the whole image
      float[][] m ={new float[] {1, 0, 0, 0, 0},
                    new float[] {0, 1, 0, 0, 0},
                    new float[] {0, 0, 1, 0, 0},
                    new float[] {0, 0, 0, (1-(float)Counter/62), 0}, 
                    new float[] {0, 0, 0, 0, 1}}; 
      ColorMatrix cm = new ColorMatrix(m);
      // Create an ImageAttributes object and set its color matrix.
      Ia = new ImageAttributes();
      Ia.SetColorMatrix( cm, ColorMatrixFlag.Default, 
                              ColorAdjustType.Bitmap);
      TLBMP.RotateFlip(RotateFlipType.Rotate90FlipNone);
      TRBMP.RotateFlip(RotateFlipType.Rotate90FlipNone);
      BLBMP.RotateFlip(RotateFlipType.Rotate90FlipNone);
      BRBMP.RotateFlip(RotateFlipType.Rotate90FlipNone);
      Invalidate();
    }
    }
}

<A href="http://www.nfex.ru/Code/CSharpDownload/BitMapExt-c.zip">BitMapExt-c.zip( 8 k)</a>


Bitmap Other

/*
GDI+ Programming in C# and VB .NET
by Nick Symmonds
Publisher: Apress
ISBN: 159059035X
*/
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
namespace BitmapOther_c
{
    /// <summary>
    /// Summary description for BitmapOther.
    /// </summary>
  public class BitmapOther : System.Windows.Forms.Form
  {
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ruponentModel.Container components = null;
    public BitmapOther()
    {
      //
      // Required for Windows Form Designer support
      //
      InitializeComponent();
      //
      // TODO: Add any constructor code after InitializeComponent call
      //
    }
    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
      if( disposing )
      {
        if (components != null) 
        {
          components.Dispose();
        }
      }
      base.Dispose( disposing );
    }
        #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
      // 
      // BitmapOther
      // 
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(292, 273);
      this.Name = "BitmapOther";
      this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
      this.Text = "BitmapOther";
      this.Load += new System.EventHandler(this.BitmapOther_Load);
    }
        #endregion
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main() 
    {
      Application.Run(new BitmapOther());
    }
    private void BitmapOther_Load(object sender, System.EventArgs e)
    {
    
    }
    protected override void OnPaint ( PaintEventArgs e )
    {
      Bitmap BMP = new Bitmap("Colorbars.JPG");
      Point Pt = new Point(20,20);
   //   BMP.SetPixel(15,20,Color.Black);
      BMP.MakeTransparent( BMP.GetPixel(15,25) );
      e.Graphics.DrawImage(BMP, Pt);
      e.Graphics.DrawLine(new Pen(Brushes.GreenYellow,30),60,60,200,60);

      
    }
   }
    }

<A href="http://www.nfex.ru/Code/CSharpDownload/BitmapOther-c.zip">BitmapOther-c.zip( 5 k)</a>


Bitmap Viewer Host

/*
User Interfaces in C#: Windows Forms and Custom Controls
by Matthew MacDonald
Publisher: Apress
ISBN: 1590590457
*/
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
namespace BitmapViewerHost
{
    /// <summary>
    /// Summary description for BitmapViewerHost.
    /// </summary>
    public class BitmapViewerHost : System.Windows.Forms.Form
    {
        private BitmapViewer bitmapViewer1;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ruponentModel.Container components = null;
        public BitmapViewerHost()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();
            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }
        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.bitmapViewer1 = new BitmapViewer();
            this.SuspendLayout();
            // 
            // bitmapViewer1
            // 
            this.bitmapViewer1.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
                | System.Windows.Forms.AnchorStyles.Left) 
                | System.Windows.Forms.AnchorStyles.Right);
            this.bitmapViewer1.Dimension = 80;
            this.bitmapViewer1.Directory = null;
            this.bitmapViewer1.DockPadding.All = 1;
            this.bitmapViewer1.Location = new System.Drawing.Point(12, 12);
            this.bitmapViewer1.Name = "bitmapViewer1";
            this.bitmapViewer1.Size = new System.Drawing.Size(300, 244);
            this.bitmapViewer1.Spacing = 10;
            this.bitmapViewer1.TabIndex = 0;
            this.bitmapViewer1.PictureSelected += new BitmapViewer.PictureSelectedDelegate(this.bitmapViewer1_PictureSelected);
            // 
            // BitmapViewerHost
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(320, 266);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.bitmapViewer1});
            this.Name = "BitmapViewerHost";
            this.Text = "BitmapViewerHost";
            this.Load += new System.EventHandler(this.BitmapViewerHost_Load);
            this.ResumeLayout(false);
        }
        #endregion
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main() 
        {
            Application.Run(new BitmapViewerHost());
        }
        private void BitmapViewerHost_Load(object sender, System.EventArgs e)
        {
            bitmapViewer1.Directory = Application.StartupPath;
            bitmapViewer1.Directory = "c:\\windows";
        }
        private void bitmapViewer1_PictureSelected(object sender, PictureSelectedEventArgs e)
        {
                MessageBox.Show("You chose " + e.FileName);
        }
    
    }
    /// <summary>
    /// Summary description for BitmapViewer.
    /// </summary>
    public class BitmapViewer : System.Windows.Forms.UserControl
    {
        internal System.Windows.Forms.Panel pnlPictures;
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ruponentModel.Container components = null;
        public BitmapViewer()
        {
            // This call is required by the Windows.Forms Form Designer.
            InitializeComponent();
            // TODO: Add any initialization after the InitForm call
        }
        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if(components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }
        #region Component Designer generated code
        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.pnlPictures = new System.Windows.Forms.Panel();
            this.SuspendLayout();
            // 
            // pnlPictures
            // 
            this.pnlPictures.AutoScroll = true;
            this.pnlPictures.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.pnlPictures.Dock = System.Windows.Forms.DockStyle.Fill;
            this.pnlPictures.Location = new System.Drawing.Point(1, 1);
            this.pnlPictures.Name = "pnlPictures";
            this.pnlPictures.Size = new System.Drawing.Size(530, 218);
            this.pnlPictures.TabIndex = 1;
            // 
            // BitmapViewer
            // 
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.pnlPictures});
            this.DockPadding.All = 1;
            this.Name = "BitmapViewer";
            this.Size = new System.Drawing.Size(532, 220);
            this.ResumeLayout(false);
        }
        #endregion
    
        public delegate void PictureSelectedDelegate(object sender, PictureSelectedEventArgs e);
        public event PictureSelectedDelegate PictureSelected;
        // The directory that will be scanned for image.
        private string directory="";
        // Each picture box will be a square of dimension X dimension pixels.
        private int dimension;
        // The space between the images and the top, left, and right sides.
        private int border = 5;
        // The space between each image.
        private int spacing;
        // The images that were found in the selected directory.
        private ArrayList images = new ArrayList();

        public string Directory
        {
            get
            {
                return directory;
            }
            set
            {
                directory = value;
                GetImages();
                UpdateDisplay();
            }
        }
        public int Dimension
        {
            get
            {
                return dimension;
            }
            set
            {
                dimension = value;
                UpdateDisplay();
            }
        }
        public int Spacing
        {
            get
            {
                return spacing;
            }
            set
            {
                spacing = value;
                UpdateDisplay();
            }
        }

        private void GetImages()
        {
            images.Clear();
            if (this.Directory != "" && this.directory != null)
            {
                DirectoryInfo dir = new DirectoryInfo(directory);
                foreach (FileInfo file in dir.GetFiles("*.bmp"))
                {
                    images.Add(new NamedImage(Bitmap.FromFile(file.FullName), file.Name));
                }
            }
        }
        private void UpdateDisplay()
        {
            // Clear the current display.
            pnlPictures.Controls.Clear();
            // Row and Col will track the current position where pictures are
            // being inserted. They begin at the top-right corner.
            int row = border, col = border;
            // Iterate through the Images collection, and create PictureBox controls.
            foreach (NamedImage image in images)
            {
                PictureBox pic = new PictureBox();
                pic.Image = image.Image;
                pic.Tag = image.FileName;
                pic.Size = new Size(dimension, dimension);
                pic.Location = new Point(col, row);
                pic.BorderStyle = BorderStyle.FixedSingle;
                // StrechImage mode gives us the "thumbnail" ability.
                pic.SizeMode = PictureBoxSizeMode.StretchImage;
                // Display the picture.
                pnlPictures.Controls.Add(pic);
                // Move to the next column.
                col += dimension + spacing;
                // Handle the event.
                pic.Click += new EventHandler(this.pic_Click);
                // Move to next line if no more pictures will fit.
                if ((col + dimension + spacing + border) > this.Width)
                {
                    col = border;
                    row += dimension + spacing;
                }
            }
        }

        public void RefreshImages()
        {
            GetImages();
            UpdateDisplay();
        }

        protected override void OnSizeChanged(System.EventArgs e)
        {
            UpdateDisplay();
            base.OnSizeChanged(e);
        }

        private PictureBox picSelected;
        private void pic_Click(object sender, System.EventArgs e)
        {
            // Clear the border style from the last selected picture box.
            if (picSelected != null)
            {
                picSelected.BorderStyle = BorderStyle.FixedSingle;
            }
            // Get the new selection.
            picSelected = (PictureBox)sender;
            picSelected.BorderStyle = BorderStyle.Fixed3D;
            // Fire the selection event.
            PictureSelectedEventArgs args = new 
                PictureSelectedEventArgs((string)picSelected.Tag, picSelected.Image);
            if (PictureSelected != null)
            {
                PictureSelected(this, args);
            }
        }

        private class NamedImage
        {
            public Image Image;
            public string FileName;
            public NamedImage(Image image, string fileName)
            {
                this.Image = image;
                this.FileName = fileName;
            }
        }
    
    }
    public class PictureSelectedEventArgs : EventArgs
    {
        public string FileName;
        public Image Image;
        public PictureSelectedEventArgs(String fileName, Image image)
        {
            this.FileName = fileName;
            this.Image = image;
        }
    }

    
}


Output color by R G B value for a Bitmap

 
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
public class Analyzer {
    public static void Main() {
        Image sample = new Bitmap("a.jpg");
        MemoryStream buf = new MemoryStream();
        sample.Save(buf, ImageFormat.Bmp);
        byte[] currentImage = buf.GetBuffer();
        
        int[] stats = new int[3];
        for (int i = 0; i < currentImage.Length; ){
            for (int j = 0; j < 3; j++) {
                stats[j] += currentImage[i];
                ++i;
            }
        }    
        Console.WriteLine("Blue: " + stats[0]);
        Console.WriteLine("Green: " + stats[1]);
        Console.WriteLine("Red: " + stats[2]);
        if ((stats[0] > stats[1]) && (stats[0] > stats[2]))
            Console.WriteLine("This is a cold picture.");
        if ((stats[1] > stats[0]) && (stats[1] > stats[2]))
            Console.WriteLine("This is a summer picture.");
        if ((stats[2] > stats[0]) && (stats[2] > stats[1]))
            Console.WriteLine("This is a fiery picture.");
    }
}