
Draw text or graphics on an image
Sometimes the picture just isn't enough and you need another thousand words or some circles and arrows to draw attention to something in the image. In these cases you'll need to draw directly onto the image and save the picture along with your changes. This is made simple by GDI+ because you can obtain a Graphics object for any Image based objects that doesn't use an indexed colour palette and draw on them directly. The Graphics object behaves in just the same way as it does for on-screen drawing. In cases where the pixel format of the original image is indexed, such as a GIF file you can make a non-indexed copy of that image and draw on that. Saving the image again however might mean an unavoidable change in format. The following code shows how to draw graphics and text on an image. The code draws the date onto the image. Dim imageName As String = "c:\foo.jpg" ' substitute your own image name here 'NOTE Don't use this test code to draw on images that you want to keep! Dim i As Image = Image.FromFile(imageName) Dim g As Graphics = Graphics.FromImage(i) g.FillRectangle(Brushes.White, 5, 5, 100, 30) g.DrawRectangle(Pens.DarkBlue, 5, 5, 100, 30) Dim sf As StringFormat = CType(StringFormat.GenericTypographic.Clone(), StringFormat) sf.Alignment = StringAlignment.Center sf.LineAlignment = StringAlignment.Center
g.DrawString(DateTime.Now.ToShortDateString(), New Font("Arial", 14, GraphicsUnit.Point), Brushes.Black, New RectangleF(7, 7, 94, 25), sf)
g.Dispose() i.Save("C:\testimage.jpg", ImageFormat.Jpeg)
i.Dispose()
string imageName="c:\\foo.jpg"; // substitute your own image name here //NOTE Don't use this test code to draw on images that you want to keep!
Image i=Image.FromFile(imageName); Graphics g=Graphics.FromImage(i); g.FillRectangle(Brushes.White,5,5,100,30); g.DrawRectangle(Pens.DarkBlue,5,5,100,30); StringFormat sf=(StringFormat)StringFormat.GenericTypographic.Clone(); sf.Alignment=StringAlignment.Center; sf.LineAlignment=StringAlignment.Center;
g.DrawString(DateTime.Now.ToShortDateString(),new Font("Arial",14,GraphicsUnit.Point),Brushes.Black,new RectangleF(7,7,94,25),sf);
g.Dispose(); i.Save("C:\\testimage.jpg",ImageFormat.Jpeg);
i.Dispose();
Return to Windows Forms Tips and Tricks Copyright Ramuseco Limited 2004. All rights reserved.
|