xbdev - software development
Friday February 23, 2024
home | contact | Support



With C# and .Net...


Images and C#


Lets say you have an image file (.bmp, jpg, gif etc)  and you want to load it and render it in your window...how do we do that?  Well its easy, we use the 'Bitmap' class...it only takes a couple of lines, and can really make cooler as we can plug in pre-made graphics :)




The simple demo is really simple...and the few lines of code in the OnPaint(..) callback function demonstrate how to create, load and render an image from a file.  The great thing to note, is that you can load not just one file format, but a variety...which includes jpg, bmp and gif.


If you run the mini demo, resize the window to see the full image...  Also, you should note, that you wouldn't really load the image in the OnPaint(..) function, as you program would need to load and release your image each time the image is drawn.


Instead you usually load it once in the constructor and save the 'Bitmap', then render it when you need to.




Code: code.cs


using System.Drawing;

using System.Drawing.Imaging;


class AWindow : System.Windows.Forms.Form


      private void OnPaint(object sender, System.Windows.Forms.PaintEventArgs e)


            System.Drawing.Graphics g = e.Graphics;


            Bitmap TestImage = null;


            TestImage = new Bitmap("gremlin.jpg");


            int iImageWidth = TestImage.Width;

            int iImageHeight = TestImage.Height;



            Rectangle destR = new Rectangle(10, 10, TestImage.Width, TestImage.Height);

            Rectangle srcR  = new Rectangle(0,0, TestImage.Width, TestImage.Height);


            g.DrawImage(TestImage, destR, srcR, GraphicsUnit.Pixel);


            // Or

            Point p = new Point(10,10);

            g.DrawImage(TestImage, p);


      }// End of OnPaint(..)




            this.Paint += new System.Windows.Forms.PaintEventHandler(this.OnPaint);

      }// End of AWindow()


      // Application Entry Point

      static void Main()


            System.Windows.Forms.Application.Run(new AWindow());

      }// End Main()

}// End of AWindow class







Advert (Support Website)

Copyright (c) 2002-2024 xbdev.net - All rights reserved.
Designated articles, tutorials and software are the property of their respective owners.