Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Aspose.Imaging for .NET
Gist for Aspose.Imaging for .NET.
// Create an instance of CAD Metered class
Aspose.Imaging.Metered metered = new Aspose.Imaging.Metered();
// Access the setMeteredKey property and pass public and private keys as parameters
metered.SetMeteredKey("*****", "*****");
// Get metered data amount before calling API
decimal amountbefore = Aspose.Imaging.Metered.GetConsumptionQuantity();
// Display information
Console.WriteLine("Amount Consumed Before: " + amountbefore.ToString());
// Get metered data amount After calling API
decimal amountafter = Aspose.Imaging.Metered.GetConsumptionQuantity();
// Display information
Console.WriteLine("Amount Consumed After: " + amountafter.ToString());
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
// Create an instance of JpegOptions and set its various properties
JpegOptions imageOptions = new JpegOptions();
// Create an instance of FileCreateSource and assign it to Source property
imageOptions.Source = new FileCreateSource(dataDir + "Two_images_result_out.bmp", false);
// Create an instance of Image and define canvas size
using (var image = Image.Create(imageOptions, 600, 600))
{
// Create and initialize an instance of Graphics, Clear the image surface with white color and Draw Image
var graphics = new Graphics(image);
graphics.Clear(Color.White);
graphics.DrawImage(Image.Load(dataDir + "sample_1.bmp"), 0, 0, 600, 300);
graphics.DrawImage(Image.Load(dataDir + "File1.bmp"), 0, 300, 600, 300);
image.Save();
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
// Creates an instance of BmpOptions and set its various properties
BmpOptions ImageOptions = new BmpOptions();
ImageOptions.BitsPerPixel = 24;
// Define the source property for the instance of BmpOptions Second boolean parameter determines if the file is temporal or not
ImageOptions.Source = new FileCreateSource(dataDir + "CreatingAnImageBySettingPath_out.bmp", false);
// Creates an instance of Image and call Create method by passing the BmpOptions object
using (Image image = Image.Create(ImageOptions, 500, 500))
{
image.Save(dataDir + "CreatingAnImageBySettingPath1_out.bmp");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
// Creates an instance of BmpOptions and set its various properties
BmpOptions ImageOptions = new BmpOptions();
ImageOptions.BitsPerPixel = 24;
// Create an instance of System.IO.Stream
Stream stream = new FileStream(dataDir + "sample_out.bmp", FileMode.Create);
// Define the source property for the instance of BmpOptions Second boolean parameter determines if the Stream is disposed once get out of scope
ImageOptions.Source = new StreamSource(stream, true);
// Creates an instance of Image and call Create method by passing the BmpOptions object
using (Image image = Image.Create(ImageOptions, 500, 500))
{
// Do some image processing
image.Save(dataDir + "CreatingImageUsingStream_out.bmp");
}
// Creates an instance of FileStream
using (FileStream stream = new FileStream(dataDir + "DrawingArc_out.bmp", FileMode.Create))
{
// Create an instance of BmpOptions and set its various properties
BmpOptions saveOptions = new BmpOptions();
saveOptions.BitsPerPixel = 32;
// Set the Source for BmpOptions and create an instance of Image
saveOptions.Source = new StreamSource(stream);
using (Image image = Image.Create(saveOptions, 100, 100))
{
// Create and initialize an instance of Graphics class and clear Graphics surface
Graphics graphic = new Graphics(image);
graphic.Clear(Color.Yellow);
// Draw an arc shape by specifying the Pen object having red black color and coordinates, height, width, start & end angles
int width = 100;
int height = 200;
int startAngle = 45;
int sweepAngle = 270;
// Draw arc to screen and save all changes.
graphic.DrawArc(new Pen(Color.Black), 0, 0, width, height, startAngle, sweepAngle);
image.Save();
}
stream.Close();
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
// Creates an instance of FileStream
using (FileStream stream = new FileStream(dataDir + "DrawingBezier_out.bmp", FileMode.Create))
{
// Create an instance of BmpOptions and set its various properties
BmpOptions saveOptions = new BmpOptions();
saveOptions.BitsPerPixel = 32;
// Set the Source for BmpOptions and Create an instance of Image
saveOptions.Source = new StreamSource(stream);
using (Image image = Image.Create(saveOptions, 100, 100))
{
// Create and initialize an instance of Graphics class and clear Graphics surface
Graphics graphic = new Graphics(image);
graphic.Clear(Color.Yellow);
// Initializes the instance of PEN class with black color and width
Pen BlackPen = new Pen(Color.Black, 3);
float startX = 10;
float startY = 25;
float controlX1 = 20;
float controlY1 = 5;
float controlX2 = 55;
float controlY2 = 10;
float endX = 90;
float endY = 25;
// Draw a Bezier shape by specifying the Pen object having black color and co-ordinate Points and save all changes.
graphic.DrawBezier(BlackPen, startX, startY, controlX1, controlY1, controlX2, controlY2, endX, endY);
image.Save();
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
// Creates an instance of FileStream
using (FileStream stream = new FileStream(dataDir + "DrawingEllipse_out.bmp", FileMode.Create))
{
// Create an instance of BmpOptions and set its various properties
BmpOptions saveOptions = new BmpOptions();
saveOptions.BitsPerPixel = 32;
saveOptions.Source = new StreamSource(stream);
// Create an instance of Image
using (Image image = Image.Create(saveOptions, 100, 100))
{
// Create and initialize an instance of Graphics class and Clear Graphics surface
Graphics graphic = new Graphics(image);
graphic.Clear(Color.Yellow);
// Draw a dotted ellipse shape by specifying the Pen object having red color and a surrounding Rectangle
graphic.DrawEllipse(new Pen(Color.Red), new Rectangle(30, 10, 40, 80));
// Draw a continuous ellipse shape by specifying the Pen object having solid brush with blue color and a surrounding Rectangle
graphic.DrawEllipse(new Pen(new SolidBrush(Color.Blue)), new Rectangle(10, 30, 80, 40));
image.Save();
}
stream.Close();
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages() + "SolidLines_out.bmp";
// Creates an instance of FileStream
using (FileStream stream = new FileStream(dataDir, FileMode.Create))
{
// Create an instance of BmpOptions and set its various properties
BmpOptions saveOptions = new BmpOptions();
saveOptions.BitsPerPixel = 32;
saveOptions.Source = new StreamSource(stream);
// Create an instance of Image
using (Image image = Image.Create(saveOptions, 100, 100))
{
// Create and initialize an instance of Graphics class and Clear Graphics surface
Graphics graphic = new Graphics(image);
graphic.Clear(Color.Yellow);
// Draw two dotted diagonal lines by specifying the Pen object having blue color and co-ordinate Points
graphic.DrawLine(new Pen(Color.Blue), 9, 9, 90, 90);
graphic.DrawLine(new Pen(Color.Blue), 9, 90, 90, 9);
// Draw a four continuous line by specifying the Pen object having Solid Brush with red color and two point structures
graphic.DrawLine(new Pen(new SolidBrush(Color.Red)), new Point(9, 9), new Point(9, 90));
graphic.DrawLine(new Pen(new SolidBrush(Color.Aqua)), new Point(9, 90), new Point(90, 90));
graphic.DrawLine(new Pen(new SolidBrush(Color.Black)), new Point(90, 90), new Point(90, 9));
graphic.DrawLine(new Pen(new SolidBrush(Color.White)), new Point(90, 9), new Point(9, 9));
image.Save();
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages() + "SampleRectangle_out.bmp";
// Creates an instance of FileStream
using (FileStream stream = new FileStream(dataDir, FileMode.Create))
{
// Create an instance of BmpOptions and set its various properties
BmpOptions saveOptions = new BmpOptions();
saveOptions.BitsPerPixel = 32;
// Set the Source for BmpOptions and Create an instance of Image
saveOptions.Source = new StreamSource(stream);
using (Image image = Image.Create(saveOptions, 100, 100))
{
// Create and initialize an instance of Graphics class, Clear Graphics surface, Draw a rectangle shapes and save all changes.
Graphics graphic = new Graphics(image);
graphic.Clear(Color.Yellow);
graphic.DrawRectangle(new Pen(Color.Red), new Rectangle(30, 10, 40, 80));
graphic.DrawRectangle(new Pen(new SolidBrush(Color.Blue)), new Rectangle(10, 30, 80, 40));
image.Save();
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages() + "SampleImage_out.bmp";
// 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, 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();
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
// 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 + "sample_1.bmp", false);
// Create an instance of Image and initialize an instance of Graphics
using (Image image = Image.Create(ImageOptions, 500, 500))
{
Graphics graphics = new Graphics(image);
graphics.Clear(Color.White);
// Create an instance of GraphicsPath and Instance of Figure, add EllipseShape, RectangleShape and TextShape to the figure
GraphicsPath graphicspath = new GraphicsPath();
Figure figure = new Figure();
figure.AddShape(new EllipseShape(new RectangleF(0, 0, 499, 499)));
figure.AddShape(new RectangleShape(new RectangleF(0, 0, 499, 499)));
figure.AddShape(new TextShape("Aspose.Imaging", new RectangleF(170, 225, 170, 100), new Font("Arial", 20), StringFormat.GenericTypographic));
graphicspath.AddFigures(new[] { figure });
graphics.DrawPath(new Pen(Color.Blue), graphicspath);
// Create an instance of HatchBrush and set its properties also Fill path by supplying the brush and GraphicsPath objects
HatchBrush hatchbrush = new HatchBrush();
hatchbrush.BackgroundColor = Color.Brown;
hatchbrush.ForegroundColor = Color.Blue;
hatchbrush.HatchStyle = HatchStyle.Vertical;
graphics.FillPath(hatchbrush, graphicspath);
image.Save();
Console.WriteLine("Processing completed successfully.");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
// Load the image to be drawn
using (RasterImage imageToDraw = (RasterImage)Image.Load(dataDir + "asposenet_220_src01.png"))
{
// Load the image for drawing on it (drawing surface)
using (EmfImage canvasImage = (EmfImage)Image.Load(dataDir + "input.emf"))
{
EmfRecorderGraphics2D graphics = EmfRecorderGraphics2D.FromEmfImage(canvasImage);
// Draw a rectagular part of the raster image within the specified bounds of the vector image (drawing surface).
// Note that because the source size is not equal to the destination one, the drawn image is stretched horizontally and vertically.
graphics.DrawImage(
imageToDraw,
new Rectangle(67, 67, canvasImage.Width, canvasImage.Height),
new Rectangle(0, 0, imageToDraw.Width, imageToDraw.Height),
GraphicsUnit.Pixel);
// Save the result image
using (EmfImage resultImage = graphics.EndRecording())
{
resultImage.Save(dataDir + "input.DrawImage.emf");
}
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
// Load the image to be drawn
using (RasterImage imageToDraw = (RasterImage)Image.Load(dataDir + "asposenet_220_src01.png"))
{
// Load the image for drawing on it (drawing surface)
using (SvgImage canvasImage = (SvgImage)Image.Load(dataDir + "asposenet_220_src02.svg"))
{
// Drawing on an existing Svg image.
Aspose.Imaging.FileFormats.Svg.Graphics.SvgGraphics2D graphics = new Aspose.Imaging.FileFormats.Svg.Graphics.SvgGraphics2D(canvasImage);
// Draw a rectagular part of the raster image within the specified bounds of the vector image (drawing surface).
// Note that because the source size is equal to the destination one, the drawn image is not stretched.
graphics.DrawImage(
new Rectangle(0, 0, imageToDraw.Width, imageToDraw.Height),
new Rectangle(67, 67, imageToDraw.Width, imageToDraw.Height),
imageToDraw);
// Save the result image
using (SvgImage resultImage = graphics.EndRecording())
{
resultImage.Save(dataDir + "asposenet_220_src02.DrawImage.svg");
}
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
// Load the image to be drawn
using (RasterImage imageToDraw = (RasterImage)Image.Load(dataDir + "asposenet_220_src01.png"))
{
// Load the image for drawing on it (drawing surface)
using (WmfImage canvasImage = (WmfImage)Image.Load(dataDir + "asposenet_222_wmf_200.wmf"))
{
WmfRecorderGraphics2D graphics = WmfRecorderGraphics2D.FromWmfImage(canvasImage);
// Draw a rectagular part of the raster image within the specified bounds of the vector image (drawing surface).
// Note that because the source size is not equal to the destination one, the drawn image is stretched horizontally and vertically.
graphics.DrawImage(
imageToDraw,
new Rectangle(67, 67, canvasImage.Width, canvasImage.Height),
new Rectangle(0, 0, imageToDraw.Width, imageToDraw.Height),
GraphicsUnit.Pixel);
// Save the result image
using (WmfImage resultImage = graphics.EndRecording())
{
resultImage.Save(dataDir + "asposenet_222_wmf_200.DrawImage.wmf");
}
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
using (MemoryStream drawnImageStream = new MemoryStream())
{
// First, rasterize Svg to Png and write the result to a stream.
using (SvgImage svgImage = (SvgImage)Image.Load(dataDir + "asposenet_220_src02.svg"))
{
SvgRasterizationOptions rasterizationOptions = new SvgRasterizationOptions();
rasterizationOptions.PageSize = svgImage.Size;
PngOptions saveOptions = new PngOptions();
saveOptions.VectorRasterizationOptions = rasterizationOptions;
svgImage.Save(drawnImageStream, saveOptions);
// Now load a Png image from stream for further drawing.
drawnImageStream.Seek(0, System.IO.SeekOrigin.Begin);
using (RasterImage imageToDraw = (RasterImage)Image.Load(drawnImageStream))
{
// Drawing on the existing Svg image.
Aspose.Imaging.FileFormats.Svg.Graphics.SvgGraphics2D graphics = new Aspose.Imaging.FileFormats.Svg.Graphics.SvgGraphics2D(svgImage);
// Scale down the entire drawn image by 2 times and draw it to the center of the drawing surface.
int width = imageToDraw.Width / 2;
int height = imageToDraw.Height / 2;
Point origin = new Point((svgImage.Width - width) / 2, (svgImage.Height - height) / 2);
Size size = new Size(width, height);
graphics.DrawImage(imageToDraw, origin, size);
// Save the result image
using (SvgImage resultImage = graphics.EndRecording())
{
resultImage.Save(dataDir + "asposenet_220_src02.DrawVectorImage.svg");
}
}
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PSD();
using (PsdImage image = (PsdImage)Image.Load(@"input.psd"))
{
image.Save("NoFont.psd");
}
Console.WriteLine("You have 2 minutes to install the font");
Thread.Sleep(TimeSpan.FromMinutes(2));
OpenTypeFontsCache.UpdateCache();
using (PsdImage image = (PsdImage)Image.Load(@"input.psd"))
{
image.Save("HasFont.psd");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
string filePath = "Flower.png"; // specify your path
using (PngImage image = (PngImage)Image.Load(filePath))
{
float opacity = image.ImageOpacity; // opacity = 0,470798
Console.WriteLine(opacity);
if (opacity == 0)
{
// The image is fully transparent.
}
}
}
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
ImageOptionsBase saveOptions = new PngOptions();
InterruptMonitor monitor = new InterruptMonitor();
SaveImageWorker worker = new SaveImageWorker(dataDir + "big.jpg", dataDir + "big_out.png", saveOptions, monitor);
Thread thread = new Thread(new ThreadStart(worker.ThreadProc));
try
{
thread.Start();
// The timeout should be less than the time required for full image conversion (without interruption).
Thread.Sleep(3000);
// Interrupt the process
monitor.Interrupt();
Console.WriteLine("Interrupting the save thread #{0} at {1}", thread.ManagedThreadId, System.DateTime.Now);
// Wait for interruption...
thread.Join();
}
finally
{
// If the file to be deleted does not exist, no exception is thrown.
File.Delete(dataDir + "big_out.png");
}
}
/// <summary>
/// Initiates image conversion and waits for its interruption.
/// </summary>
private class SaveImageWorker
{
/// <summary>
/// The path to the input image.
/// </summary>
private readonly string inputPath;
/// <summary>
/// The path to the output image.
/// </summary>
private readonly string outputPath;
/// <summary>
/// The interrupt monitor.
/// </summary>
private readonly InterruptMonitor monitor;
/// <summary>
/// The save options.
/// </summary>
private readonly ImageOptionsBase saveOptions;
/// <summary>
/// Initializes a new instance of the <see cref="SaveImageWorker" /> class.
/// </summary>
/// <param name="inputPath">The path to the input image.</param>
/// <param name="outputPath">The path to the output image.</param>
/// <param name="saveOptions">The save options.</param>
/// <param name="monitor">The interrupt monitor.</param>
public SaveImageWorker(string inputPath, string outputPath, ImageOptionsBase saveOptions, InterruptMonitor monitor)
{
this.inputPath = inputPath;
this.outputPath = outputPath;
this.saveOptions = saveOptions;
this.monitor = monitor;
}
/// <summary>
/// Tries to convert image from one format to another. Handles interruption.
/// </summary>
public void ThreadProc()
{
using (Image image = Image.Load(this.inputPath))
{
InterruptMonitor.ThreadLocalInstance = this.monitor;
try
{
image.Save(this.outputPath, this.saveOptions);
}
catch (OperationInterruptedException e)
{
Console.WriteLine("The save thread #{0} finishes at {1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now);
Console.WriteLine(e);
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
InterruptMonitor.ThreadLocalInstance = null;
}
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PSD();
using (Image image = Image.Load("testReplacementNotAvailableFonts.psd", new PsdLoadOptions() { DefaultReplacementFont = "Arial" }))
{
PsdImage psdImage = (PsdImage)image;
psdImage.Save(dataDir+"result.png", new PngOptions() { ColorType = PngColorType.TruecolorWithAlpha });
}
// Load an existing JPG image
using (Image image = Image.Load(dataDir + "SampleTiff1.tiff"))
{
// Declare a String object with Watermark Text
string theString = "45 Degree Rotated Text";
// Create and initialize an instance of Graphics class and Initialize an object of SizeF to store image Size
Graphics graphics = new Graphics(image);
SizeF sz = graphics.Image.Size;
// Creates an instance of Font, initialize it with Font Face, Size and Style
Font font = new Font("Times New Roman", 20, FontStyle.Bold);
// Create an instance of SolidBrush and set its various properties
SolidBrush brush = new SolidBrush();
brush.Color = Color.Red;
brush.Opacity = 0;
// Initialize an object of StringFormat class and set its various properties
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;
// Create an object of Matrix class for transformation
Matrix matrix = new Matrix();
// First a translation then a rotation
matrix.Translate(sz.Width / 2, sz.Height / 2);
matrix.Rotate(-45.0f);
// Set the Transformation through Matrix
graphics.Transform = matrix;
// Draw the string on Image Save output to disk
graphics.DrawString(theString, font, brush, 0, 0, format);
image.Save(dataDir + "AddDiagonalWatermarkToImage_out.jpg");
}
TiffOptions outputSettings = new TiffOptions(TiffExpectedFormat.Default);
outputSettings.BitsPerSample = new ushort[] { 1 };
outputSettings.Compression = TiffCompressions.CcittFax3;
outputSettings.Photometric = TiffPhotometrics.MinIsWhite;
outputSettings.Source = new StreamSource(new MemoryStream());
int newWidth = 500;
int newHeight = 500;
string path = dataDir + "AddFramesToTIFFImage_out.tif";
using (TiffImage tiffImage = (TiffImage)Image.Create(outputSettings, newWidth, newHeight))
{
int index = 0;
foreach (var file in Directory.GetFiles(dataDir, "*.jpg"))
{
using (RasterImage ri = (RasterImage)Image.Load(file))
{
ri.Resize(newWidth, newHeight, ResizeType.NearestNeighbourResample);
TiffFrame frame = tiffImage.ActiveFrame;
if (index > 0)
{
frame = new TiffFrame(new TiffOptions(outputSettings) /*ensure options are cloned for each frame*/,
newWidth, newHeight);
// If there is a TIFF image loaded you need to enumerate the frames and perform the following
// Frame = TiffFrame.CreateFrameFrom(sourceFrame, outputSettings);
}
frame.SavePixels(frame.Bounds, ri.LoadPixels(ri.Bounds));
if (index > 0)
{
tiffImage.AddFrame(frame);
}
index++;
}
}
tiffImage.Save(path);
}
// Create an instance of Image and load the primary image
using (Image canvas = Image.Load(dataDir + "SampleTiff1.tiff"))
{
// Create another instance of Image and load the secondary image containing the signature graphics
using (Image signature = Image.Load(dataDir + "signature.gif"))
{
// Create an instance of Graphics class and initialize it using the object of the primary image
Graphics graphics = new Graphics(canvas);
// Call the DrawImage method while passing the instance of secondary image and appropriate location. The following snippet tries to draw the secondary image at the right bottom of the primary image
graphics.DrawImage(signature, new Point(canvas.Height - signature.Height, canvas.Width - signature.Width));
canvas.Save(dataDir + "AddSignatureToImage_out.png", new PngOptions());
}
}
// Display Status.
Console.WriteLine("Watermark added successfully.");
// Load an image in an instance of Image
using (Image image__1 = Image.Load(dataDir + Convert.ToString("aspose-logo.jpg")))
{
// Cast object of Image to RasterImage
RasterImage rasterImage = (RasterImage)image__1;
// Check if RasterImage is cached and Cache RasterImage for better performance
if (!rasterImage.IsCached)
{
rasterImage.CacheData();
}
// Adjust the brightness
rasterImage.AdjustBrightness(70);
// Create an instance of TiffOptions for the resultant image, Set various properties for the object of TiffOptions and Save the resultant image
TiffOptions tiffOptions = new TiffOptions(TiffExpectedFormat.Default);
tiffOptions.BitsPerSample = new ushort[] {8,8,8};
tiffOptions.Photometric = TiffPhotometrics.Rgb;
rasterImage.Save(dataDir + Convert.ToString("AdjustBrightness_out.tiff"), tiffOptions);
}
// Load an image in an instance of Image
using (Image image = Image.Load(dataDir + "aspose-logo.jpg"))
{
// Cast object of Image to RasterImage
RasterImage rasterImage = (RasterImage)image;
// Check if RasterImage is cached and Cache RasterImage for better performance
if (!rasterImage.IsCached)
{
rasterImage.CacheData();
}
// Adjust the contrast
rasterImage.AdjustContrast(10);
// Create an instance of TiffOptions for the resultant image, Set various properties for the object of TiffOptions and Save the resultant image to TIFF format
TiffOptions tiffOptions = new TiffOptions(TiffExpectedFormat.Default);
tiffOptions.BitsPerSample = new ushort[] { 8, 8, 8 };
tiffOptions.Photometric = TiffPhotometrics.Rgb;
rasterImage.Save(dataDir + "AdjustContrast_out.tiff", tiffOptions);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load an image in an instance of Image
using (Image image = Image.Load(dataDir + "aspose-logo.jpg"))
{
// Cast object of Image to RasterImage
RasterImage rasterImage = (RasterImage)image;
// Check if RasterImage is cached and Cache RasterImage for better performance
if (!rasterImage.IsCached)
{
rasterImage.CacheData();
}
// Adjust the gamma
rasterImage.AdjustGamma(2.2f, 2.2f, 2.2f);
// Create an instance of TiffOptions for the resultant image, Set various properties for the object of TiffOptions and Save the resultant image to TIFF format
TiffOptions tiffOptions = new TiffOptions(TiffExpectedFormat.Default);
tiffOptions.BitsPerSample = new ushort[] { 8, 8, 8 };
tiffOptions.Photometric = TiffPhotometrics.Rgb;
rasterImage.Save(dataDir + "AdjustGamma_out.tiff", tiffOptions);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load an image and convert the image instance to TiffImage
using (TiffImage image = (TiffImage)Image.Load(dataDir + "SampleTiff1.tiff"))
{
// Call the align resolution method and Save the results to output path.
image.AlignResolutions();
image.Save(dataDir + "AlignHorizontalAndVeticalResolutionsOfImage_out.tiff");
int framesCount = image.Frames.Length;
for (int i = 0; i < framesCount; i++)
{
TiffFrame frame = image.Frames[i];
// All resolutions after aligment must be equal
Console.WriteLine("Horizontal and vertical resolutions are equal:" + ((int)frame.VerticalResolution == (int)frame.HorizontalResolution));
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load the image
using (Image image = Image.Load(dataDir + "asposelogo.gif"))
{
// Caste the image into RasterImage
RasterImage rasterImage = image as RasterImage;
if (rasterImage == null)
{
return;
}
// Create an instance of GaussWienerFilterOptions class and set the radius size and smooth value.
GaussWienerFilterOptions options = new GaussWienerFilterOptions(12, 3);
options.Grayscale = true;
// Apply MedianFilterOptions filter to RasterImage object and Save the resultant image
rasterImage.Filter(image.Bounds, options);
image.Save(dataDir + "ApplyGaussWienerFilter_out.gif");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load the image
using (Image image = Image.Load(dataDir + "asposelogo.gif"))
{
// Caste the image into RasterImage
RasterImage rasterImage = image as RasterImage;
if (rasterImage == null)
{
return;
}
// Create an instance of GaussWienerFilterOptions class and set the radius size and smooth value.
GaussWienerFilterOptions options = new GaussWienerFilterOptions(5, 1.5);
options.Brightness = 1;
// Apply MedianFilterOptions filter to RasterImage object and Save the resultant image
rasterImage.Filter(image.Bounds, options);
image.Save(dataDir + "ApplyGaussWienerFilter_out.gif");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load the image
using (Image image = Image.Load(dataDir + "asposelogo.gif"))
{
// Caste the image into RasterImage
RasterImage rasterImage = image as RasterImage;
if (rasterImage == null)
{
return;
}
// Create an instance of MotionWienerFilterOptions class and set the length, smooth value and angle.
MotionWienerFilterOptions options = new MotionWienerFilterOptions(50, 9, 90);
options.Grayscale = true;
// Apply MedianFilterOptions filter to RasterImage object and Save the resultant image
rasterImage.Filter(image.Bounds, options);
image.Save(dataDir + "ApplyingMotionWienerFilter_out.gif");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load the noisy image
using (Image image = Image.Load(dataDir + "asposelogo.gif"))
{
// Caste the image into RasterImage
RasterImage rasterImage = image as RasterImage;
if (rasterImage == null)
{
return;
}
// Create an instance of MedianFilterOptions class and set the size, Apply MedianFilterOptions filter to RasterImage object and Save the resultant image
MedianFilterOptions options = new MedianFilterOptions(4);
rasterImage.Filter(image.Bounds, options);
image.Save(dataDir + "median_test_denoise_out.gif");
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
string sourceFileName = dataDir + "Colored by Faith_small.psd";
string inputPointsFileName = dataDir + "Colored by Faith_small.dat";
AutoMaskingArgs maskingArgs = new AutoMaskingArgs();
FillInputPoints(inputPointsFileName, maskingArgs);
string outputFileName = dataDir + "Colored by Faith_small_auto.png";
using (RasterImage image = (RasterImage)Image.Load(sourceFileName))
{
MaskingOptions maskingOptions = new MaskingOptions()
{
Method = SegmentationMethod.GraphCut,
Args = maskingArgs,
Decompose = false,
ExportOptions =
new PngOptions()
{
ColorType = PngColorType.TruecolorWithAlpha,
Source = new StreamSource(new MemoryStream())
},
};
MaskingResult[] maskingResults = new ImageMasking(image).Decompose(maskingOptions);
using (Image resultImage = maskingResults[1].GetImage())
{
resultImage.Save(outputFileName);
}
}
private static void FillInputPoints(string filePath, AutoMaskingArgs autoMaskingArgs)
{
BinaryFormatter serializer = new BinaryFormatter();
using (Stream stream = File.OpenRead(filePath))
{
bool hasObjectRectangles = (bool)serializer.Deserialize(stream);
bool hasObjectPoints = (bool)serializer.Deserialize(stream);
autoMaskingArgs.ObjectsRectangles = null;
autoMaskingArgs.ObjectsPoints = null;
if (hasObjectRectangles)
{
autoMaskingArgs.ObjectsRectangles = ((System.Drawing.Rectangle[])serializer.Deserialize(stream))
.Select(rect => new Aspose.Imaging.Rectangle(rect.X, rect.Y, rect.Width, rect.Height))
.ToArray();
}
if (hasObjectPoints)
{
autoMaskingArgs.ObjectsPoints = ((System.Drawing.Point[][])serializer.Deserialize(stream))
.Select(pointArray => pointArray
.Select(point => new Aspose.Imaging.Point(point.X, point.Y))
.ToArray())
.ToArray();
}
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load an image in an instance of Image
using (Image image = Image.Load(dataDir + "aspose-logo.jpg"))
{
// Cast the image to RasterCachedImage and Check if image is cached
RasterCachedImage rasterCachedImage = (RasterCachedImage)image;
if (!rasterCachedImage.IsCached)
{
// Cache image if not already cached
rasterCachedImage.CacheData();
}
// Binarize image with predefined fixed threshold and Save the resultant image
rasterCachedImage.BinarizeFixed(100);
rasterCachedImage.Save(dataDir + "BinarizationWithFixedThreshold_out.jpg");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load an image in an instance of Image
using (Image image = Image.Load(dataDir + "aspose-logo.jpg"))
{
// Cast the image to RasterCachedImage and Check if image is cached
RasterCachedImage rasterCachedImage = (RasterCachedImage)image;
if (!rasterCachedImage.IsCached)
{
// Cache image if not already cached
rasterCachedImage.CacheData();
}
// Binarize image with Otsu Thresholding and Save the resultant image
rasterCachedImage.BinarizeOtsu();
rasterCachedImage.Save(dataDir + "BinarizationWithOtsuThreshold_out.jpg");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load the image
using (Image image = Image.Load(dataDir + "asposelogo.gif"))
{
// Convert the image into RasterImage, Pass Bounds[rectangle] of image and GaussianBlurFilterOptions instance to Filter method and Save the results
RasterImage rasterImage = (RasterImage)image;
rasterImage.Filter(rasterImage.Bounds, new GaussianBlurFilterOptions(5, 5));
rasterImage.Save(dataDir + "BlurAnImage_out.gif");
}
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
using (BmpImage image = (BmpImage)Image.Load(dataDir))
{
Aspose.Imaging.ImageOptions.PdfOptions exportOptions = new PdfOptions();
exportOptions.PdfDocumentInfo = new Aspose.Imaging.FileFormats.Pdf.PdfDocumentInfo();
image.Save(dataDir, exportOptions);
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages() + "sample.bmp";
// Load an existing image.
using (var objimage = (BmpImage)Image.Load(dataDir))
{
// Define threshold value, Call BinarizeBradley method and pass the threshold value as parameter and Save the output image
double threshold = 0.15;
objimage.BinarizeBradley(threshold);
objimage.Save(dataDir + "binarized_out.png");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_CDR();
string inputFileName = dataDir + "test.cdr";
FileFormat expectedFileFormat = FileFormat.Cdr;
using (Image image = Image.Load(inputFileName))
{
if (expectedFileFormat != image.FileFormat)
{
throw new Exception("Image FileFormat is not {expectedFileFormat}");
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_CMX();
string[] fileNames = new string[] {
"Rectangle.cmx",
"Rectangle+Fill.cmx",
"Ellipse.cmx",
"Ellipse+fill.cmx",
"brushes.cmx",
"outlines.cmx",
"order.cmx",
"many_images.cmx",
};
foreach (string fileName in fileNames)
{
using (Image image = Image.Load(dataDir + fileName))
{
image.Save(
dataDir + fileName + ".docpage.png",
new PngOptions
{
VectorRasterizationOptions =
new CmxRasterizationOptions()
{
Positioning = PositioningTypes.DefinedByDocument,
SmoothingMode = SmoothingMode.AntiAlias
}
});
}
}
// Load an existing JPG image
using (JpegImage image = (JpegImage)Image.Load(dataDir + "aspose-logo_tn.jpg"))
{
StreamSource rgbprofile = new StreamSource(File.OpenRead(dataDir + "rgb.icc"));
StreamSource cmykprofile = new StreamSource(File.OpenRead(dataDir + "cmyk.icc"));
image.DestinationRgbColorProfile = rgbprofile;
image.DestinationCmykColorProfile = cmykprofile;
image.Save(dataDir + "ColorConversionUsingDefaultProfiles_out.icc");
}
// Load an existing JPG image
using (JpegImage image = (JpegImage)Image.Load(dataDir + "aspose-logo_tn.jpg"))
{
StreamSource rgbprofile = new StreamSource(File.OpenRead(dataDir + "rgb.icc"));
StreamSource cmykprofile = new StreamSource(File.OpenRead(dataDir + "cmyk.icc"));
image.RgbColorProfile = rgbprofile;
image.CmykColorProfile = cmykprofile;
Color[] colors = image.LoadPixels(new Rectangle(0, 0, image.Width, image.Height));
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load an image through file path location or stream
Image image = Image.Load(dataDir + "SampleTiff1.tiff");
// Create an instance of TiffOptions for the resultant image
TiffOptions outputSettings = new TiffOptions(TiffExpectedFormat.Default);
// Set BitsPerSample, Photometric mode & Compression mode
outputSettings.BitsPerSample = new ushort[] { 4 };
outputSettings.Compression = TiffCompressions.AdobeDeflate;
outputSettings.Photometric = TiffPhotometrics.Palette;
// Set graycale palette
outputSettings.Palette = ColorPaletteHelper.Create4BitGrayscale(false);
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load an image through file path location or stream
Image image = Image.Load(dataDir + "SampleTiff.tiff");
// Create an instance of TiffOptions for the resultant image
TiffOptions outputSettings = new TiffOptions(TiffExpectedFormat.Default);
// Set BitsPerSample, Compression, Photometric mode and graycale palette
outputSettings.BitsPerSample = new ushort[] { 4 };
outputSettings.Compression = TiffCompressions.Lzw;
outputSettings.Photometric = TiffPhotometrics.Palette;
outputSettings.Palette = ColorPaletteHelper.Create4BitGrayscale(false);
image.Save(dataDir + "SampleTiff_out.tiff", outputSettings);
List<string> files = new List<string>(new[] { dataDir + "TestDemo.tiff", dataDir + "sample.tiff" });
TiffOptions createOptions = new TiffOptions(TiffExpectedFormat.Default);
createOptions.BitsPerSample = new ushort[] { 1 };
createOptions.Orientation = TiffOrientations.TopLeft;
createOptions.Photometric = TiffPhotometrics.MinIsBlack;
createOptions.Compression = TiffCompressions.CcittFax3;
createOptions.FillOrder = TiffFillOrders.Lsb2Msb;
// Create a new image by passing the TiffOptions and size of first frame, we will remove the first frame at the end, cause it will be empty
TiffImage output = null;
try
{
List<TiffImage> images = new List<TiffImage>();
try
{
foreach (var file in files)
{
// Create an instance of TiffImage and load the source image
TiffImage input = (TiffImage)Image.Load(file);
images.Add(input); // Do not dispose before data is fetched. Data is fetched on 'Save' later.
foreach (var frame in input.Frames)
{
if (output == null)
{
// Create a new tiff image with first frame defined.
output = new TiffImage(TiffFrame.CopyFrame(frame));
}
else
{
// Add copied frame to destination image
output.AddFrame(TiffFrame.CopyFrame(frame));
}
}
}
if (output != null)
{
// Save the result
output.Save(dataDir + "ConcatenateTiffImagesHavingSeveralFrames_out.tif", createOptions);
}
}
finally
{
foreach (TiffImage image in images)
{
image.Dispose();
}
}
}
catch (Exception ex)
{
}
// Create instances of FileStream and initialize with Tiff images
FileStream fileStream = new FileStream(dataDir + "TestDemo.tif", FileMode.Open);
FileStream fileStream1 = new FileStream(dataDir + "sample.tif", FileMode.Open);
// Create an instance of TiffImage and load the destination image from filestream
using (TiffImage image = (TiffImage) Image.Load(fileStream))
{
// Create an instance of TiffImage and load the source image from filestream
using (TiffImage image1 = (TiffImage) Image.Load(fileStream1))
{
// Create an instance of TIffFrame and copy active frame of source image
TiffFrame frame = TiffFrame.CopyFrame(image1.ActiveFrame);
// Add copied frame to destination image
image.AddFrame(frame);
}
// Save the image with changes
image.Save(dataDir + "ConcatenatingTIFFImagesfromStream_out.tif");
// Close the FileStreams
fileStream.Close();
fileStream1.Close();
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Create a copy of original image to avoid any alteration
File.Copy(dataDir + "demo.tif", dataDir + "TestDemo.tif", true);
// Create an instance of TiffImage and load the copied destination image
using (TiffImage image = (TiffImage)Image.Load(dataDir + "TestDemo.tif"))
{
// Create an instance of TiffImage and load the source image
using (TiffImage image1 = (TiffImage)Image.Load(dataDir + "sample.tif"))
{
// Create an instance of TIffFrame and copy active frame of source image, Add copied frame to destination image and Save the image with changes.
TiffFrame frame = TiffFrame.CopyFrame(image1.ActiveFrame);
image.AddFrame(frame);
image.Save(dataDir + "ConcatTIFFImages_out.tiff");
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Cache();
// By default the cache folder is set to the local temp directory. You can specify a different cache folder from the default this way:
Cache.CacheFolder = dataDir;
// Auto mode is flexible and efficient
Cache.CacheType = CacheType.Auto;
// The default cache max value is 0, which means that there is no upper limit
Cache.MaxDiskSpaceForCache = 1073741824; // 1 gigabyte
Cache.MaxMemoryForCache = 1073741824; // 1 gigabyte
// We do not recommend that you change the following property because it may greatly affect performance
Cache.ExactReallocateOnly = false;
// At any time you can check how many bytes are currently allocated for the cache in memory or on disk By examining the following properties
long l1 = Cache.AllocatedDiskBytesCount;
long l2 = Cache.AllocatedMemoryBytesCount;
GifOptions options = new GifOptions();
options.Palette = new ColorPalette(new[] { Color.Red, Color.Blue, Color.Black, Color.White });
options.Source = new StreamSource(new MemoryStream(), true);
using (RasterImage image = (RasterImage)Image.Create(options, 100, 100))
{
Color[] pixels = new Color[10000];
for (int i = 0; i < pixels.Length; i++)
{
pixels[i] = Color.White;
}
image.SavePixels(image.Bounds, pixels);
// After executing the code above 40000 bytes are allocated to memory.
long diskBytes = Cache.AllocatedDiskBytesCount;
long memoryBytes = Cache.AllocatedMemoryBytesCount;
}
// The allocation properties may be used to check whether all Aspose.Imaging objects were properly disposed. If you've forgotten to call dispose on an object the cache values will not be 0.
l1 = Cache.AllocatedDiskBytesCount;
l2 = Cache.AllocatedMemoryBytesCount;
// Load an existing EMF file as Image.
using (Image image = Image.Load(dataDir + "Picture1.emf"))
{
// Call the Save method of Image class & Pass instance of WmfOptions class to Save method.
image.Save(dataDir + "ConvertEMFToWMF_out.wmf", new WmfOptions());
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load a GIF image and Convert the image to GIF image
Image objImage = Image.Load(dataDir + "asposelogo.gif");
using (GifImage gif = (GifImage)objImage)
{
// Iterate through arry of blocks in the GIF image
for (int i = 0; i < gif.Blocks.Length; i++)
{
// Convert block to GifFrameBlock class instance
GifFrameBlock gifBlock = gif.Blocks[i] as GifFrameBlock;
// Check if gif block is then ignore it
if (gifBlock == null)
{
continue;
}
// Create an instance of TIFF Option class and Save the GIFF block as TIFF image
TiffOptions objTiff = new TiffOptions(TiffExpectedFormat.Default);
gifBlock.Save(dataDir + "asposelogo" + i + "_out.tif", objTiff);
}
}
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
JpegCompressionColorMode[] colorTypes = new JpegCompressionColorMode[]
{
JpegCompressionColorMode.Grayscale,
JpegCompressionColorMode.YCbCr,
JpegCompressionColorMode.Rgb,
JpegCompressionColorMode.Cmyk,
JpegCompressionColorMode.Ycck,
};
string[] sourceFileNames = new string[]
{
"Rgb.jpg",
"Rgb.jpg",
"Rgb.jpg",
"Rgb.jpg",
"Rgb.jpg",
};
JpegOptions options = new JpegOptions();
options.BitsPerChannel = 12;
for (int i = 0; i < colorTypes.Length; ++i)
{
options.ColorType = colorTypes[i];
string fileName = colorTypes[i] + " 12-bit.jpg";
using (Image image = Image.Load(dataDir + sourceFileNames[i]))
{
image.Save(dataDir + fileName, options);
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load the image
using (SvgImage image = (SvgImage)Image.Load(dataDir + "aspose_logo.Svg"))
{
// Create an instance of PNG options and Save the results to disk
PngOptions pngOptions = new PngOptions();
image.Save(dataDir + "ConvertingSVGToRasterImages_out.png", pngOptions);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load the image
using (SvgImage image = (SvgImage)Image.Load(dataDir + "aspose_logo.Svg"))
{
// Create an instance of PNG options and Save the results to disk
PngOptions pngOptions = new PngOptions();
image.Save(dataDir + "ConvertingSVGToRasterImages_out.png", pngOptions);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Create an instance of Image class by loading an existing .
using (Image image = Image.Load(dataDir + "input.wmf"))
{
// Create an instance of EmfRasterizationOptions class.
EmfRasterizationOptions options = new EmfRasterizationOptions();
options.PageWidth = image.Width;
options.PageHeight = image.Height;
// Call save method to convert WMF to SVG format by passing output file name and SvgOptions class instance.
image.Save(dataDir + "ConvertWMFMetaFileToSVG_out.svg", new SvgOptions { VectorRasterizationOptions = options });
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load an existing WMF image
using (Image image = Image.Load(dataDir + "input.wmf"))
{
// Create an instance of EmfRasterizationOptions class and set different properties
EmfRasterizationOptions emfRasterizationOptions = new EmfRasterizationOptions();
emfRasterizationOptions.BackgroundColor = Color.WhiteSmoke;
emfRasterizationOptions.PageWidth = image.Width;
emfRasterizationOptions.PageHeight = image.Height;
// Create an instance of PdfOptions class and provide rasterization option
PdfOptions pdfOptions = new PdfOptions();
pdfOptions.VectorRasterizationOptions = emfRasterizationOptions;
// Call the save method, provide output path and PdfOptions to convert the WMF file to PDF and save the output
image.Save(dataDir + "ConvertWMFToPDF_out.pdf", pdfOptions);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
string inputFileName = dataDir + "thistlegirl_wmfsample.wmf";
string outputFileNamePng = dataDir + "thistlegirl_wmfsample.png";
using (Image image = Image.Load(inputFileName))
{
WmfRasterizationOptions rasterizationOptions = new WmfRasterizationOptions();
rasterizationOptions.BackgroundColor = Color.WhiteSmoke;
rasterizationOptions.PageWidth = image.Width;
rasterizationOptions.PageHeight = image.Height;
image.Save(outputFileNamePng, new PngOptions()
{
VectorRasterizationOptions = rasterizationOptions
});
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load an existing WMF image
using (Image image = Image.Load(dataDir + "input.wmf"))
{
// Calculate new Webp image height
double k = (image.Width * 1.00) / image.Height;
// Create an instance of EmfRasterizationOptions class and set different properties
EmfRasterizationOptions emfRasterization = new EmfRasterizationOptions
{
BackgroundColor = Color.WhiteSmoke,
PageWidth = 400,
PageHeight = (int)Math.Round(400 / k),
BorderX = 5,
BorderY = 10
};
// Create an instance of WebPOptions class and provide rasterization option
ImageOptionsBase imageOptions = new WebPOptions();
imageOptions.VectorRasterizationOptions = emfRasterization;
// Call the save method, provide output path and WebPOptions to convert the WMF file to Webp and save the output
image.Save(dataDir + "ConvertWMFToWebp_out.webp", imageOptions);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// EmfRecorderGraphics2D class provides you the frame or canvas to draw shapes on it.
EmfRecorderGraphics2D graphics = new EmfRecorderGraphics2D(new Rectangle(0, 0, 1000, 1000), new Size(1000, 1000), new Size(100, 100));
{
// Create an instance of Imaging Pen class and mention its color.
Pen pen = new Pen(Color.Bisque);
// Draw a line by calling DrawLine method and passing x,y coordinates of 1st point and same for 2nd point along with color infor as Pen.
graphics.DrawLine(pen, 1, 1, 50, 50);
// Reset the Pen color Specify the end style of the line.
pen = new Pen(Color.BlueViolet, 3);
pen.EndCap = LineCap.Round;
// Draw a line by calling DrawLine method and passing x,y coordinates of 1st point and same for 2nd point along with color infor as Pen and end style of line.
graphics.DrawLine(pen, 15, 5, 50, 60);
// Specify the end style of the line.
pen.EndCap = LineCap.Square;
graphics.DrawLine(pen, 5, 10, 50, 10);
pen.EndCap = LineCap.Flat;
// Draw a line by calling DrawLine method and passing parameters.
graphics.DrawLine(pen, new Point(5, 20), new Point(50, 20));
// Create an instance of HatchBrush class to define rectanglurar brush with with different settings.
HatchBrush hatchBrush = new HatchBrush
{
BackgroundColor = Color.AliceBlue,
ForegroundColor = Color.Red,
HatchStyle = HatchStyle.Cross
};
// Draw a line by calling DrawLine method and passing parameters.
pen = new Pen(hatchBrush, 7);
graphics.DrawRectangle(pen, 50, 50, 20, 30);
// Draw a line by calling DrawLine method and passing parameters with different mode.
graphics.BackgroundMode = EmfBackgroundMode.OPAQUE;
graphics.DrawLine(pen, 80, 50, 80, 80);
// Draw a polygon by calling DrawPolygon method and passing parameters with line join setting/style.
pen = new Pen(new SolidBrush(Color.Aqua), 3);
pen.LineJoin = LineJoin.MiterClipped;
graphics.DrawPolygon(pen, new[]
{
new Point(10, 20),
new Point(12, 45),
new Point(22, 48),
new Point(48, 36),
new Point(30, 55)
});
// Draw a rectangle by calling DrawRectangle method.
pen.LineJoin = LineJoin.Bevel;
graphics.DrawRectangle(pen, 50, 10, 10, 5);
pen.LineJoin = LineJoin.Round;
graphics.DrawRectangle(pen, 65, 10, 10, 5);
pen.LineJoin = LineJoin.Miter;
graphics.DrawRectangle(pen, 80, 10, 10, 5);
// Call EndRecording method to produce the final shape. EndRecording method will return the final shape as EmfImage. So create an instance of EmfImage class and initialize it with EmfImage returned by EndRecording method.
using (EmfImage image = graphics.EndRecording())
{
// Create an instance of PdfOptions class.
PdfOptions options = new PdfOptions();
// Create an instance of EmfRasterizationOptions class and define different settings.
EmfRasterizationOptions rasterizationOptions = new EmfRasterizationOptions();
rasterizationOptions.PageSize = image.Size;
options.VectorRasterizationOptions = rasterizationOptions;
string outPath = dataDir + "CreateEMFMetaFileImage_out.pdf";
image.Save(outPath, options);
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
WmfRecorderGraphics2D graphics = new WmfRecorderGraphics2D(new Rectangle(0, 0, 100, 100), 96);
// Define background color
graphics.BackgroundColor = Color.WhiteSmoke;
// Init Create an instance of Imaging Pen class, Brush class and mention its color.
Pen pen = new Pen(Color.Blue);
Brush brush = new SolidBrush(Color.YellowGreen);
// Polygon Fill polygon and then Draw a polygon
graphics.FillPolygon(brush, new[] { new Point(2, 2), new Point(20, 20), new Point(20, 2) });
graphics.DrawPolygon(pen, new[] { new Point(2, 2), new Point(20, 20), new Point(20, 2) });
brush = new HatchBrush { HatchStyle = HatchStyle.Cross, BackgroundColor = Color.White, ForegroundColor = Color.Silver };
// Fill ellipse and Draw an ellipse
graphics.FillEllipse(brush, new Rectangle(25, 2, 20, 20));
graphics.DrawEllipse(pen, new Rectangle(25, 2, 20, 20));
// Arc Define pen style by setting DashStyle value, Set color of the pen
pen.DashStyle = DashStyle.Dot;
pen.Color = Color.Black;
// Draw an Arc by calling DrawArc method and set CubicBezier
graphics.DrawArc(pen, new Rectangle(50, 2, 20, 20), 0, 180);
pen.DashStyle = DashStyle.Solid;
pen.Color = Color.Red;
// Draw an CubicBezier
graphics.DrawCubicBezier(pen, new Point(10, 25), new Point(20, 50), new Point(30, 50), new Point(40, 25));
// Image Create an Instance of Image class.
using (Image image = Image.Load(dataDir + @"WaterMark.bmp"))
{
// Cast the instance of image class to RasterImage.
RasterImage rasterImage = image as RasterImage;
if (rasterImage != null)
{
// Draw an image by calling DrawImage method and passing parameters rasterimage and point.
graphics.DrawImage(rasterImage, new Point(50, 50));
}
}
// Line Draw a line by calling DrawLine method and passing x,y coordinates of 1st point and same for 2nd point along with color infor as Pen.
graphics.DrawLine(pen, new Point(2, 98), new Point(2, 50));
// Pie Define settings of the brush object.
brush = new SolidBrush(Color.Green);
pen.Color = Color.DarkGoldenrod;
// Fill pie by calling FillPie method and passing parameters brush and an instance of Imaging Rectangle class.
graphics.FillPie(brush, new Rectangle(2, 38, 20, 20), 0, 45);
// Draw pie by calling DrawPie method and passing parameters pen and an instance of Imaging Rectangle class.
graphics.DrawPie(pen, new Rectangle(2, 38, 20, 20), 0, 45);
pen.Color = Color.AliceBlue;
// Polyline Draw Polyline by calling DrawPolyline method and passing parameters pen and points.
graphics.DrawPolyline(pen, new[] { new Point(50, 40), new Point(75, 40), new Point(75, 45), new Point(50, 45) });
// For having Strings Create an instance of Font class.
Font font = new Font("Arial", 16);
// Draw String by calling DrawString method and passing parameters string to display, color and X & Y coordinates.
graphics.DrawString("Aspose", font, Color.Blue, 25, 75);
// Call end recording of graphics object and save WMF image by calling Save method.
using (WmfImage image = graphics.EndRecording())
{
image.Save(dataDir + "CreateWMFMetaFileImage.wmf");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages() + "SavingRasterImageToTIFFWithCompression_out.tiff";
// Create an instance of TiffOptions and set its various properties
TiffOptions options = new TiffOptions(TiffExpectedFormat.Default);
options.BitsPerSample = new ushort[] { 8, 8, 8 };
options.Photometric = TiffPhotometrics.Rgb;
options.Xresolution = new TiffRational(72);
options.Yresolution = new TiffRational(72);
options.ResolutionUnit = TiffResolutionUnits.Inch;
options.PlanarConfiguration = TiffPlanarConfigs.Contiguous;
// Set the Compression to AdobeDeflate
options.Compression = TiffCompressions.AdobeDeflate;
// Or Deflate
// Options.Compression = TiffCompressions.Deflate;
// Create a new TiffImage with specific size and TiffOptions settings
using (TiffImage tiffImage = new TiffImage(new TiffFrame(options, 100, 100)))
{
// Loop over the pixels to set the color to red
for (int i = 0; i < 100; i++)
{
tiffImage.ActiveFrame.SetPixel(i, i, Color.Red);
}
// Save resultant image
tiffImage.Save(dataDir);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
using (EmfImage image = Image.Load(dataDir + "test.emf") as EmfImage)
{
image.Crop(new Rectangle(10, 10, 100, 150));
Console.WriteLine(image.Width);
Console.WriteLine(image.Height);
image.Save(dataDir + "test.emf_crop.emf");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load an existing WMF image
using (WmfImage image = (WmfImage)Image.Load(dataDir + "File.wmf"))
{
image.Crop(new Rectangle(300, 200, 200, 200));
// Create an instance of EmfRasterizationOptions class and set different properties
Aspose.Imaging.ImageOptions.EmfRasterizationOptions emfRasterization = new Aspose.Imaging.ImageOptions.EmfRasterizationOptions
{
BackgroundColor = Color.WhiteSmoke,
PageWidth = 1000,
PageHeight = 1000
};
// Create an instance of PngOptions class and provide rasterization option
ImageOptionsBase imageOptions = new PngOptions();
imageOptions.VectorRasterizationOptions = emfRasterization;
// Call the save method, provide output path and PngOptions to convert the cropped WMF file to PNG and save the output
image.Save(dataDir + "ConvertWMFToPNG_out.png", imageOptions);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
using (WmfImage image = Image.Load(dataDir + "test.wmf") as WmfImage)
{
image.Crop(new Rectangle(10, 10, 100, 150));
Console.WriteLine(image.Width);
Console.WriteLine(image.Height);
image.Save(dataDir + "test.wmf_crop.wmf");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DICOM();
using (var fileStream = new FileStream(dataDir + "file.dcm", FileMode.Open, FileAccess.Read))
using (DicomImage image = new DicomImage(fileStream))
{
// Adjust the brightness and Create an instance of BmpOptions for the resultant image and Save the resultant image
image.AdjustBrightness(50);
image.Save(dataDir + "AdjustBrightnessDICOM_out.bmp", new BmpOptions());
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DICOM();
using (var fileStream = new FileStream(dataDir + "file.dcm", FileMode.Open, FileAccess.Read))
using (DicomImage image = new DicomImage(fileStream))
{
// Adjust the contrast and Create an instance of BmpOptions for the resultant image and Save the resultant image
image.AdjustContrast(50);
image.Save(dataDir + "AdjustContrastDICOM_out.bmp", new BmpOptions());
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DICOM();
using (var fileStream = new FileStream(dataDir + "file.dcm", FileMode.Open, FileAccess.Read))
using (DicomImage image = new DicomImage(fileStream))
{
// Adjust the gamma and Create an instance of BmpOptions for the resultant image and Save the resultant image
image.AdjustGamma(50);
image.Save(dataDir + "AdjustGammaDICOM_out.bmp", new BmpOptions());
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DICOM();
using (var fileStream = new FileStream(dataDir + "file.dcm", FileMode.Open, FileAccess.Read))
using (DicomImage image = new DicomImage(fileStream))
{
// Supply the filters to DICOM image and Save the results to output path.
image.Filter(image.Bounds, new MedianFilterOptions(8));
image.Save(dataDir + "ApplyFilterOnDICOMImage_out.bmp", new BmpOptions());
}
string inputFile = dataDir + "image.dcm";
using (var fileStream = new FileStream(dataDir+"file.dcm", FileMode.Open, FileAccess.Read))
using (DicomImage image = new DicomImage(fileStream))
{
// Binarize image with bradley's adaptive threshold and Save the resultant image.
image.BinarizeBradley(10);
image.Save(dataDir + "BinarizationWithBradleysAdaptiveThreshold_out.bmp", new BmpOptions());
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DICOM();
using (var fileStream = new FileStream(dataDir + "file.dcm", FileMode.Open, FileAccess.Read))
using (DicomImage image = new DicomImage(fileStream))
{
// Binarize image with predefined fixed threshold and Save the resultant image.
image.BinarizeFixed(100);
image.Save(dataDir + "BinarizationWithFixedThresholdOnDICOMImage_out.bmp", new BmpOptions());
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DICOM();
using (var fileStream = new FileStream(dataDir + "file.dcm", FileMode.Open, FileAccess.Read))
using (DicomImage image = new DicomImage(fileStream))
{
// Binarize image with Otsu Thresholding and Save the resultant image.
image.BinarizeOtsu();
image.Save(dataDir + "BinarizationWithOtsuThresholdOnDICOMImage_out.bmp", new BmpOptions());
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DICOM();
using (var fileStream = new FileStream(dataDir + "file.dcm", FileMode.Open, FileAccess.Read))
using (DicomImage image = new DicomImage(fileStream))
{
// Call and supply the four values to Crop method and Save the results to disk
image.Crop(1, 1, 1, 1);
image.Save(dataDir + "DICOMCroppingByShifts_out.bmp", new BmpOptions());
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DICOM();
using (var fileStream = new FileStream(dataDir + "file.dcm", FileMode.Open, FileAccess.Read))
using (DicomImage image = new DicomImage(fileStream))
{
image.Resize(200, 200);
image.Save(dataDir + "DICOMSimpleResizing_out.bmp", new BmpOptions());
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DICOM();
using (var fileStream = new FileStream(dataDir + "file.dcm", FileMode.Open, FileAccess.Read))
using (DicomImage image = new DicomImage(fileStream))
{
image.ResizeHeightProportionally(100, ResizeType.AdaptiveResample);
image.Save(dataDir + "DICOMSOtherImageResizingOptions_out.bmp", new BmpOptions());
}
using (var fileStream = new FileStream(dataDir + "file.dcm", FileMode.Open, FileAccess.Read))
using (DicomImage image1 = new DicomImage(fileStream))
{
image1.ResizeWidthProportionally(150, ResizeType.AdaptiveResample);
image1.Save(dataDir + "DICOMSOtherImageResizingOptions1_out.bmp", new BmpOptions());
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DICOM();
using (var fileStream = new FileStream(dataDir + "file.dcm", FileMode.Open, FileAccess.Read))
using (DicomImage image = new DicomImage(fileStream))
{
// Peform Threshold dithering on the image and Save the resultant image.
image.Dither(DitheringMethod.ThresholdDithering, 1);
image.Save(dataDir + "DitheringForDICOMImage_out.bmp", new BmpOptions());
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DICOM();
using (var fileStream = new FileStream(dataDir + "file.dcm", FileMode.Open, FileAccess.Read))
using (DicomImage image = new DicomImage(fileStream))
{
// Flip Image & Save the resultant image.
image.RotateFlip(RotateFlipType.Rotate180FlipNone);
image.Save(dataDir + "FlipDICOMImage_out.bmp", new BmpOptions());
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DICOM();
using (var fileStream = new FileStream(dataDir + "file.dcm", FileMode.Open, FileAccess.Read))
using (DicomImage image = new DicomImage(fileStream))
{
// Transform image to its grayscale representation and Save the resultant image.
image.Grayscale();
image.Save(dataDir + "GrayscalingOnDICOM_out.bmp", new BmpOptions());
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DICOM();
using (var fileStream = new FileStream(dataDir + "file.dcm", FileMode.Open, FileAccess.Read))
using (DicomImage image = new DicomImage(fileStream))
{
image.Rotate(10);
image.Save(dataDir + "RotatingDICOMImage_out.bmp", new BmpOptions());
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Create an instance of JpegImage and load an image as of JpegImage
using (var image = (JpegImage)Image.Load(dataDir + "aspose-logo.jpg"))
{
// Peform Floyd Steinberg dithering on the current image and Save the resultant image
image.Dither(DitheringMethod.ThresholdDithering, 4);
image.Save(dataDir + "SampleImage_out.bmp");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DjVu();
// Load a DjVu image
using (DjvuImage image = (DjvuImage)Image.Load(dataDir + "Sample.djvu"))
{
// Create an instance of PdfOptions and Initialize the metadata for Pdf document
PdfOptions exportOptions = new PdfOptions();
exportOptions.PdfDocumentInfo = new PdfDocumentInfo();
// Create an instance of IntRange and initialize it with the range of DjVu pages to be exported
IntRange range = new IntRange(0, 5); //Export first 5 pages
// Initialize an instance of DjvuMultiPageOptions with range of DjVu pages to be exported and Save the result in PDF format
exportOptions.MultiPageOptions = new DjvuMultiPageOptions(range);
image.Save(dataDir + "ConvertDjVuToPDFFormat_out.pdf", exportOptions);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DjVu();
// Load a DjVu image
using (DjvuImage image = (DjvuImage)Image.Load(dataDir + "Sample.djvu"))
{
// Create an instance of TiffOptions & use preset options for Black n While with Deflate compression
TiffOptions exportOptions = new TiffOptions(TiffExpectedFormat.TiffDeflateBw);
// Initialize the DjvuMultiPageOptions and Call Save method while passing instance of TiffOptions
exportOptions.MultiPageOptions = new DjvuMultiPageOptions();
image.Save(dataDir + "ConvertDjVuToTIFFFormat_out.tiff", exportOptions);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DjVu();
// Load a DjVu image
using (DjvuImage image = (DjvuImage)Image.Load(dataDir + "Sample.djvu"))
{
// Create an instance of TiffOptions with preset options and IntRange and initialize it with range of pages to be exported
TiffOptions exportOptions = new TiffOptions(TiffExpectedFormat.TiffDeflateBw);
IntRange range = new IntRange(0, 2);