Drawing Images using Graphics
Drawing Images using Graphics
With the Aspose.Imaging library you can draw simple shapes like lines, rectangles and circles, as well as complex shapes like polygons, curves, arcs and Bezier shapes. Aspose.Imaging library creates such shapes using Graphics class that resides in the Aspose.Imaging namespace. Graphics objects are responsible for performing different drawing operations on an image, thus changing the image’s surface. The Graphics class uses a variety of helper objects to enhance the shapes:
- Pens, to draw lines, outline shapes, or render other geometric representations.
- Brushes, to define how areas are filled in.
- Fonts, to define the shape of characters of text.
Drawing with the Graphics Class
Below is a code example demonstrating the use of the Graphics class. The example source code has been split into several parts to keep it simple and easy to follow. Step by step, the examples show how to:
- Create an image.
- Create and initialize a Graphics object.
- Clear the surface.
- Draw an ellipse.
- Draw a filled polygon and save the image.
Programming Samples
Creating an Image
Start by creating an image using any of the methods described in Creating Files.
Create and Initialize a Graphics Object
Then create and initialize a Graphics object by passing the Image object to its constructor.
Clear the Surface
Clear the Graphics surface by calling the Graphics class Clear method and pass a color as a parameter. This method fills the Graphics surface with the color passed in as argument.
Draw an Ellipse
You may notice that the Graphics class has exposed plenty of methods to draw and fill shapes. You’ll find get the complete list of methods in the Aspose.Imaging for .NET API Reference. There are several overloaded versions of the DrawEllipse method exposed by the Graphics class. All these methods accept a Pen object as its first argument. The later parameters are passed to define the bounding rectangle around the ellipse. For the sake of this example, use the version accepting a Rectangle object as the second parameter to draw an ellipse using the Pen object in your desired color.
Draw a Filled Polygon
Next, draw a polygon using the LinearGradientBrush and an array of points. The Graphics class has exposed several overloaded versions of the FillPolygon() method. All of these accept a Brush object as its first argument, defining the characteristics of the fill. The second parameter is an array of points. Please note that every two consecutive points in the array specify a side of the polygon.
using Aspose.Imaging; | |
using Aspose.Imaging.Brushes; | |
using Aspose.Imaging.FileFormats.Bmp; | |
using System.IO; | |
string templatesFolder = @"c:\Users\USER\Downloads\templates\"; | |
string dataDir = templatesFolder; | |
// Creates an instance of FileStream | |
using (BmpImage image = (BmpImage)Image.Load(dataDir + "template.bmp")) | |
{ | |
// Create and initialize an instance of Graphics class and clear Graphics surface | |
Graphics graphic = new Graphics(image); | |
graphic.FillRectangle(new SolidBrush(Color.Green), new Rectangle(0, 0, 100, 100)); | |
graphic.FillPolygon(new SolidBrush(Color.Green), new Point[] { new Point(0, 0), new Point(100, 100), new Point(10, 10) }); | |
image.Save(dataDir + "result.bmp"); | |
} | |
File.Delete(dataDir + "result.bmp"); |
Measure string using Aspose.Graphics
Aspose.Imaging Graphics supports method to measure string. Here the sample code for it is provided.
using Aspose.Imaging; | |
using Aspose.Imaging.Brushes; | |
using Aspose.Imaging.FileFormats.Bmp; | |
using System.IO; | |
string templatesFolder = @"c:\Users\USER\Downloads\templates\"; | |
string dataDir = templatesFolder; | |
// Creates an instance of FileStream | |
using (BmpImage image = (BmpImage)Image.Load(dataDir + "template.bmp")) | |
{ | |
// Create and initialize an instance of Graphics class and clear Graphics surface | |
Graphics graphic = new Graphics(image); | |
// Draw a Bezier shape by specifying the Pen object having black color and co-ordinate Points and save all changes. | |
graphic.DrawString("Test", new Font("Arial", 10), new HatchBrush(), new PointF(0, 0)); | |
SizeF size = graphic.MeasureString("Test", new Font("Arial", 10), new SizeF(100, 100), StringFormat.GenericDefault); | |
image.Save(dataDir + "result.bmp"); | |
} | |
File.Delete(dataDir + "result.bmp"); |
Drawing Images using Graphics : Complete Source
using Aspose.Imaging; | |
using Aspose.Imaging.Brushes; | |
using Aspose.Imaging.FileFormats.Bmp; | |
using Aspose.Imaging.ImageOptions; | |
using Aspose.Imaging.Sources; | |
using System.IO; | |
string templatesFolder = @"c:\Users\USER\Downloads\templates\"; | |
string dataDir = templatesFolder; | |
// Create an instance of BmpOptions and set its various properties | |
BmpOptions imageOptions = new BmpOptions(); | |
imageOptions.BitsPerPixel = 24; | |
// Create an instance of FileCreateSource and assign it to Source property | |
imageOptions.Source = new FileCreateSource(dataDir + "result.bmp", false); | |
using (var image = Image.Create(imageOptions, 500, 500)) | |
{ | |
var graphics = new Graphics(image); | |
// Clear the image surface with white color and Create and initialize a Pen object with blue color | |
graphics.Clear(Color.White); | |
var pen = new Pen(Color.Blue); | |
// Draw Ellipse by defining the bounding rectangle of width 150 and height 100 also Draw a polygon using the LinearGradientBrush | |
graphics.DrawEllipse(pen, new Rectangle(10, 10, 150, 100)); | |
using (var linearGradientBrush = new LinearGradientBrush(image.Bounds, Color.Red, Color.White, 45f)) | |
{ | |
graphics.FillPolygon(linearGradientBrush, new[] { new Point(200, 200), new Point(400, 200), new Point(250, 350) }); | |
} | |
image.Save(); | |
} | |
File.Delete(dataDir + "result.bmp"); |
All classes that implement IDisposable and access unmanaged resources are instantiated in a Using statement to ensure that they are disposed of correctly.
Drawing Text on images using Graphics
Using Aspose.Imaging you can easily draw text on image with text alignment using Graphics.
using Aspose.Imaging; | |
using System; | |
using System.IO; | |
string templatesFolder = @"c:\Users\USER\Downloads\templates\"; | |
string dataDir = templatesFolder; | |
Run(); | |
void Run() | |
{ | |
string[] alignments = new[] { "Left", "Center", "Right" }; | |
foreach (var alignment in alignments) | |
{ | |
DrawString(templatesFolder, alignment); | |
} | |
} | |
void DrawString(string baseFolder, string align) | |
{ | |
string outputFileName = dataDir + "result.png"; | |
string[] fontNames = new[] | |
{ | |
"Arial", "Times New Roman", | |
"Bookman Old Style", "Calibri", "Comic Sans MS", | |
"Courier New", "Microsoft Sans Serif", "Tahoma", | |
"Verdana", "Proxima Nova Rg" | |
}; | |
float[] fontSizes = new[] { 10f, 22f, 50f, 100f }; | |
int width = 3000; | |
int height = 3500; | |
using (System.IO.FileStream stream = | |
new System.IO.FileStream(outputFileName, System.IO.FileMode.Create)) | |
{ | |
//Create an instance of PngOptions and set its various properties | |
Aspose.Imaging.ImageOptions.PngOptions pngOptions | |
= new Aspose.Imaging.ImageOptions.PngOptions(); | |
//Set the Source for PngOptions | |
pngOptions.Source = new Aspose.Imaging.Sources.StreamSource(stream); | |
//Create an instance of Image | |
using (Aspose.Imaging.Image image | |
= Aspose.Imaging.Image.Create(pngOptions, width, height)) | |
{ | |
//Create and initialize an instance of Graphics class | |
Aspose.Imaging.Graphics graphics = new Aspose.Imaging.Graphics(image); | |
//Clear Graphics surface | |
graphics.Clear(Aspose.Imaging.Color.White); | |
//Create a SolidBrush object and set its various properties | |
Aspose.Imaging.Brushes.SolidBrush brush | |
= new Aspose.Imaging.Brushes.SolidBrush(); | |
brush.Color = Color.Black; | |
float x = 10; | |
int lineX = 0; | |
float y = 10; | |
float w = width - 20; | |
var pen = new Pen(Color.Red, 1); | |
StringAlignment alignment = StringAlignment.Near; | |
switch (align) | |
{ | |
case "Left": | |
alignment = StringAlignment.Near; | |
lineX = (int)Math.Round(x, 0); | |
break; | |
case "Center": | |
alignment = StringAlignment.Center; | |
lineX = (int)Math.Round(x + w / 2f, 0); | |
break; | |
case "Right": | |
alignment = StringAlignment.Far; | |
lineX = (int)(x + w); | |
break; | |
} | |
var stringFormat = new StringFormat(StringFormatFlags.ExactAlignment); | |
stringFormat.Alignment = alignment; | |
foreach (var fontName in fontNames) | |
{ | |
foreach (var fontSize in fontSizes) | |
{ | |
var font = new Font(fontName, fontSize); | |
string text = String.Format("This is font: {0}, size:{1}", fontName, fontSize); | |
var s = graphics.MeasureString(text, font, SizeF.Empty, null); | |
graphics. | |
DrawString(text, font, brush, new RectangleF(x, y, w, s.Height), stringFormat); | |
y += s.Height; | |
} | |
graphics.DrawLine(pen, new Point((int)(x), (int)y), new Point((int)(x + w), (int)y)); | |
} | |
graphics.DrawLine(pen, new Point(lineX, 0), new Point(lineX, (int)y)); | |
// save all changes. | |
image.Save(); | |
} | |
} | |
File.Delete(dataDir + "result.png"); | |
} | |
Memory Strategy optimization
Graphics operations can be proceeded using memory strategy optimization - ie limiting memory buffer size for operation.
using Aspose.Imaging; | |
using Aspose.Imaging.ImageOptions; | |
using Aspose.Imaging.Sources; | |
using System; | |
using System.IO; | |
string templatesFolder = @"c:\Users\USER\Downloads\templates\"; | |
string dataDir = templatesFolder; | |
const int ImageSize = 2000; | |
ImageOptionsBase createOptions = new PngOptions(); | |
createOptions.Source = new FileCreateSource(dataDir + "result.png"); | |
createOptions.BufferSizeHint = 30; // Memory limit is 30 Mb | |
using (Image image = Image.Create(createOptions, ImageSize, ImageSize)) | |
{ | |
Graphics graphics = new Graphics(image); | |
// You can use any graphic operations here, all of them will be performed within the established memory limit | |
// For example: | |
graphics.Clear(Color.LightSkyBlue); | |
graphics.DrawLine(new Pen(Color.Red, 3f), 0, 0, image.Width, image.Height); | |
} | |
File.Delete(dataDir + "result.png"); | |
// A large number of graphic operations are also supported: | |
const int OperationAreaSize = 10; | |
createOptions = new PngOptions(); | |
createOptions.Source = new FileCreateSource(dataDir + "result.png"); | |
createOptions.BufferSizeHint = 30; // Memory limit is 30 Mb | |
using (Image image = Image.Create(createOptions, ImageSize, ImageSize)) | |
{ | |
Graphics graphics = new Graphics(image); | |
graphics.BeginUpdate(); | |
graphics.Clear(Color.LightSkyBlue); | |
int x, y; | |
for (int column = 0; column * OperationAreaSize < ImageSize; column++) | |
{ | |
for (int row = 0; row * OperationAreaSize < ImageSize; row++) | |
{ | |
x = column * OperationAreaSize; | |
y = row * OperationAreaSize; | |
bool reversed = (column + row) % 2 != 0; | |
if (reversed) | |
{ | |
graphics.DrawLine( | |
new Pen(Color.Red), | |
x + OperationAreaSize - 2, | |
y, | |
x, | |
y + OperationAreaSize); | |
} | |
else | |
{ | |
graphics.DrawLine( | |
new Pen(Color.Red), | |
x, | |
y, | |
x + OperationAreaSize - 2, | |
y + OperationAreaSize); | |
} | |
} | |
} | |
// About 40k operations will be applied here, while they do not take up too much memory | |
// (since they are already unloaded into the external file, and will be loaded from there one at a time) | |
graphics.EndUpdate(); | |
} | |
File.Delete(dataDir + "result.png"); |