Skip to content

Instantly share code, notes, and snippets.

@aspose-imaging
Last active September 3, 2021 01:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save aspose-imaging/b93073a27bcdd4fefc2821e113f0cb3a to your computer and use it in GitHub Desktop.
Save aspose-imaging/b93073a27bcdd4fefc2821e113f0cb3a to your computer and use it in GitHub Desktop.
This Gist contains .NET code snippets for examples of Aspose.Imaging for .NET.
Aspose.Imaging-for-.NET
<UserControl x:Class="SilverlightApp.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Canvas x:Name="LayoutRoot" Background="White">
<Button x:Name="btnProcess" Width="100" Height="100" Content="Save File" Canvas.Top="10" Canvas.Left="10" Click="btnProcess_Click" />
</Canvas>
</UserControl>
// 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_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();
// 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");
}
// 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();
using (var image = Image.Load(dataDir + "aspose-logo.jpg"));
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(sourceFileNames[i]))
{
image.Save(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);
}
// 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();
// 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 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 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();
// 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_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);
// Initialize an instance of DjvuMultiPageOptions while passing instance of IntRange and Call Save method while passing instance of TiffOptions
exportOptions.MultiPageOptions = new DjvuMultiPageOptions(range);
image.Save(dataDir + "ConvertRangeOfDjVuPages_out.djvu", 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 BmpOptions and Set BitsPerPixel for resultant images
BmpOptions exportOptions = new BmpOptions();
exportOptions.BitsPerPixel = 32;
// Create an instance of IntRange and initialize it with range of pages to be exported
IntRange range = new IntRange(0, 2);
int counter = 0;
foreach (var i in range.Range)
{
// Save each page in separate file, as BMP do not support layering
exportOptions.MultiPageOptions = new DjvuMultiPageOptions(range.GetArrayOneItemFromIndex(counter));
image.Save(dataDir + string.Format("{0}_out.bmp", counter++), 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 PngOptions and Set ColorType to Grayscale
PngOptions exportOptions = new PngOptions();
exportOptions.ColorType = PngColorType.Grayscale;
// Create an instance of Rectangle and specify the portion on DjVu page
Rectangle exportArea = new Rectangle(0, 0, 500, 500);
// Specify the DjVu page index and Initialize an instance of DjvuMultiPageOptions while passing index of DjVu page index and instance of Rectangle covering the area to be exported
int exportPageIndex = 2;
exportOptions.MultiPageOptions = new DjvuMultiPageOptions(exportPageIndex, exportArea);
image.Save(dataDir + "ConvertSpecificPortionOfDjVuPage_out.djvu", exportOptions);
}
//Declare variables to store file paths for input and output images.
string sourceFiles = "Path_to_source_folder\\Source\\HDR - 3c.dng";
string destPath = "Path_to_results_folder\\Results\\result.jpg";
// Create an instance of Image class and load an exiting DNG file.
// Convert the image to DngImage object.
using (Aspose.Imaging.FileFormats.Dng.DngImage image = (Aspose.Imaging.FileFormats.Dng.DngImage)Image.Load(sourceFiles))
{
// Create an instance of JpegOptions class.
// convert and save to disk in Jpeg file format.
image.Save(destPath, new Aspose.Imaging.ImageOptions.JpegOptions());
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load an image in an instance of Image and Setting for image data to be cashed
using (RasterImage rasterImage = (RasterImage)Image.Load(dataDir + "aspose-logo.jpg"))
{
rasterImage.CacheData();
// Create an instance of Rectangle class and define X,Y and Width, height of the rectangle, and Save output image
Rectangle destRect = new Rectangle { X = -200, Y = -200, Width = 300, Height = 300 };
rasterImage.Save(dataDir + "Grayscaling_out.jpg", new JpegOptions(), destRect);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
string imageDataPath = "";
try
{
// Path & name of existing image.
imageDataPath = dataDir + "sample.bmp";
// Create the stream of the existing image file.
using (System.IO.FileStream fileStream = System.IO.File.Create(imageDataPath))
{
// Create an instance of BMP image option class.
using (Aspose.Imaging.ImageOptions.BmpOptions bmpOptions = new Aspose.Imaging.ImageOptions.BmpOptions())
{
bmpOptions.BitsPerPixel = 32;
// Set the source property of the imaging option class object.
bmpOptions.Source = new Aspose.Imaging.Sources.StreamSource(fileStream);
// DO PROCESSING.
// Following is the sample processing on the image. Un-comment to use it.
//using (RasterImage image = (RasterImage)Image.Create(bmpOptions, 10, 10))
//{
// Color[] pixels = new Color[4];
// for (int i = 0; i < 4; ++i)
// {
// pixels[i] = Color.FromArgb(40, 30, 20, 10);
// }
// image.SavePixels(new Rectangle(0, 0, 2, 2), pixels);
// image.Save();
//}
}
}
}
finally
{
// Delete the file. This statement is in the final block because in any case this statement should execute to make it sure that resource is properly disposed off.
System.IO.File.Delete(imageDataPath);
}
// Load an existing image (of type Gif) in an instance of the Image class
using (Image image = Image.Load(dataDir + "sample.gif"))
{
//Export to BMP, JPEG, PNG and TIFF file format using the default options
image.Save(dataDir + "_output.bmp", new BmpOptions());
image.Save(dataDir + "_output.jpeg", new JpegOptions());
image.Save(dataDir + "_output.png", new PngOptions());
image.Save(dataDir + "_output.tiff", new TiffOptions(TiffExpectedFormat.Default));
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load an existing image
using (Image image = Image.Load(dataDir + "sample.bmp"))
{
// Create an instance of PsdOptions, Set it�s various properties Save image to disk in PSD format
PsdOptions psdOptions = new PsdOptions();
psdOptions.ColorMode = ColorModes.Rgb;
psdOptions.CompressionMethod = CompressionMethod.Raw;
psdOptions.Version = 4;
image.Save(dataDir + "ExportImageToPSD_output.psd", psdOptions);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load an existing image
using (Image image = Image.Load(dataDir + "samplePsd.psd"))
{
var psdImage = (PsdImage)image;
var pngOptions = new PngOptions();
pngOptions.ColorType = PngColorType.TruecolorWithAlpha;
for (int i = 0; i < psdImage.Layers.Length; i++)
{
psdImage.Layers[i].Save(dataDir + "layer-" + i +"_out.png", pngOptions);
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
string[] paths = new string[]
{
@"C:\test\butterfly.gif",
@"C:\test\33715-cmyk.jpeg",
@"C:\test\3.JPG",
@"C:\test\test.j2k",
@"C:\test\Rings.png",
@"C:\test\3layers_maximized_comp.psd",
@"C:\test\img4.TIF",
@"C:\test\Lossy5.webp"
};
foreach (string path in paths)
{
string destPath = path + ".svg";
using (Image image = Image.Load(path))
{
SvgOptions svgOptions = new SvgOptions();
SvgRasterizationOptions svgRasterizationOptions = new SvgRasterizationOptions();
svgOptions.VectorRasterizationOptions = svgRasterizationOptions;
svgOptions.VectorRasterizationOptions.PageWidth = image.Width;
svgOptions.VectorRasterizationOptions.PageHeight = image.Height;
image.Save(destPath, svgOptions);
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
using (Image image = Image.Load(dataDir + "Picture1.emf"))
{
EmfRasterizationOptions emfRasterizationOptions = new EmfRasterizationOptions();
emfRasterizationOptions.BackgroundColor = Color.White;
emfRasterizationOptions.PageWidth = image.Width;
emfRasterizationOptions.PageHeight = image.Height;
image.Save(dataDir + "TextAsShapes_out.svg", new SvgOptions
{
VectorRasterizationOptions = emfRasterizationOptions,
TextAsShapes = true
});
image.Save(dataDir + "TextAsShapesFalse_out.svg", new SvgOptions
{
VectorRasterizationOptions = emfRasterizationOptions,
TextAsShapes = false
});
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
using (TiffImage multiImage = (TiffImage)Image.Load(dataDir + "SampleTiff1.tiff"))
{
// Create an instance of int to keep track of frames in TiffImage
int frameCounter = 0;
// Iterate over the TiffFrames in TiffImage
foreach (TiffFrame tiffFrame in multiImage.Frames)
{
multiImage.ActiveFrame = tiffFrame;
// Load Pixels of TiffFrame into an array of Colors
Color[] pixels = multiImage.LoadPixels(tiffFrame.Bounds);
// Create an instance of bmpCreateOptions
BmpOptions bmpCreateOptions = new BmpOptions();
bmpCreateOptions.BitsPerPixel = 24;
// Set the Source of bmpCreateOptions as FileCreateSource by specifying the location where output will be saved
bmpCreateOptions.Source = new FileCreateSource(string.Format("{0}\\ConcatExtractTIFFFramesToBMP_out{1}.bmp", dataDir, frameCounter), false);
// Create a new bmpImage
using (BmpImage bmpImage = (BmpImage)Image.Create(bmpCreateOptions, tiffFrame.Width, tiffFrame.Height))
{
// Save the bmpImage with pixels from TiffFrame
bmpImage.SavePixels(tiffFrame.Bounds, pixels);
bmpImage.Save();
}
frameCounter++;
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
using (RasterImage image = (RasterImage)Image.Load(dataDir + "aspose-logo.jpg"))
{
// Gets the date from [FileInfo]
string modifyDate = image.GetModifyDate(true).ToString();
Console.WriteLine("Last modify date using [FileInfo]: {0}", modifyDate);
// Gets the date from XMP metadata of [FileInfo] as long as it's not default case
modifyDate = image.GetModifyDate(false).ToString();
Console.WriteLine("Last modify date using info from [FileInfo] and XMP metadata: {0}", modifyDate);
}
// 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();
}
// Transform image to its grayscale representation and Save the resultant image
rasterCachedImage.Grayscale();
rasterCachedImage.Save(dataDir + "Grayscaling_out.jpg");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Sets the maximum allowed pixel difference. If greater than zero, lossy compression will be used.
// Recommended value for optimal lossy compression is 80. 30 is very light compression, 200 is heavy.
GifOptions gifExport = new GifOptions();
gifExport.MaxDiff = 80;
using (Image image = Image.Load("anim_orig.gif"))
{
image.Save("anim_lossy-80.gif", gifExport);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_JPEG();
using (MemoryStream stream = new MemoryStream())
{
JpegImage thumbnailImage = new JpegImage(100, 100);
JpegImage image = new JpegImage(1000, 1000);
image.ExifData = new JpegExifData();
image.ExifData.Thumbnail = thumbnailImage;
image.Save(dataDir + stream + "_out.jpg");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_JPEG();
using (MemoryStream stream = new MemoryStream())
{
JpegImage thumbnailImage = new JpegImage(100, 100);
JpegImage image = new JpegImage(1000, 1000);
image.Jfif = new JFIFData();
image.Jfif.Thumbnail = thumbnailImage;
image.Save(dataDir + stream + "_out.jpeg");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_JPEG();
// Load a Jpeg image from file path location or stream
using (JpegImage image = (JpegImage)Image.Load(dataDir + "aspose-logo.jpg"))
{
// Perform the automatic rotation on the image depending on the orientation data stored in the EXIF and Save the result on disc or stream
image.AutoRotate();
image.Save(dataDir + "aspose-logo_out.jpg");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_JPEG();
using (var original = Image.Load(dataDir+"ColorGif.gif"))
{
var jpegOptions = new JpegOptions()
{
ColorType = JpegCompressionColorMode.Grayscale,
CompressionType = JpegCompressionMode.Progressive,
};
original.Save("D:/temp/result.jpg", jpegOptions);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_JPEG();
// Load an existing image into an instance of RasterImage class
using (RasterImage rasterImage = (RasterImage)Image.Load(dataDir + "aspose-logo.jpg"))
{
if (!rasterImage.IsCached)
{
rasterImage.CacheData();
}
// Create an instance of Rectangle class with desired size, Perform the crop operation on object of Rectangle class and Save the results to disk
Rectangle rectangle = new Rectangle(20, 20, 20, 20);
rasterImage.Crop(rectangle);
rasterImage.Save(dataDir + "CroppingByRectangle_out.jpg");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_JPEG();
// Load an existing image into an instance of RasterImage class
using (RasterImage rasterImage = (RasterImage)Image.Load(dataDir + "aspose-logo.jpg"))
{
// Before cropping, the image should be cached for better performance
if (!rasterImage.IsCached)
{
rasterImage.CacheData();
}
// Define shift values for all four sides
int leftShift = 10;
int rightShift = 10;
int topShift = 10;
int bottomShift = 10;
// Based on the shift values, apply the cropping on image Crop method will shift the image bounds toward the center of image and Save the results to disk
rasterImage.Crop(leftShift, rightShift, topShift, bottomShift);
rasterImage.Save(dataDir + "CroppingByShifts_out.jpg");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_JPEG();
using (JpegImage image = (JpegImage)Image.Load(dataDir + "aspose-logo.jpg"))
{
JpegExifData exifData = image.ExifData;
Type type = exifData.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine(property.Name + ":" + property.GetValue(exifData, null));
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_JPEG();
// Load an image using the factory method Load exposed by Image class
using (Image image = Image.Load(dataDir + "aspose-logo.jpg"))
{
// Initialize an object of ExifData and fill it will image's EXIF information and Check if image has any EXIF entries defined
ExifData exif = ((JpegImage)image).ExifData;
if (exif != null)
{
// In order to get all EXIF tags, first get the Type of EXIF object, Get all properties of EXIF object into an array and Iterate over the EXIF properties
Type type = exif.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
// Display property name and its value
Console.WriteLine(property.Name + ":" + property.GetValue(exif, null));
}
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_JPEG();
using (JpegImage image = (JpegImage)Image.Load(dataDir + "aspose-logo.jpg"))
{
JpegExifData exifData = image.ExifData;
Console.WriteLine("Camera Owner Name: " + exifData.CameraOwnerName);
Console.WriteLine("Aperture Value: " + exifData.ApertureValue);
Console.WriteLine("Orientation: " + exifData.Orientation);
Console.WriteLine("Focal Length: " + exifData.FocalLength);
Console.WriteLine("Compression: " + exifData.Compression);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_JPEG();
// Load an image using the factory method Load exposed by Image class
using (Image image = Image.Load(dataDir + "aspose-logo.jpg"))
{
// Initialize an object of ExifData and fill it will image's EXIF information
ExifData exif = ((JpegImage)image).ExifData;
// Check if image has any EXIF entries defined and Display a few EXIF entries
if (exif != null)
{
Console.WriteLine("Exif WhiteBalance: " + exif.WhiteBalance);
Console.WriteLine("Exif PixelXDimension: " + exif.PixelXDimension);
Console.WriteLine("Exif PixelYDimension: " + exif.PixelYDimension);
Console.WriteLine("Exif ISOSpeed: " + exif.ISOSpeed);
Console.WriteLine("Exif FocalLength: " + exif.FocalLength);
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_JPEG();
// Loading and Rotating Image
using (var image = Image.Load(dataDir + "aspose-logo.jpg"))
{
image.RotateFlip(RotateFlipType.Rotate270FlipNone);
image.Save(dataDir + "RotatingAnImage_out.jpg");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_JPEG();
int bpp = 2; // Set 2 bits per sample to see the difference in size and quality
// The origin PNG with 8 bits per sample
string originPngFileName = "lena24b.png";
// The output JPEG-LS with 2 bits per sample.
string outputJpegFileName = "lena24b " + bpp + "-bit Gold.jls";
using (PngImage pngImage = (PngImage)Image.Load(originPngFileName))
{
JpegOptions jpegOptions = new JpegOptions();
jpegOptions.BitsPerChannel = (byte)bpp;
jpegOptions.CompressionType = JpegCompressionMode.JpegLs;
pngImage.Save(outputJpegFileName, jpegOptions);
}
// The output PNG is produced from JPEG-LS to check image visually.
string outputPngFileName = "lena24b " + bpp + "-bit Gold.png";
using (JpegImage jpegImage = (JpegImage)Image.Load(outputJpegFileName))
{
jpegImage.Save(outputPngFileName, new PngOptions());
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_JPEG();
MemoryStream jpegStream = new MemoryStream();
try
{
// Save to JPEG Lossless CMYK
using (JpegImage image = (JpegImage)Image.Load("056.jpg"))
{
JpegOptions options = new JpegOptions();
options.ColorType = JpegCompressionColorMode.Cmyk;
options.CompressionType = JpegCompressionMode.Lossless;
// The default profiles will be used.
options.RgbColorProfile = null;
options.CmykColorProfile = null;
image.Save(jpegStream, options);
}
// Load from JPEG Lossless CMYK
jpegStream.Position = 0;
using (JpegImage image = (JpegImage)Image.Load(jpegStream))
{
image.Save("056_cmyk.png", new PngOptions());
}
}
finally
{
jpegStream.Dispose();
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_JPEG();
MemoryStream jpegStream = new MemoryStream();
FileStream rgbProfileStream = new FileStream("eciRGB_v2.icc", FileMode.Open);
FileStream cmykProfileStream = new FileStream("ISOcoated_v2_FullGamut4.icc", FileMode.Open);
Sources.StreamSource rgbColorProfile = new Sources.StreamSource(rgbProfileStream);
Sources.StreamSource cmykColorProfile = new Sources.StreamSource(cmykProfileStream);
try
{
// Save to JPEG Lossless CMYK
using (JpegImage image = (JpegImage)Image.Load("056.jpg"))
{
JpegOptions options = new JpegOptions();
options.ColorType = JpegCompressionColorMode.Cmyk;
options.CompressionType = JpegCompressionMode.Lossless;
// The custom profiles will be used.
options.RgbColorProfile = rgbColorProfile;
options.CmykColorProfile = cmykColorProfile;
image.Save(jpegStream, options);
}
// Load from JPEG Lossless CMYK
jpegStream.Position = 0;
rgbProfileStream.Position = 0;
cmykProfileStream.Position = 0;
using (JpegImage image = (JpegImage)Image.Load(jpegStream))
{
image.RgbColorProfile = rgbColorProfile;
image.CmykColorProfile = cmykColorProfile;
image.Save("056_cmyk_custom_profiles.png", new PngOptions());
}
}
finally
{
jpegStream.Dispose();
rgbProfileStream.Dispose();
cmykProfileStream.Dispose();
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_JPEG();
string sourceJpegFileName = @"c:\aspose.work\lena24b.jls";
string outputPngFileName = @"c:\aspose.work\\lena24b.png";
string outputPngRectFileName = @"c:\aspose.work\\lena24b_rect.png";
// Decoding
using (JpegImage jpegImage = (JpegImage)Image.Load(sourceJpegFileName))
{
JpegOptions jpegOptions = jpegImage.JpegOptions;
// You can read new options:
System.Console.WriteLine("Compression type: {0}", jpegOptions.CompressionType);
System.Console.WriteLine("Allowed lossy error (NEAR): {0}", jpegOptions.JpegLsAllowedLossyError);
System.Console.WriteLine("Interleaved mode (ILV): {0}", jpegOptions.JpegLsInterleaveMode);
System.Console.WriteLine("Horizontal sampling: {0}", ArrayToString(jpegOptions.HorizontalSampling));
System.Console.WriteLine("Vertical sampling: {0}", ArrayToString(jpegOptions.VerticalSampling));
// Save the original JPEG-LS image to PNG.
jpegImage.Save(outputPngFileName, new PngOptions());
// Save the bottom-right quarter of the original JPEG-LS to PNG
Rectangle quarter = new Rectangle(jpegImage.Width / 2, jpegImage.Height / 2, jpegImage.Width / 2, jpegImage.Height / 2);
jpegImage.Save(outputPngRectFileName, new PngOptions(), quarter);
}
}
private static int ArrayToString(byte[] horizontalSampling)
{
throw new NotImplementedException();
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_JPEG();
MemoryStream jpegLsStream = new MemoryStream();
try
{
// Save to CMYK JPEG-LS
using (JpegImage image = (JpegImage)Image.Load("056.jpg"))
{
JpegOptions options = new JpegOptions();
//Just replace one line given below in examples to use YCCK instead of CMYK
//options.ColorType = JpegCompressionColorMode.Cmyk;
options.ColorType = JpegCompressionColorMode.Cmyk;
options.CompressionType = JpegCompressionMode.JpegLs;
// The default profiles will be used.
options.RgbColorProfile = null;
options.CmykColorProfile = null;
image.Save(jpegLsStream, options);
}
// Load from CMYK JPEG-LS
jpegLsStream.Position = 0;
using (JpegImage image = (JpegImage)Image.Load(jpegLsStream))
{
image.Save("056_cmyk.png", new PngOptions());
}
}
finally
{
jpegLsStream.Dispose();
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_JPEG();
int bpp = 2; // Set 2 bits per sample to see the difference in size and quality
// The origin PNG with 8 bits per sample
string originPngFileName = "lena24b.png";
// The output JPEG-LS with 2 bits per sample.
string outputJpegFileName = "lena24b " + bpp + "-bit Gold.jls";
using (PngImage pngImage = (PngImage)Image.Load(originPngFileName))
{
JpegOptions jpegOptions = new JpegOptions();
jpegOptions.BitsPerChannel = (byte)bpp;
jpegOptions.CompressionType = JpegCompressionMode.JpegLs;
pngImage.Save(outputJpegFileName, jpegOptions);
}
// The output PNG is produced from JPEG-LS to check image visually.
string outputPngFileName = "lena24b " + bpp + "-bit Gold.png";
using (JpegImage jpegImage = (JpegImage)Image.Load(outputJpegFileName))
{
jpegImage.Save(outputPngFileName, new PngOptions());
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_JPEG();
int bpp = 2; // Set 2 bits per sample to see the difference in size and quality
// The origin PNG with 8 bits per sample
string originPngFileName = "lena24b.png";
// The output JPEG-LS with 2 bits per sample.
string outputJpegFileName = "lena24b " + bpp + "-bit Gold.jls";
using (PngImage pngImage = (PngImage)Image.Load(originPngFileName))
{
JpegOptions jpegOptions = new JpegOptions();
jpegOptions.BitsPerChannel = (byte)bpp;
jpegOptions.CompressionType = JpegCompressionMode.JpegLs;
pngImage.Save(outputJpegFileName, jpegOptions);
}
// The output PNG is produced from JPEG-LS to check image visually.
string outputPngFileName = "lena24b " + bpp + "-bit Gold.png";
using (JpegImage jpegImage = (JpegImage)Image.Load(outputJpegFileName))
{
jpegImage.Save(outputPngFileName, new PngOptions());
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_JPEG();
// Load an image using the factory method Load exposed by Image class
using (Image image = Image.Load(dataDir + "aspose-logo.jpg"))
{
// Initialize an object of ExifData and fill it will image's EXIF information
JpegExifData exif = ((JpegImage)image).ExifData;
// Set LensMake, WhiteBalance, Flash information Save the image
exif.LensMake = "Sony";
exif.WhiteBalance = ExifWhiteBalance.Auto;
exif.Flash = ExifFlash.Fired;
image.Save(dataDir + "aspose-logo_out.jpg");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MetaFiles();
string[] filePaths = {
"Picture1.emf"
};
foreach (string filePath in filePaths)
{
string outPath = dataDir + filePath + "_out.pdf";
using (var image = (EmfImage)Image.Load(dataDir + filePath))
using (FileStream outputStream = new FileStream(outPath, FileMode.Create))
{
if (!image.Header.EmfHeader.Valid)
{
throw new ImageLoadException(string.Format("The file {0} is not valid", outPath));
}
EmfRasterizationOptions emfRasterization = new EmfRasterizationOptions();
emfRasterization.PageWidth = image.Width;
emfRasterization.PageHeight = image.Height;
emfRasterization.BackgroundColor = Color.WhiteSmoke;
PdfOptions pdfOptions = new PdfOptions();
pdfOptions.VectorRasterizationOptions = emfRasterization;
image.Save(outputStream, pdfOptions);
}
}
// List of existing EMF images.
string path = @"";
string[] files = new string[] { "TestEmfRotatedText.emf", "TestEmfPlusFigures.emf", "TestEmfBezier.emf" };
// Loop for each file name.
foreach (string file in files)
{
// Input file name & path.
string filePath = System.IO.Path.Combine(path, file);
// Load the EMF image as image and convert it to MetaImage object.
using (Aspose.Imaging.FileFormats.Emf.MetaImage image = (Aspose.Imaging.FileFormats.Emf.MetaImage)Image.Load(filePath))
{
// Convert the EMF image to WMF image by creating and passing WMF image options class object.
image.Save(filePath + "_out.wmf", new Aspose.Imaging.ImageOptions.WmfOptions());
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MetaFiles();
// Create an instance of Rasterization options
EmfRasterizationOptions emfRasterizationOptions = new EmfRasterizationOptions();
emfRasterizationOptions.BackgroundColor = Color.WhiteSmoke;
// Create an instance of PNG options
PdfOptions pdfOptions = new PdfOptions();
pdfOptions.VectorRasterizationOptions = emfRasterizationOptions;
// Load an existing image into an instance of EMF class
using (EmfImage image = (EmfImage)Image.Load(dataDir + "Picture1.emf"))
{
using (FileStream outputStream = new FileStream(dataDir + "CroppingByRectangleEMFImage_out.pdf", FileMode.Create))
{
// Create an instance of Rectangle class with desired size and Perform the crop operation on object of Rectangle class and Set height and width and Save the results to disk
image.Crop(new Rectangle(30, 50, 100, 150));
pdfOptions.VectorRasterizationOptions.PageWidth = image.Width;
pdfOptions.VectorRasterizationOptions.PageHeight = image.Height;
image.Save(outputStream, pdfOptions);
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MetaFiles();
// Create an instance of Rasterization options
EmfRasterizationOptions emfRasterizationOptions = new EmfRasterizationOptions();
emfRasterizationOptions.BackgroundColor = Color.WhiteSmoke;
// Create an instance of PNG options
PdfOptions pdfOptions = new PdfOptions();
pdfOptions.VectorRasterizationOptions = emfRasterizationOptions;
// Load an existing image into an instance of EMF class
using (EmfImage image = (EmfImage)Image.Load(dataDir + "Picture1.emf"))
{
using (FileStream outputStream = new FileStream(dataDir + "CroppingEMFImage_out.pdf", FileMode.Create))
{
// Based on the shift values, apply the cropping on image and Crop method will shift the image bounds toward the center of image
image.Crop(30, 40, 50, 60);
// Set height and width and Save the results to disk
pdfOptions.VectorRasterizationOptions.PageWidth = image.Width;
pdfOptions.VectorRasterizationOptions.PageHeight = image.Height;
image.Save(outputStream, pdfOptions);
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MetaFiles();
string outputfile = dataDir + "file_out";
// Create EmfRasterizationOption class instance and set properties
EmfRasterizationOptions emfRasterizationOptions = new EmfRasterizationOptions();
emfRasterizationOptions.BackgroundColor = Color.PapayaWhip;
emfRasterizationOptions.PageWidth = 300;
emfRasterizationOptions.PageHeight = 300;
// Load an existing EMF file as iamge and convert it to EmfImage class object
using (var image = (EmfImage)Image.Load(dataDir + "Picture1.emf"))
{
if (!image.Header.EmfHeader.Valid)
{
throw new ImageLoadException(string.Format("The file {0} is not valid", dataDir + "Picture1.emf"));
}
// Convert EMF to BMP, GIF, JPEG, J2K, PNG, PSD, TIFF and WebP
image.Save(outputfile + ".bmp", new BmpOptions { VectorRasterizationOptions = emfRasterizationOptions });
image.Save(outputfile + ".gif", new GifOptions { VectorRasterizationOptions = emfRasterizationOptions });
image.Save(outputfile + ".jpeg", new JpegOptions { VectorRasterizationOptions = emfRasterizationOptions });
image.Save(outputfile + ".j2k", new Jpeg2000Options { VectorRasterizationOptions = emfRasterizationOptions });
image.Save(outputfile + ".png", new PngOptions { VectorRasterizationOptions = emfRasterizationOptions });
image.Save(outputfile + ".psd", new PsdOptions { VectorRasterizationOptions = emfRasterizationOptions });
image.Save(outputfile + ".tiff", new TiffOptions(TiffExpectedFormat.TiffLzwRgb) { VectorRasterizationOptions = emfRasterizationOptions });
image.Save(outputfile + ".webp", new WebPOptions { VectorRasterizationOptions = emfRasterizationOptions });
}
string dataDir = RunExamples.GetDataDir_MetaFiles();
}
#region Constants
//Please Update path int constant SourceFolder.
private const string ImageFolderName = "Images";
private const string OutFolderName = "Out";
private const string SourceFolder = @"D:\ImageTests";
private static readonly string OutFolder = Path.Combine(SourceFolder, OutFolderName);
private static readonly string ImageFolder = Path.Combine(OutFolder, ImageFolderName);
#endregion
#region Methods
public void SaveWithEmbeddedImages()
{
string[] files = new string[1] { "auto.svg" };
for (int i = 0; i < files.Length; i++)
{
this.Save(true, files[i], null);
}
}
public void SaveWithExportImages()
{
string[] files = new string[1] { "auto.svg" };
string[][] expectedImages = new string[1][]
{
new string[16]
{
"svg_img1.png", "svg_img10.png", "svg_img11.png","svg_img12.png",
"svg_img13.png", "svg_img14.png", "svg_img15.png", "svg_img16.png",
"svg_img2.png", "svg_img3.png", "svg_img4.png", "svg_img5.png",
"svg_img6.png","svg_img7.png", "svg_img8.png", "svg_img9.png"
},
};
for (int i = 0; i < files.Length; i++)
{
this.Save(false, files[i], expectedImages[i]);
}
}
private void Save(bool useEmbedded, string fileName, string[] expectedImages)
{
if (!Directory.Exists(OutFolder))
{
Directory.CreateDirectory(OutFolder);
}
string storeType = useEmbedded ? "Embedded" : "Stream";
string inputFile = Path.Combine(SourceFolder, fileName);
string outFileName = Path.GetFileNameWithoutExtension(fileName) + "_" + storeType + ".svg";
string outputFile = Path.Combine(OutFolder, outFileName);
string imageFolder = string.Empty;
using (Image image = Image.Load(inputFile))
{
EmfRasterizationOptions emfRasterizationOptions = new EmfRasterizationOptions();
emfRasterizationOptions.BackgroundColor = Color.White;
emfRasterizationOptions.PageWidth = image.Width;
emfRasterizationOptions.PageHeight = image.Height;
string testingFileName = Path.GetFileNameWithoutExtension(inputFile);
imageFolder = Path.Combine(ImageFolder, testingFileName);
image.Save(outputFile,
new SvgOptions
{
VectorRasterizationOptions = emfRasterizationOptions,
Callback =
new SvgCallbackImageTest(useEmbedded, imageFolder)
{
Link = ImageFolderName + "/" + testingFileName
}
});
}
if (!useEmbedded)
{
string[] files = Directory.GetFiles(imageFolder);
if (files.Length != expectedImages.Length)
{
throw new Exception(string.Format("Expected count font files = {0}, Current count image files = {1}", expectedImages.Length, files.Length));
}
for (int i = 0; i < files.Length; i++)
{
string file = Path.GetFileName(files[i]);
if (string.IsNullOrEmpty(file))
{
throw new Exception(string.Format("Expected file name: '{0}', current is empty", expectedImages[i]));
}
if (file.ToLower() != expectedImages[i])
{
throw new Exception(string.Format("Expected file name: '{0}', current: '{1}'", expectedImages[i], file.ToLower()));
}
}
}
}
#endregion
private class SvgCallbackImageTest : FileFormats.Svg.SvgResourceKeeperCallback
{
#region Fields
/// <summary>
/// The out folder
/// </summary>
private readonly string outFolder;
/// <summary>
/// The use embedded font
/// </summary>
private readonly bool useEmbeddedImage;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="SvgTests.SvgCallbackFontTest" /> class.
/// </summary>
/// <param name="useEbeddedImage">if set to <c>true</c> [use ebedded image].</param>
/// <param name="outFolder">The out folder.</param>
public SvgCallbackImageTest(bool useEbeddedImage, string outFolder)
{
this.useEmbeddedImage = useEbeddedImage;
this.outFolder = outFolder;
}
#endregion
#region Properties
public string Link { get; set; }
#endregion
#region Methods
/// <summary>
/// Called when image resource ready.
/// </summary>
/// <param name="imageData">The resource data.</param>
/// <param name="imageType">Type of the image.</param>
/// <param name="suggestedFileName">Name of the suggested file.</param>
/// <param name="useEmbeddedImage">if set to <c>true</c> the embedded image must be used.</param>
/// <returns>
/// Returns path to saved resource. Path should be relative to target SVG document.
/// </returns>
public override string OnImageResourceReady(byte[] imageData, SvgImageType imageType, string suggestedFileName, ref bool useEmbeddedImage)
{
useEmbeddedImage = this.useEmbeddedImage;
if (useEmbeddedImage)
{
return suggestedFileName;
}
string fontFolder = this.outFolder;
if (!Directory.Exists(fontFolder))
{
Directory.CreateDirectory(fontFolder);
}
string fileName = fontFolder + @"\" + Path.GetFileName(suggestedFileName);
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
fs.Write(imageData, 0, imageData.Length);
}
return @"./" + this.Link + "/" + suggestedFileName;
}
#endregion
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MetaFiles();
EmfRecorderGraphics2D graphics = new EmfRecorderGraphics2D(
new Rectangle(0, 0, 5000, 5000),
new Size(5000, 5000),
new Size(1000, 1000));
{
Font font = new Font("Arial", 10, FontStyle.Bold | FontStyle.Underline);
graphics.DrawString(font.Name + " " + font.Size + " " + font.Style.ToString(), font, Color.Brown, 10, 10);
graphics.DrawString("some text", font, Color.Brown, 10, 30);
font = new Font("Arial", 24, FontStyle.Italic | FontStyle.Strikeout);
graphics.DrawString(font.Name + " " + font.Size + " " + font.Style.ToString(), font, Color.Brown, 20, 50);
graphics.DrawString("some text", font, Color.Brown, 20, 80);
using (EmfImage image = graphics.EndRecording())
{
var path = dataDir+ @"Fonts.emf";
image.Save(path, new EmfOptions());
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MetaFiles();
var path = dataDir + "TestEmfPlusFigures.emf";
using (var image = (MetaImage)Image.Load(path))
{
image.Save(path + ".emf", new EmfOptions());
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MetaFiles();
var path = dataDir+"TestEmfBezier.emf";
using (var image = (MetaImage)Image.Load(path))
{
image.Save(path + ".emf", new EmfOptions());
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MetaFiles();
// Create an instance of Rasterization options
EmfRasterizationOptions emfRasterizationOptions = new EmfRasterizationOptions();
emfRasterizationOptions.BackgroundColor = Color.WhiteSmoke;
// Create an instance of PNG options
PngOptions pngOptions = new PngOptions();
pngOptions.VectorRasterizationOptions = emfRasterizationOptions;
// Load an existing EMF image
using (EmfImage image = (EmfImage)Image.Load(dataDir + "Picture1.emf"))
{
image.CacheData();
// Set height and width, Reset font settings
pngOptions.VectorRasterizationOptions.PageWidth = 300;
pngOptions.VectorRasterizationOptions.PageHeight = 350;
FontSettings.Reset();
image.Save(dataDir + "Picture1_default_fonts_out.png", pngOptions);
// Initialize font list
List<string> fonts = new List<string>(FontSettings.GetDefaultFontsFolders());
// Add new font path to font list and Assign list of font folders to font settings and Save the EMF file to PNG image with new font
fonts.Add(dataDir + "arialAndTimesAndCourierRegular.xml");
FontSettings.SetFontsFolders(fonts.ToArray(), true);
image.Save(dataDir + "Picture1_with_my_fonts_out.png", pngOptions);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MetaFiles();
FontSettings.DefaultFontName = "Comic Sans MS";
string[] files = new string[] { "missing-font.emf", "missing-font.odg", "missing-font.svg", "missing-font.wmf" };
VectorRasterizationOptions[] options = new VectorRasterizationOptions[] { new EmfRasterizationOptions(), new MetafileRasterizationOptions(), new SvgRasterizationOptions(), new WmfRasterizationOptions() };
for (int i = 0; i < files.Length; i++)
{
string outFile = files[i] + ".png";
using (Image img = Image.Load(files[i]))
{
options[i].PageWidth = img.Width;
options[i].PageHeight = img.Height;
img.Save(outFile, new PngOptions()
{
VectorRasterizationOptions = options[i]
});
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
//String path = @"C:\Imaging Data\IMG\";
int page = 0;
var tempImage = Aspose.Imaging.Image.Load(dataDir + "Image1.png");
int width = 500;
int height = 500;
width = tempImage.Width;
height = tempImage.Height;
Aspose.Imaging.ImageOptions.TiffOptions tiffOptions = new Aspose.Imaging.ImageOptions.TiffOptions(TiffExpectedFormat.Default);
tiffOptions.Source = new Aspose.Imaging.Sources.FileCreateSource(dataDir+"MultiPage.tiff", false);
//Create an instance of Image and initialize it with instance of BmpOptions by calling Create method
using (TiffImage TiffImage = (TiffImage)Aspose.Imaging.Image.Create(tiffOptions, width, height))
{
//do some image processing
DirectoryInfo di = new DirectoryInfo(dataDir);
FileInfo[] files = di.GetFiles("*.img");
int index = 0;
foreach (var file in files)
{
using (Aspose.Imaging.Image inputImage = Aspose.Imaging.Image.Load(file.FullName))
{
inputImage.Resize(width, height, ResizeType.NearestNeighbourResample);
// var frame = TiffImage.ActiveFrame;
if (index > 0)
{
var newframe = new TiffFrame(tiffOptions, width, height);
TiffImage.AddFrame(newframe);
int cnt = TiffImage.Frames.Count();
}
var frame = TiffImage.Frames[index];
frame.SavePixels(frame.Bounds, ((RasterImage)inputImage).LoadPixels(inputImage.Bounds));
index += 1;
}
}
// save all changes
TiffImage.Save(dataDir+"output.tiff");
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PNG();
using (PngImage png = (PngImage)Image.Load(dataDir + "aspose_logo.png"))
{
// Create an instance of PngOptions, Set the PNG filter method and Save changes to the disc
PngOptions options = new PngOptions();
options.FilterType = PngFilterType.Paeth;
png.Save(dataDir + "ApplyFilterMethod_out.jpg", options);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PNG();
// Create an instance of Image class and load a PNG image
using (Image img = Image.Load(dataDir + "aspose_logo.png"))
{
// Create an instance of RasterImage and get the pixels array by calling method LoadArgb32Pixels.
RasterImage rasterImg = img as RasterImage;
if (rasterImg != null)
{
int[] pixels = rasterImg.LoadArgb32Pixels(img.Bounds);
if (pixels != null)
{
// Iterate through the pixel array and Check the pixel information that if it is a transparent color pixel and Change the pixel color to white
for (int i = 0; i < pixels.Length; i++)
{
if (pixels[i] == rasterImg.TransparentColor.ToArgb())
{
pixels[i] = Color.White.ToArgb();
}
}
// Replace the pixel array into the image.
rasterImg.SaveArgb32Pixels(img.Bounds, pixels);
}
}
// Save the updated image to disk.
if (rasterImg != null)
rasterImg.Save(dataDir + "ChangeBackgroundColor_out.jpg");
}
string dataDir = RunExamples.GetDataDir_PNG();
string sourceFile = @"test.png";
string outputFile = "result.png";
using (PngImage image = (PngImage)Image.Load(dataDir+sourceFile))
{
image.BinarizeBradley(10, 20);
image.Save(dataDir+outputFile);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PNG();
// Load an image from file (or stream)
using (Image image = Image.Load(dataDir + "aspose_logo.png"))
{
// Loop over possible CompressionLevel range
for (int i = 0; i <= 9; i++)
{
// Create an instance of PngOptions for each resultant PNG, Set CompressionLevel and Save result on disk
PngOptions options = new PngOptions();
options.CompressionLevel = i;
image.Save(i + "_out.png", options);
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PNG();
// Initialize variables to hold width & height values
int width = 0;
int height = 0;
// Initialize an array of type Color to hold the pixel data
Color[] pixels = null;
// Create an instance of RasterImage and load a BMP image
using (RasterImage raster = (RasterImage)Image.Load(dataDir + "aspose_logo.png"))
{
// Store the width & height in variables for later use
width = raster.Width;
height = raster.Height;
// Load the pixels of RasterImage into the array of type Color
pixels = raster.LoadPixels(new Rectangle(0, 0, width, height));
}
// Create & initialize an instance of PngImage while specifying size and PngColorType
using (PngImage png = new PngImage(width, height))
{
// Save the previously loaded pixels on to the new PngImage
png.SavePixels(new Rectangle(0, 0, width, height), pixels);
// Create an instance of PngOptions, Set the horizontal & vertical resolutions and Save the result on disc
PngOptions options = new PngOptions();
options.ResolutionSettings = new ResolutionSetting(72, 96);
png.Save(dataDir + "SettingResolution_output.png", options);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PNG();
// Load an existing PNG image
using (PngImage png = (PngImage)Image.Load(dataDir + "aspose_logo.png"))
{
// Create an instance of PngOptions, Set the desired ColorType, BitDepth according to the specified ColorType and save image
PngOptions options = new PngOptions();
options.ColorType = PngColorType.Grayscale;
options.BitDepth = 1;
png.Save(dataDir + "SpecifyBitDepth_out.jpg", options);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PNG();
// Initialize variables to hold width & height values
int width = 0;
int height = 0;
// Initialize an array of type Color to hold the pixel data
Color[] pixels = null;
// Create an instance of RasterImage and load a BMP image
using (RasterImage raster = (RasterImage)Image.Load(dataDir + "aspose_logo.png"))
{
// Store the width & height in variables for later use
width = raster.Width;
height = raster.Height;
// Load the pixels of RasterImage into the array of type Color
pixels = raster.LoadPixels(new Rectangle(0, 0, width, height));
}
// Create & initialize an instance of PngImage while specifying size and PngColorType
using (PngImage png = new PngImage(width, height, PngColorType.TruecolorWithAlpha))
{
// Save the previously loaded pixels on to the new PngImage and Set TransparentColor property to specify which color to be rendered as transparent
png.SavePixels(new Rectangle(0, 0, width, height), pixels);
png.TransparentColor = Color.Black;
png.HasTransparentColor = true;
png.Save(dataDir + "SpecifyTransparencyforPNGImages_out.jpg");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PNG();
// Initialize variables to hold width & height values
int width = 0;
int height = 0;
// Create an instance of RasterImage and load a BMP image
using (RasterImage image = (RasterImage)Image.Load(dataDir + "aspose_logo.png"))
{
// Store the width & height in variables for later use
width = image.Width;
height = image.Height;
// Set the background color, transparent, HasTransparentColor & HasBackgroundColor properties for the image
image.BackgroundColor = Color.White;
image.TransparentColor = Color.Black;
image.HasTransparentColor = true;
image.HasBackgroundColor = true;
image.Save(dataDir + "SpecifyTransparencyforPNGImagesUsingRasterImage_out.jpg", new PngOptions());
}
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
using (PngImage image = (PngImage)Image.Load(dataDir + "test.png"))
{
Aspose.Imaging.ImageOptions.PdfOptions exportOptions = new Aspose.Imaging.ImageOptions.PdfOptions();
exportOptions.PdfDocumentInfo = new Aspose.Imaging.FileFormats.Pdf.PdfDocumentInfo();
image.Save(dataDir + "test.pdf", exportOptions);
}
string dataDir = RunExamples.GetDataDir_PSD();
string fileName = string.Format("cmyk_{0}.tiff", isIccProfile);
string inputFile = Path.Combine(folder,"cmyk.psd");
string inputIccFile = Path.Combine(folder,"JapanWebCoated.icc");
string outputFile = Path.Combine(folder,fileName);
using (Image image = Image.Load(inputFile))
{
if (isIccProfile)
{
using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(inputIccFile)))
{
image.Save(outputFile, new TiffOptions(TiffExpectedFormat.TiffLzwCmyk) { IccProfile = ms });
}
}
else
{
image.Save(outputFile, new TiffOptions(TiffExpectedFormat.TiffLzwCmyk));
}
}
}
String path = "F:\\Aspose WPrk\\";
string dataDir = RunExamples.GetDataDir_PSD();
using (PsdImage image = (PsdImage)Image.Load(dataDir + "photooverlay_5_new_3.psd"))
{
PsdImage psdImage = image;
var pngOptions = new PngOptions();
foreach (var layer in psdImage.Layers)
{
if (layer.GetType() == typeof(Aspose.Imaging.FileFormats.Psd.Layers.TextLayer))
{
if (layer.Name == "dealerwebsite")
{
((Aspose.Imaging.FileFormats.Psd.Layers.TextLayer)layer).UpdateText("My new Text!", Color.Red);
}
}
else if (layer.Name == "Maincolor")
{
//layer.BackgroundColor = Color.Yellow;
//TODO: Change color of this layer
int dd = 0;
layer.HasBackgroundColor = true;
layer.BackgroundColor = Color.Orange;
// layer.BackgroundColor = Color.Yellow;
}
}
psdImage.Save(dataDir+"asposeImage02.png", new Aspose.Imaging.ImageOptions.PngOptions());
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PSD();
// Create an instance of PsdOptions and set it's properties
var createOptions = new PsdOptions();
createOptions.Source = new FileCreateSource(dataDir + "Newsample_out.psd", false);
createOptions.ColorMode = ColorModes.Indexed;
createOptions.Version = 5;
// Create a new color patelle having RGB colors, Set Palette property & compression method
Color[] palette = { Color.Red, Color.Green, Color.Blue };
createOptions.Palette = new PsdColorPalette(palette);
createOptions.CompressionMethod = CompressionMethod.RLE;
// Create a new PSD with PsdOptions created previously
using (var psd = Image.Create(createOptions, 500, 500))
{
// Draw some graphics over the newly created PSD
var graphics = new Graphics(psd);
graphics.Clear(Color.White);
graphics.DrawEllipse(new Pen(Color.Red, 6), new Rectangle(0, 0, 400, 400));
psd.Save(dataDir + "CreateIndexedPSDFiles_out.psd");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PSD();
// Load a PSD in an instance of PsdImage
using (PsdImage image = (PsdImage)Image.Load(dataDir + "sample.psd"))
{
// Iterate over the PSD resources
foreach (var resource in image.ImageResources)
{
// Check if the resource is of thumbnail type
if (resource is ThumbnailResource)
{
// Retrieve the ThumbnailResource and Check the format of the ThumbnailResource
var thumbnail = (ThumbnailResource)resource;
if (thumbnail.Format == ThumbnailFormat.KJpegRgb)
{
// Create a new BmpImage by specifying the width and height, Store the pixels of thumbnail on to the newly created BmpImage and save image
BmpImage thumnailImage = new BmpImage(thumbnail.Width, thumbnail.Height);
thumnailImage.SavePixels(thumnailImage.Bounds, thumbnail.ThumbnailData);
thumnailImage.Save(dataDir + "CreateThumbnailsFromPSDFiles_out.bmp");
}
}
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PSD();
// Load a PSD file
using (PsdImage image = (PsdImage)Image.Load(dataDir + "samplePsd.psd"))
{
// Do processing, Get the true value if PSD is flatten and false in case the PSD is not flatten.
Console.WriteLine(image.IsFlatten);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PSD();
// Create an instance of Image class and load PSD file as image.
using (Image image = Image.Load(dataDir + "samplePsd.psd"))
{
// Cast image object to PSD image
var psdImage = (PsdImage)image;
// Create an instance of PngOptions class
var pngOptions = new PngOptions();
pngOptions.ColorType = PngColorType.TruecolorWithAlpha;
// Loop through the list of layers
for (int i = 0; i < psdImage.Layers.Length; i++)
{
// Convert and save the layer to PNG file format.
psdImage.Layers[i].Save(string.Format("layer_out{0}.png", i + 1), pngOptions);
}
}
public static void Run()
{
string dataDir = RunExamples.GetDataDir_PSD();
string sourcePath = dataDir + "gray-d15.psd";
string outputPath = dataDir + "gray-d15.psd.ignore-icc.tif";
// Save to grayscale TIFF
TiffOptions saveOptions = new TiffOptions(TiffExpectedFormat.Default);
saveOptions.Photometric = TiffPhotometrics.MinIsBlack;
saveOptions.BitsPerSample = new ushort[] { 8 };
// Disable the ICC color conversion explicitly to get the original colors without applying a built-in ICC profile.
LoadOptions loadOptions = new LoadOptions();
loadOptions.UseIccProfileConversion = false;
// Or just omit loadOptions because the built-in Gray ICC profile is not applied by default in contrast of the CMYK profile.
using (PsdImage psdImage = (PsdImage)Image.Load(sourcePath))
{
// Embed the gray ICC profile to the output TIFF.
// The built-in Gray Profile can be read via the PsdImage.GrayColorProfile property.
saveOptions.IccProfile = ToMemoryStream(psdImage.GrayColorProfile);
psdImage.Save(outputPath, saveOptions);
}
}
private static MemoryStream ToMemoryStream(StreamSource streamSource)
{
Stream srcStream = streamSource.Stream;
MemoryStream dstStream = new MemoryStream();
int byteCount;
byte[] buffer = new byte[1024];
long pos = srcStream.Position;
srcStream.Seek(0, System.IO.SeekOrigin.Begin);
while ((byteCount = srcStream.Read(buffer, 0, buffer.Length)) > 0)
{
dstStream.Write(buffer, 0, byteCount);
}
srcStream.Seek(pos, System.IO.SeekOrigin.Begin);
return dstStream;
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PSD();
// Load a PSD in an instance of PsdImage
using (Image image = Image.Load(filePath))
{
// Cast image object to PSD image
PsdImage psdImage = (PsdImage)image;
// Create an instance of PngOptions class
PngOptions pngOptions = new PngOptions();
pngOptions.ColorType = PngColorType.TruecolorWithAlpha;
image.Save("result.png", pngOptions);
}
public static void Run()
{
//string dir = @"c:\aspose.work\IMAGINGNET\2990\";
string dataDir = RunExamples.GetDataDir_PSD();
string sourcePath = dataDir + "gray-d15.psd";
string outputPath = dataDir + "gray-d15.psd.apply-icc.tif";
// Save to grayscale TIFF
TiffOptions saveOptions = new TiffOptions(TiffExpectedFormat.Default);
saveOptions.Photometric = TiffPhotometrics.MinIsBlack;
saveOptions.BitsPerSample = new ushort[] { 8 };
// If the image contains a built-in Gray ICC profile, it is not be applied by default in contrast of the CMYK profile.
// Enable ICC conversion explicitly.
LoadOptions loadOptions = new LoadOptions();
loadOptions.UseIccProfileConversion = true;
using (PsdImage psdImage = (PsdImage)Image.Load(sourcePath, loadOptions))
{
// Embed the gray ICC profile to the output TIFF.
// The built-in Gray Profile can be read via the PsdImage.GrayColorProfile property.
saveOptions.IccProfile = ToMemoryStream(psdImage.GrayColorProfile);
psdImage.Save(outputPath, saveOptions);
}
}
private static MemoryStream ToMemoryStream(StreamSource streamSource)
{
Stream srcStream = streamSource.Stream;
MemoryStream dstStream = new MemoryStream();
int byteCount;
byte[] buffer = new byte[1024];
long pos = srcStream.Position;
srcStream.Seek(0, System.IO.SeekOrigin.Begin);
while ((byteCount = srcStream.Read(buffer, 0, buffer.Length)) > 0)
{
dstStream.Write(buffer, 0, byteCount);
}
srcStream.Seek(pos, System.IO.SeekOrigin.Begin);
return dstStream;
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PSD();
// Load a PSD file as an image and caste it into PsdImage
using (PsdImage image = (PsdImage)Image.Load(dataDir + "samplePsd.psd"))
{
//Extract a layer from PSDImage
Layer layer = image.Layers[1];
// Load the image that is needed to be imported into the PSD file.
using (RasterImage drawImage = (RasterImage)Image.Load(dataDir + "aspose_logo.png"))
{
// Call DrawImage method of the Layer class and pass the image instance.
layer.DrawImage(new Point(10, 10), drawImage);
}
// Save the results to output path.
image.Save(dataDir + "ImportImageToPSDLayer_out.psd", new PsdOptions());
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PSD();
string sourceFile = dataDir+"layerLock.psd";
string outputFile = dataDir+"result.psd";
//loading the file
using (PsdImage image = (PsdImage)Image.Load(sourceFile))
{
//Applying locks
Layer[] layers = image.Layers;
layers[4].LayerLock = LayerLockType.LockAll;
layers[2].LayerLock = LayerLockType.None;
layers[3].LayerLock = LayerLockType.LockTransparentPixels;
layers[1].LayerLock = LayerLockType.LockImagePixels;
layers[5].LayerLock = LayerLockType.LockPosition;
layers[5].Flags = LayerFlags.TransparencyProtected;
//Saving file
image.Save(outputFile);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PSD();
string sourceFileName = dataDir + "PsdImage.psd";
// Load an existing PSD file as image
using (Image image = Image.Load(sourceFileName))
{
// Convert the loaded image to PSDImage
var psdImage = (PsdImage)image;
// Create a JPG file stream
using (Stream stream = File.Create(sourceFileName.Replace("psd", "jpg")))
{
// Create JPEG option class object, Set the source property to jpg file stream and save image
var jpgOptions = new JpegOptions();
jpgOptions.Source = new StreamSource(stream);
psdImage.Save(stream, jpgOptions);
}
}
string dataDir = RunExamples.GetDataDir_PSD();
string sourceFileName = "FromRasterImageEthalon.psd";
string outputfile = "result.pdf";
//using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dataDir + "samplePsd.psd"));
using (Image image = Image.Load(dataDir+"sample.psd"))
{
PsdImage psdImage = (Aspose.Imaging.FileFormats.Psd.PsdImage)image;
//PsdImage psdImage = (Aspose.Imaging.FileFormats.Psd.PsdImage)image;
PdfOptions exportOptions = new PdfOptions();
exportOptions.PdfDocumentInfo = new Aspose.Imaging.FileFormats.Pdf.PdfDocumentInfo();
psdImage.Save(outputfile);
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PSD();
using (PsdImage image = Image.Load(dataDir+"smallCap.psd") as PsdImage)
{
image.Save(dataDir+"smallCap.png", new PngOptions() { ColorType = PngColorType.TruecolorWithAlpha });
}
string dataDir = RunExamples.GetDataDir_PSD();
string[] inputFiles = new string[]
{
"text",
"textReverse"
};
foreach (string inputFile in inputFiles)
{
string sourceFileName = "FromRasterImageEthalon.psd";
using (Image image = Image.Load(dataDir + "sample.psd"))
{
image.Save(inputFile + ".png", new PngOptions() { ColorType = PngColorType.TruecolorWithAlpha });
}
}
string sourceFileName = "dropShadow.psd";
string output = "dropShadow.png";
using (
PsdImage image =
(PsdImage)
Aspose.Imaging.Image.Load(
sourceFileName,
new Aspose.Imaging.ImageLoadOptions.PsdLoadOptions()
{
LoadEffectsResource = true,
UseDiskForLoadEffectsResource = true
}))
{
Debug.Assert(image.Layers[2] != null, "Layer with effects resource was not recognized");
image.Save(output, new Aspose.Imaging.ImageOptions.PngOptions()
{
ColorType =
Aspose.Imaging.FileFormats.Png
.PngColorType
.TruecolorWithAlpha
});
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PSD();
// Create an instance of MemoryStream to hold the uncompressed image data.
using (MemoryStream stream = new MemoryStream())
{
// First convert the image to raw PSD format.
using (PsdImage psdImage = (PsdImage)Image.Load(dataDir + "PsdImage.psd"))
{
PsdOptions saveOptions = new PsdOptions();
saveOptions.CompressionMethod = CompressionMethod.Raw;
psdImage.Save(dataDir + stream + "_out", saveOptions);
}
// Now reopen the newly created image.
using (PsdImage psdImage = (PsdImage)Image.Load(dataDir + stream + "_out"))
{
Graphics graphics = new Graphics(psdImage);
// Perform graphics operations.
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PSD();
// First convert the image to raw PSD format.
using (PsdImage psdImage = (PsdImage)Image.Load(dataDir + "PsdImage.psd"))
{
PsdOptions saveOptions = new PsdOptions();
saveOptions.CompressionMethod = CompressionMethod.Raw;
psdImage.Save(dataDir + "uncompressed_out.psd", saveOptions);
}
// Now reopen the newly created image.
using (PsdImage psdImage = (PsdImage)Image.Load(dataDir + "uncompressed_out.psd"))
{
Graphics graphics = new Graphics(psdImage);
// Perform graphics operations.
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PSD();
try
{
// Load a PSD file as an image and caste it into PsdImage
using (PsdImage image = (PsdImage)Image.Load(dataDir + "samplePsd.psd"))
{
PsdImage psdImage = image;
TextLayer textLayer1 = psdImage.Layers[1] as TextLayer;
TextLayer textLayer2 = psdImage.Layers[2] as TextLayer;
Debug.Assert(textLayer2 != null, "textLayer2 != null");
textLayer2.UpdateText("test update", new Point(100, 100), 72.0f, Color.Purple);
psdImage.Save(dataDir + "UpdateTextLayerInPSDFile_out.psd", new PsdOptions { CompressionMethod = CompressionMethod.RLE });
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx.");
}
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
string destFilePath = "transparent_orig.gif.pdf";
using (Image image = Image.Load(dataDir+ "transparent_orig.gif"))
{
image.Save(dataDir+destFilePath, new PdfOptions());
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Specify the size of image by defining a Rectangle
Rectangle rect = new Rectangle(0, 0, 100, 200);
TiffOptions tiffOptions = new TiffOptions(TiffExpectedFormat.TiffJpegRgb);
tiffOptions.Photometric = TiffPhotometrics.MinIsBlack;
tiffOptions.BitsPerSample = new ushort[] { 8 };
// Create the brand new image just for sample purposes
using (var image = new TiffImage(new TiffFrame(tiffOptions, rect.Width, rect.Height)))
{
// Create an instance of XMP-Header
XmpHeaderPi xmpHeader = new XmpHeaderPi(Guid.NewGuid().ToString());
// Create an instance of Xmp-TrailerPi, XMPmeta class to set different attributes
XmpTrailerPi xmpTrailer = new XmpTrailerPi(true);
XmpMeta xmpMeta = new XmpMeta();
xmpMeta.AddAttribute("Author", "Mr Smith");
xmpMeta.AddAttribute("Description", "The fake metadata value");
// Create an instance of XmpPacketWrapper that contains all metadata
XmpPacketWrapper xmpData = new XmpPacketWrapper(xmpHeader,xmpTrailer, xmpMeta);
// Create an instacne of Photoshop package and set photoshop attributes
PhotoshopPackage photoshopPackage = new PhotoshopPackage();
photoshopPackage.SetCity("London");
photoshopPackage.SetCountry("England");
photoshopPackage.SetColorMode(ColorMode.Rgb);
photoshopPackage.SetCreatedDate(DateTime.UtcNow);
// Add photoshop package into XMP metadata
xmpData.AddPackage(photoshopPackage);
// Create an instacne of DublinCore package and set dublinCore attributes
DublinCorePackage dublinCorePackage = new DublinCorePackage();
dublinCorePackage.SetAuthor("Charles Bukowski");
dublinCorePackage.SetTitle("Confessions of a Man Insane Enough to Live With the Beasts");
dublinCorePackage.AddValue("dc:movie", "Barfly");
// Add dublinCore Package into XMP metadata
xmpData.AddPackage(dublinCorePackage);
using (var ms = new MemoryStream())
{
// Update XMP metadata into image and Save image on the disk or in memory stream
image.XmpData = xmpData;
image.Save(ms);
ms.Seek(0, System.IO.SeekOrigin.Begin);
// Load the image from moemory stream or from disk to read/get the metadata
using (var img = (TiffImage)Image.Load(ms))
{
// Getting the XMP metadata
XmpPacketWrapper imgXmpData = img.XmpData;
foreach (XmpPackage package in imgXmpData.Packages)
{
// Use package data ...
}
}
}
}
}
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
//string dir = @"c:\aspose.work\IMAGINGNET\2934\";
string fileName = "16bit Uncompressed, BigEndian, Rgb, Contiguous Gamma1.0.tif";
// ICC profile is not applied for 16-bit color components at the moment, so disable that option explicitly.
LoadOptions loadOptions = new LoadOptions();
loadOptions.UseIccProfileConversion = false;
Rectangle desiredArea = new Rectangle(470, 1350, 30, 30);
using (RasterImage image = (RasterImage)Image.Load(dataDir + fileName, loadOptions))
{
long[] colors64Bit = image.LoadArgb64Pixels(image.Bounds);
ushort alpha, red, green, blue;
for (int y = desiredArea.Top; y < desiredArea.Bottom; ++y)
{
for (int x = desiredArea.Left; x < desiredArea.Right; ++x)
{
int offset = y * image.Width + x;
long color64 = colors64Bit[offset];
alpha = (ushort)((color64 >> 48) & 0xffff);
red = (ushort)((color64 >> 32) & 0xffff);
green = (ushort)((color64 >> 16) & 0xffff);
blue = (ushort)(color64 & 0xffff);
Console.WriteLine("A={0}, R={1}, G={2}, B={3}", alpha, red, green, blue);
}
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
using (Image image = Image.Load("testReplacementNotAvailableFonts.psd", new PsdLoadOptions() { DefaultReplacementFont = "Arial" }))
{
PsdImage psdImage = (PsdImage)image;
psdImage.Save("result.png", new PngOptions() { ColorType = PngColorType.TruecolorWithAlpha });
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load an image from disk
using (Image image = Image.Load(dataDir + "aspose-logo.jpg"))
{
if (!image.IsCached)
{
image.CacheData();
}
// Specifying only height, width and ResizeType
int newWidth = image.Width / 2;
image.ResizeWidthProportionally(newWidth, ResizeType.LanczosResample);
int newHeight = image.Height / 2;
image.ResizeHeightProportionally(newHeight, ResizeType.NearestNeighbourResample);
image.Save(dataDir + "ResizeImageWithResizeTypeEnumeration_out.png");
}
// Load an existing WMF image
using (Image image = Image.Load(dataDir + "input.wmf"))
{
// Call the resize method of Image class and width,height values and Calculate new PNG image height
image.Resize(100, 100);
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 = 100,
PageHeight = (int)Math.Round(100 / k),
BorderX = 5,
BorderY = 10
};
// 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 WMF file to PNG and save the output
image.Save(dataDir + "CreateEMFMetaFileImage_out.png", imageOptions);
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
using (Image image = Image.Load(dataDir + "aspose-logo.jpg"))
{
image.Resize(300, 300, ResizeType.LanczosResample);
image.Save(dataDir + "SimpleResizing_out.jpg");
}
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
string sourceFilePath = "testTileDeflate.tif";
string outputFilePath = "testTileDeflate Cmyk Icc.tif";
TiffOptions options = new TiffOptions(TiffExpectedFormat.TiffLzwCmyk);
using (Image image = Image.Load(sourceFilePath))
{
image.Save(outputFilePath, options);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load an image to be rotated in an instance of RasterImage
using (RasterImage image = (RasterImage)Image.Load(dataDir + "aspose-logo.jpg"))
{
// Before rotation, the image should be cached for better performance
if (!image.IsCached)
{
image.CacheData();
}
// Perform the rotation on 20 degree while keeping the image size proportional with red background color and Save the result to a new file
image.Rotate(20f, true, Color.Red);
image.Save(dataDir + "RotatingImageOnSpecificAngle_out.jpg");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Create an instance of TiffImage and load the file from disc
using (var multiImage = (TiffImage)Image.Load(dataDir + "SampleTiff1.tiff"))
{
// Initialize a variable to keep track of the frames in the image
int i = 0;
// Iterate over the tiff frame collection and Save the frame directly on disc in PNG format
foreach (var tiffFrame in multiImage.Frames)
{
tiffFrame.Save(dataDir + i + "_out.png", new PngOptions());
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// 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;
// Load an existing image in an instance of RasterImage
using (RasterImage image = (RasterImage)Image.Load(dataDir + "SampleTiff1.tiff"))
{
// Create a new TiffImage from the RasterImage and Save the resultant image while passing the instance of TiffOptions
using (TiffImage tiffImage = new TiffImage(new TiffFrame(image)))
{
tiffImage.Save(dataDir + "SavingRasterImage_out.tiff", options);
}
}
private const string FontFolderName = "fonts";
private const string OutFolderName = "Out";
private const string SourceFolder = @"D:\FontTests";
private static readonly string OutFolder = Path.Combine(SourceFolder, OutFolderName);
private static readonly string FontFolder = Path.Combine(OutFolder, FontFolderName);
#endregion
#region Methods
public void ReadFileWithEmbeddedFontsAndExportToPdf()
{
this.ReadAndExportToPdf("EmbeddedFonts.svg");
}
public void ReadFileWithExportedFontsAndExportToPdf()
{
this.ReadAndExportToPdf("ExportedFonts.svg");
}
public void SaveWithEmbeddedFonts()
{
string[] files = new string[3]
{
"exportedFonts.svg", // File with exported fonts
"embeddedFonts.svg", // File with embedded fonts
"mysvg.svg" // simple file
};
for (int i = 0; i < files.Length; i++)
{
this.Save(true, files[i], 0);
}
}
public void SaveWithExportFonts()
{
string[] files = new string[3]
{
"exportedFonts.svg", // File with exported fonts
"embeddedFonts.svg", // File with embedded fonts
"mysvg.svg" // simple file
};
int[] expectedFontsCount = new int[3] { 4, 4, 1 };
for (int i = 0; i < files.Length; i++)
{
this.Save(false, files[i], expectedFontsCount[i]);
}
}
private void ReadAndExportToPdf(string inputFileName)
{
if (!Directory.Exists(OutFolder))
{
Directory.CreateDirectory(OutFolder);
}
string inputFile = Path.Combine(SourceFolder, inputFileName);
string outFile = Path.Combine(OutFolder, inputFileName + ".pdf");
using (Image image = Image.Load(inputFile))
{
image.Save(outFile,
new PdfOptions { VectorRasterizationOptions = new SvgRasterizationOptions { PageSize = image.Size } });
}
}
private void Save(bool useEmbedded, string fileName, int expectedCountFonts)
{
if (!Directory.Exists(OutFolder))
{
Directory.CreateDirectory(OutFolder);
}
string fontStoreType = useEmbedded ? "Embedded" : "Stream";
string inputFile = Path.Combine(SourceFolder, fileName);
string outFileName = Path.GetFileNameWithoutExtension(fileName) + "_" + fontStoreType + ".svg";
string outputFile = Path.Combine(OutFolder, outFileName);
string fontFolder = string.Empty;
using (Image image = Image.Load(inputFile))
{
EmfRasterizationOptions emfRasterizationOptions = new EmfRasterizationOptions();
emfRasterizationOptions.BackgroundColor = Color.White;
emfRasterizationOptions.PageWidth = image.Width;
emfRasterizationOptions.PageHeight = image.Height;
string testingFileName = Path.GetFileNameWithoutExtension(inputFile);
fontFolder = Path.Combine(FontFolder, testingFileName);
image.Save(outputFile,
new SvgOptions
{
VectorRasterizationOptions = emfRasterizationOptions,
Callback =
new SvgCallbackFontTest(useEmbedded, fontFolder)
{
Link = FontFolderName + "/" + testingFileName
}
});
}
if (!useEmbedded)
{
string[] files = Directory.GetFiles(fontFolder);
if (files.Length != expectedCountFonts)
{
throw new Exception(string.Format(
"Expected count font files = {0}, Current count font files = {1}", expectedCountFonts,
files.Length));
}
}
}
#endregion
private class SvgCallbackFontTest : SvgResourceKeeperCallback
{
#region Fields
/// <summary>
/// The out folder
/// </summary>
private readonly string outFolder;
/// <summary>
/// The use embedded font
/// </summary>
private readonly bool useEmbeddedFont;
/// <summary>
/// The font counter
/// </summary>
private int fontCounter = 0;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="SvgTests.SvgCallbackFontTest" /> class.
/// </summary>
/// <param name="useEbeddedFont">if set to <c>true</c> [use ebedded font].</param>
/// <param name="outFolder">The out folder.</param>
public SvgCallbackFontTest(bool useEbeddedFont, string outFolder)
{
this.useEmbeddedFont = useEbeddedFont;
this.outFolder = outFolder;
if (Directory.Exists(outFolder))
{
Directory.Delete(this.outFolder, true);
}
}
#endregion
#region Properties
public string Link { get; set; }
#endregion
#region Methods
/// <summary>
/// Called when font resource ready to be saved to storage.
/// </summary>
/// <param name="args">The arguments.</param>
/// <returns>
/// Returns path to saved resource. Path should be relative to target SVG document.
/// </returns>
/// <exception cref="System.NotImplementedException"></exception>
public override void OnFontResourceReady(FontStoringArgs args)
{
if (this.useEmbeddedFont)
{
args.FontStoreType = FontStoreType.Embedded;
}
else
{
args.FontStoreType = FontStoreType.Stream;
string fontFolder = this.outFolder;
if (!Directory.Exists(fontFolder))
{
Directory.CreateDirectory(fontFolder);
}
string fName = args.SourceFontFileName;
if (!File.Exists(fName))
{
fName = string.Format("font_{0}.ttf", this.fontCounter++);
}
string fileName = fontFolder + @"\" + Path.GetFileName(fName);
args.DestFontStream = new FileStream(fileName, FileMode.OpenOrCreate);
args.DisposeStream = true;
args.FontFileUri = "./" + this.Link + "/" + Path.GetFileName(fName);
}
}
#endregion
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load an image from disk
using (Image image = Image.Load(dataDir + "aspose-logo.jpg"))
{
if (!image.IsCached)
{
image.CacheData();
}
// Specifying width and height
int newWidth = image.Width / 2;
image.ResizeWidthProportionally(newWidth);
int newHeight = image.Height / 2;
image.ResizeHeightProportionally(newHeight);
image.Save(dataDir + "SimpleResizeImageProportionally_out.png");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
using (Image image = Image.Load(dataDir + "aspose-logo.jpg"))
{
image.Resize(300, 300);
image.Save(dataDir + "SimpleResizing_out.jpg");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Create an instance of TiffImage and load the file from disc
using (var multiImage = (TiffImage)Image.Load(dataDir + "SampleTiff1.tiff"))
{
// Initialize a variable to keep track of the frames in the image, Iterate over the tiff frame collection and Save the image
int i = 0;
foreach (var tiffFrame in multiImage.Frames)
{
tiffFrame.Save(dataDir + i + "_out.tiff", new TiffOptions(TiffExpectedFormat.TiffJpegRgb));
}
}
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
string sourceFile = @"D:\source.bmp";
string resultFile = @"D:\result.png";
using (Image image = Image.Load(sourceFile))
{
image.Save(resultFile, new PngOptions());
}
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
using (EpsImage epsImage = Image.Load(dataDir+"anyEpsFile.eps") as EpsImage)
{
// check if EPS image has any raster preview to proceed (for now only raster preview is supported)
if (epsImage.HasRasterPreview)
{
if (epsImage.PhotoshopThumbnail != null)
{
// process Photoshop thumbnail if it's present
}
if (epsImage.EpsType == EpsType.Interchange)
{
// Get EPS Interchange subformat instance
EpsInterchangeImage epsInterchangeImage = epsImage as EpsInterchangeImage;
if (epsInterchangeImage.RasterPreview != null)
{
// process black-and-white Interchange raster preview if it's present
}
}
else
{
// Get EPS Binary subformat instance
EpsBinaryImage epsBinaryImage = epsImage as EpsBinaryImage;
if (epsBinaryImage.TiffPreview != null)
{
// process TIFF preview if it's present
}
if (epsBinaryImage.WmfPreview != null)
{
// process WMF preview if it's present
}
}
// export EPS image to PNG (by default, best available quality preview is used for export)
epsImage.Save(dataDir+"anyEpsFile.png", new PngOptions());
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
string[] files = new string[2] { "example.odg", "example1.odg" };
string folder = @"F:\\Aspose Work\\";
MetafileRasterizationOptions rasterizationOptions = new MetafileRasterizationOptions();
foreach (string file in files)
{
string fileName = Path.Combine(folder, file);
using (Image image = Image.Load(fileName))
{
rasterizationOptions.PageSize = image.Size;
string outFileName = fileName.Replace(".odg", ".png");
image.Save(outFileName,
new PngOptions
{
VectorRasterizationOptions = rasterizationOptions
});
outFileName = fileName.Replace(".odg", ".pdf");
image.Save(outFileName,
new PdfOptions
{
VectorRasterizationOptions = rasterizationOptions
});
}
}
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
string sourceFileName = "FromRasterImageEthalon.psd";
string outputfile = "result.tiff";
//Export png with alpha channel to tiff
using (Image image = Image.Load(dataDir + "Alpha.png"))
{
TiffOptions options = new TiffOptions(TiffExpectedFormat.TiffDeflateRgba);
image.Save(outputfile, options);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_SVG();
using (Image image = Image.Load(dataDir+"mysvg.svg"))
{
using (FileStream fs = new FileStream(dataDir+"yoursvg.svg", FileMode.Create, FileAccess.ReadWrite))
{
image.Save(fs);
}
}
string dataDir = RunExamples.GetDataDir_SVG();
string[] testFiles = new string[5]
{
"input.svg",
"juanmontoya_lingerie.svg",
"rg1024_green_grapes.svg",
"sample_car.svg",
"tommek_Car.svg"
};
string basePath =dataDir+ "Svg";
string outputPath = dataDir+Path.Combine(basePath, "output");
if (!Directory.Exists(outputPath))
{
Directory.CreateDirectory(outputPath);
}
foreach (string fileName in testFiles)
{
string inputFileName = Path.Combine(basePath, fileName);
string outputFileName = Path.Combine(outputPath, fileName + ".emf");
using (Image image = Image.Load(inputFileName))
{
image.Save(outputFileName,
new EmfOptions
{
VectorRasterizationOptions = new SvgRasterizationOptions
{
PageSize = image.Size
}
});
}
}
// Create an instance of Memory stream class.
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
// Create an instance of Stream container class and assign memory stream object.
using (StreamContainer streamContainer = new StreamContainer(memoryStream))
{
// check if the access to the stream source is synchronized.
lock (streamContainer.SyncRoot)
{
// do work
// now access to source MemoryStream is synchronized
}
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Create an instance of LoadOptions and set LoadOptions properties
LoadOptions loadOptions = new LoadOptions();
loadOptions.DataRecoveryMode = DataRecoveryMode.ConsistentRecover;
loadOptions.DataBackgroundColor = Color.Red;
// Create an instance of Image and load a damaged image by passing the instance of LoadOptions
using (Image image = Image.Load(dataDir + "SampleTiff1.tiff", loadOptions))
{
// Do some work
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load an image through file path location or stream
using (Image image = Image.Load(dataDir + "SampleTiff1.tiff"))
{
// Create an instance of TiffOptions while specifying desired format Passsing TiffExpectedFormat.TiffJpegRGB will set the compression to Jpeg and BitsPerPixel according to the RGB color space.
TiffOptions options = new TiffOptions(TiffExpectedFormat.TiffJpegRgb);
image.Save(dataDir + "SampleTiff_out.tiff", options);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WebPImages();
// Load GIFF image into the instance of image class.
using (Image image = Image.Load(dataDir + "asposelogo.gif"))
{
// Create an instance of GIFF image class.
GifImage gif = image as GifImage;
if (gif == null) return;
// Load an existing WebP image into the instance of WebPImage class.
using (WebPImage webp = new WebPImage(image.Width, image.Height, null))
{
// Loop through the GIFF frames
for (int i = 0; i < gif.Blocks.Length; i++)
{
// Convert GIFF block to GIFF Frame
GifFrameBlock gifBlock = gif.Blocks[i] as GifFrameBlock;
if (gifBlock == null)
{
continue;
}
// Create an instance of WebP Frame instance by passing GIFF frame to class constructor.
WebPFrameBlock block = new WebPFrameBlock(gifBlock)
{
Top = (short)gifBlock.Top,
Left = (short)gifBlock.Left,
Duration = (short)gifBlock.ControlBlock.DelayTime
};
// Add WebP frame to WebP image block list
webp.AddBlock(block);
}
// Set Properties of WebP image.
webp.Options.AnimBackgroundColor = 0xff; // Black
webp.Options.AnimLoopCount = 0; // Infinity
webp.Options.Quality = 50;
webp.Options.Lossless = false;
// Save WebP image.
webp.Save(dataDir + "ConvertGIFFImageFrame_out.webp");
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WebPImages();
// Create an instance of WebPOptions class and set properties
WebPOptions imageOptions = new WebPOptions();
imageOptions.Lossless = true;
imageOptions.Source = new FileCreateSource(dataDir + "CreatingWebPImage_out.webp", false);
// Create an instance of image class by using WebOptions instance that you have just created.
using (Image image = Image.Create(imageOptions, 500, 500))
{
image.Save();
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WebPImages();
// Create an instance of image class.
using (Image image = Image.Load(dataDir + "SampleImage1.bmp"))
{
// Create an instance of WebPOptions class and set properties
WebPOptions options = new WebPOptions();
options.Quality = 50;
options.Lossless = false;
image.Save(dataDir+ "ExportToWebP_out.webp", options);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WebPImages();
// Load WebP image into the instance of image class.
using (Image image = Image.Load(dataDir + "asposelogo.webp"))
{
// Save the image in WebP format.
image.Save(dataDir + "ExportWebPToOtherImageFormats_out.bmp", new BmpOptions());
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WebPImages();
// Load an existing WebP image into the instance of WebPImage class.
using (WebPImage image = new WebPImage(dataDir + "asposelogo.webp"))
{
if (image.Blocks.Length > 2)
{
// Access a particular frame from WebP image and cast it to Raster Image
RasterImage block = (image.Blocks[2] as RasterImage);
if (block != null)
{
// Save the Raster Image to a BMP image.
block.Save(dataDir + "ExtractFrameFromWebPImage.bmp", new BmpOptions());
}
}
}
@kashyap-msmhealth
Copy link

Missing i++ statement in loop for Examples-CSharp-ModifyingAndConvertingImages-SplittingTiffFrames-SplittingTiffFrames.cs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment