Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Aspose.Imaging for .NET
Gist for Aspose.Imaging for .NET.
class Deskew
{
public static void Run()
{
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
string fileName = "skewed.png";
string output = "skewed.out.png";
string inputFileName = Path.Combine(dataDir, fileName);
// Get rid of the skewed scan with default parameters
using (RasterImage image = (RasterImage)Image.Load(inputFileName))
{
image.NormalizeAngle(false /*do not resize*/, Color.LightGray /*background color*/);
image.Save(Path.Combine(dataDir, output));
}
}
}
using (var image = (TiffImage)Image.Load("Sample.tif"))
{
foreach (var path in image.ActiveFrame.PathResources)
{
Console.WriteLine(path.Name);
}
}
using (TiffImage tiffImage = (TiffImage)Image.Load("10MB_Tif.tif"))
{
// Set batch operation for pages
tiffImage.PageExportingAction = delegate(int index, Image page)
{
// Fires garbage collection to avoid unnecessary garbage storage from previous pages
GC.Collect();
((RasterImage)page).Rotate(90);
};
tiffImage.Save("rotated.webp", new WebPOptions());
/* Attention! In batch mode all pages will be released in this line!
If you want to further perform operations on the original image, you should reload it from the source to another instance. */
}
string inputFileName = "SimpleShapes.cdr";
using (Aspose.Imaging.FileFormats.Cdr.CdrImage image = (Aspose.Imaging.FileFormats.Cdr.CdrImage)Image.Load(inputFileName))
{
JpegOptions options = new JpegOptions();
// Set rasterization options for fileformat
options.VectorRasterizationOptions = (Aspose.Imaging.ImageOptions.VectorRasterizationOptions)image.GetDefaultOptions(new object[] { Color.White, image.Width, image.Height });
options.VectorRasterizationOptions.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
options.VectorRasterizationOptions.SmoothingMode = SmoothingMode.None;
image.Save("SimpleShapes.jpg", options);
}
string inputFileName = "SimpleShapes.cdr";
using (Aspose.Imaging.FileFormats.Cdr.CdrImage image = (Aspose.Imaging.FileFormats.Cdr.CdrImage)Image.Load(inputFileName))
{
PngOptions options = new Aspose.Imaging.ImageOptions.PngOptions();
options.ColorType = Aspose.Imaging.FileFormats.Png.PngColorType.TruecolorWithAlpha;
// Set rasterization options for fileformat
options.VectorRasterizationOptions = (Aspose.Imaging.ImageOptions.VectorRasterizationOptions)image.GetDefaultOptions(new object[] { Color.White, image.Width, image.Height });
options.VectorRasterizationOptions.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
options.VectorRasterizationOptions.SmoothingMode = SmoothingMode.None;
image.Save("SimpleShapes.png", options);
}
using (Aspose.Imaging.FileFormats.Cdr.CdrImage image = (Aspose.Imaging.FileFormats.Cdr.CdrImage)Image.Load(@"MultiPage.cdr"))
{
ImageOptionsBase options = new Aspose.Imaging.ImageOptions.PsdOptions();
// By default if image is multipage image all pages exported
options.MultiPageOptions = new Aspose.Imaging.ImageOptions.MultiPageOptions();
// Optional parameter that indicates to export multipage image as one
// layer (page) otherwise it will be exported page to page
options.MultiPageOptions.MergeLayers = true;
// Set rasterization options for fileformat
options.VectorRasterizationOptions = (Aspose.Imaging.ImageOptions.VectorRasterizationOptions)image.GetDefaultOptions(new object[] { Color.White, image.Width, image.Height });
options.VectorRasterizationOptions.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
options.VectorRasterizationOptions.SmoothingMode = SmoothingMode.None;
image.Save(@"MultiPage.psd", options);
}
using (Aspose.Imaging.FileFormats.Cmx.CmxImage image =
(Aspose.Imaging.FileFormats.Cmx.CmxImage)Image.Load("input.cmx"))
{
JpegOptions options = new JpegOptions();
// Set rasterization options for fileformat
options.VectorRasterizationOptions = (Aspose.Imaging.ImageOptions.VectorRasterizationOptions)image.GetDefaultOptions(new object[] { Color.White, image.Width, image.Height });
options.VectorRasterizationOptions.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
options.VectorRasterizationOptions.SmoothingMode = SmoothingMode.None;
image.Save("output.jpg", options);
}
using (Aspose.Imaging.FileFormats.Cmx.CmxImage image =
(Aspose.Imaging.FileFormats.Cmx.CmxImage)Image.Load("input.cmx"))
{
Aspose.Imaging.ImageOptions.PdfOptions options = new PdfOptions();
options.PdfDocumentInfo = new Aspose.Imaging.FileFormats.Pdf.PdfDocumentInfo();
// Set rasterization options for fileformat
options.VectorRasterizationOptions = (Aspose.Imaging.ImageOptions.VectorRasterizationOptions)image.GetDefaultOptions(new object[] { Color.White, image.Width, image.Height });
options.VectorRasterizationOptions.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
options.VectorRasterizationOptions.SmoothingMode = SmoothingMode.None;
image.Save("output.pdf", options);
}
// 1.Export compressed formats to raster
string[] files = new[] {"example.emz", "example.wmz", "example.svgz"};
string baseFolder = Path.Combine("D:","Compressed");
foreach (var file in files)
{
string inputFile = Path.Combine(baseFolder, file);
string outFile = inputFile + ".png";
using (Image image = Image.Load(inputFile))
{
VectorRasterizationOptions vectorRasterizationOptions = (VectorRasterizationOptions)image.GetDefaultOptions(new object[] { Color.White, image.Width, image.Height });
image.Save(outFile, new PngOptions(){VectorRasterizationOptions = vectorRasterizationOptions});
}
}
// 2.Export Emz to Emf
string file = "example.emz";
string baseFolder = Path.Combine("D:", "Compressed");
string inputFile = Path.Combine(baseFolder, file);
string outFile = inputFile + ".emf";
using (var image = Image.Load(inputFile))
{
VectorRasterizationOptions vectorRasterizationOptions = new EmfRasterizationOptions {PageSize = image.Size};
image.Save(outFile, new EmfOptions {VectorRasterizationOptions = vectorRasterizationOptions});
}
// 3.Export Wmz to Wmf
string file = "example.wmz";
string baseFolder = Path.Combine("D:", "Compressed");
string inputFile = Path.Combine(baseFolder, file);
string outFile = inputFile + ".wmf";
using (var image = Image.Load(inputFile))
{
VectorRasterizationOptions vectorRasterizationOptions = new WmfRasterizationOptions() { PageSize = image.Size};
image.Save(outFile, new WmfOptions() {VectorRasterizationOptions = vectorRasterizationOptions});
}
// 4.Export Svgz to Svg
string file = "example.svgz";
string baseFolder = Path.Combine("D:", "Compressed");
string inputFile = Path.Combine(baseFolder, file);
string outFile = inputFile + ".svg";
using (var image = Image.Load(inputFile))
{
VectorRasterizationOptions vectorRasterizationOptions = new SvgRasterizationOptions() { PageSize = image.Size};
image.Save(outFile, new SvgOptions() {VectorRasterizationOptions = vectorRasterizationOptions});
}
// 5.Export Emf to Emz
string file = "input.emf";
string baseFolder = Path.Combine("D:", "Compressed");
string inputFile = Path.Combine(baseFolder, file);
string outFile = inputFile + ".emz";
using (var image = Image.Load(inputFile))
{
VectorRasterizationOptions vectorRasterizationOptions = new EmfRasterizationOptions() { PageSize = image.Size};
image.Save(outFile, new EmfOptions() {VectorRasterizationOptions = vectorRasterizationOptions, Compress = true});
}
// 6.Export Wmf to Wmz
string file = "castle.wmf";
string baseFolder = Path.Combine("D:", "Compressed");
string inputFile = Path.Combine(baseFolder, file);
string outFile = inputFile + ".wmz";
using (var image = Image.Load(inputFile))
{
VectorRasterizationOptions vectorRasterizationOptions = new WmfRasterizationOptions() { PageSize = image.Size};
image.Save(outFile, new WmfOptions() {VectorRasterizationOptions = vectorRasterizationOptions, Compress = true});
}
// 7.Export Svg to Svgz
string file = "juanmontoya_lingerie.svg";
string baseFolder = Path.Combine("D:", "Compressed");
string inputFile = Path.Combine(baseFolder, file);
string outFile = inputFile + ".svgz";
using (var image = Image.Load(inputFile))
{
VectorRasterizationOptions vectorRasterizationOptions = new SvgRasterizationOptions() { PageSize = image.Size};
image.Save(outFile, new SvgOptions() {VectorRasterizationOptions = vectorRasterizationOptions, Compress = true});
}
public void ImagingNet3931Test()
{
string inputFilePath = "00020.png";
string outputFilePath = "00020_png.png";
ExportImage(inputFilePath, outputFilePath, FileFormat.Png, 0, null);
}
private static void ExportImage(
string sourceImageFilePath,
string outputImageFilePath,
Aspose.Imaging.FileFormat targetFormat,
float rotateAngle,
Aspose.Imaging.RotateFlipType? rotateFlipType)
{
using (RasterImage image = (RasterImage)Image.Load(
sourceImageFilePath,
new LoadOptions() { BufferSizeHint = 450 }))
{
if (!image.IsCached)
{
// !!! The caching call was in the customer example.
// We strongly recommend that you do not use caching in this case,
// since this leads to a noticeable decrease in performance in this case (in memory optimization strategy).
image.CacheData();
}
if (rotateAngle != 0)
{
image.Rotate(rotateAngle);
}
if (rotateFlipType != null)
{
image.RotateFlip(rotateFlipType.Value);
}
int bitsPerPixel = image.BitsPerPixel;
int bitDepth = bitsPerPixel == 1 ? 1 : bitsPerPixel < 8 ? 8 : 24;
ImageOptionsBase exportOptions;
switch (targetFormat)
{
case FileFormat.Jpeg:
if (bitDepth <= 8)
{
exportOptions = new JpegOptions()
{
Palette = ColorPaletteHelper.Create8BitGrayscale(true),
ColorType = JpegCompressionColorMode.Grayscale
};
}
else
{
exportOptions = new JpegOptions();
}
break;
case FileFormat.Png:
if (bitDepth <= 8)
{
exportOptions = new PngOptions()
{
Progressive = false,
ColorType = PngColorType.Grayscale,
BitDepth = (byte)bitDepth
};
}
else
{
exportOptions = new PngOptions()
{
Progressive = false
};
}
break;
case FileFormat.Tiff:
switch (bitDepth)
{
case 1:
exportOptions =
new TiffOptions(TiffExpectedFormat.Default)
{
Photometric = TiffPhotometrics.MinIsWhite,
Palette = ColorPaletteHelper.CreateMonochrome(),
Compression = TiffCompressions.CcittFax4,
BitsPerSample = new ushort[] {1}
};
break;
case 8:
exportOptions =
new TiffOptions(TiffExpectedFormat.Default)
{
Photometric = TiffPhotometrics.MinIsWhite,
Palette = ColorPaletteHelper.Create8BitGrayscale(true),
Compression = TiffCompressions.Deflate,
BitsPerSample = new ushort[] { 8 }
};
break;
default:
ushort bitsPerSample = (ushort)(bitDepth / 3);
exportOptions =
new TiffOptions(TiffExpectedFormat.Default)
{
Photometric = TiffPhotometrics.Rgb,
Compression = TiffCompressions.Jpeg,
BitsPerSample = new ushort[] { bitsPerSample, bitsPerSample, bitsPerSample }
};
break;
}
break;
default:
return;
}
exportOptions.BufferSizeHint = 2056;
exportOptions.ResolutionSettings = new ResolutionSetting(50, 50);
image.Save(outputImageFilePath, exportOptions);
}
}
using Aspose.Imaging;
using Aspose.Imaging.ImageOptions;
using Aspose.Imaging.FileFormats.Apng;
const int AnimationDuration = 1000; // 1 s
const int FrameDuration = 70; // 70 ms
using (RasterImage sourceImage = (RasterImage)Image.Load("not_animated.png"))
{
ApngOptions createOptions = new ApngOptions
{
Source = new FileCreateSource("raster_animation.png", false),
DefaultFrameTime = (uint)FrameDuration,
ColorType = PngColorType.TruecolorWithAlpha,
};
using (ApngImage apngImage = (ApngImage)Image.Create(
createOptions,
sourceImage.Width,
sourceImage.Height))
{
int numOfFrames = AnimationDuration / FrameDuration;
int numOfFrames2 = numOfFrames / 2;
apngImage.RemoveAllFrames();
// add first frame
apngImage.AddFrame(sourceImage, FrameDuration);
// add intermediate frames
for (int frameIndex = 1; frameIndex < numOfFrames - 1; ++frameIndex)
{
apngImage.AddFrame(sourceImage, FrameDuration);
ApngFrame lastFrame = (ApngFrame)apngImage.Pages[apngImage.PageCount - 1];
float gamma = frameIndex >= numOfFrames2 ? numOfFrames - frameIndex - 1 : frameIndex;
lastFrame.AdjustGamma(gamma);
}
// add last frame
apngImage.AddFrame(sourceImage, FrameDuration);
apngImage.Save();
}
}
using Aspose.Imaging;
using Aspose.Imaging.FileFormats.Apng;
// preparing the animation scene
const int SceneWidth = 400;
const int SceneHeigth = 400;
const uint ActDuration = 1000; // Act duration, in milliseconds
const uint TotalDuration = 4000; // Total duration, in milliseconds
const uint FrameDuration = 50; // Frame duration, in milliseconds
Scene scene = new Scene();
Ellipse ellipse = new Ellipse
{
FillColor = Color.FromArgb(128, 128, 128),
CenterPoint = new PointF(SceneWidth / 2f, SceneHeigth / 2f),
RadiusX = 80,
RadiusY = 80
};
scene.AddObject(ellipse);
Line line = new Line
{
Color = Color.Blue,
LineWidth = 10,
StartPoint = new PointF(30, 30),
EndPoint = new PointF(SceneWidth - 30, 30)
};
scene.AddObject(line);
IAnimation lineAnimation1 = new LinearAnimation(
delegate(float progress)
{
line.StartPoint = new PointF(
30 + (progress * (SceneWidth - 60)),
30 + (progress * (SceneHeigth - 60)));
line.Color = Color.FromArgb(
(int)(progress * 255),
0,
255 - (int)(progress * 255));
}) { Duration = ActDuration };
IAnimation lineAnimation2 = new LinearAnimation(
delegate(float progress)
{
line.EndPoint = new PointF(
SceneWidth - 30 - (progress * (SceneWidth - 60)),
30 + (progress * (SceneHeigth - 60)));
line.Color = Color.FromArgb(
255,
(int)(progress * 255),
0);
})
{ Duration = ActDuration };
IAnimation lineAnimation3 = new LinearAnimation(
delegate(float progress)
{
line.StartPoint = new PointF(
SceneWidth - 30 - (progress * (SceneWidth - 60)),
SceneHeigth - 30 - (progress * (SceneHeigth - 60)));
line.Color = Color.FromArgb(
255 - (int)(progress * 255),
255,
0);
})
{ Duration = ActDuration };
IAnimation lineAnimation4 = new LinearAnimation(
delegate(float progress)
{
line.EndPoint = new PointF(
30 + (progress * (SceneWidth - 60)),
SceneHeigth - 30 - (progress * (SceneHeigth - 60)));
line.Color = Color.FromArgb(
0,
255 - (int)(progress * 255),
(int)(progress * 255));
})
{ Duration = ActDuration };
IAnimation fullLineAnimation = new SequentialAnimation() { lineAnimation1, lineAnimation2, lineAnimation3, lineAnimation4 };
IAnimation ellipseAnimation1 = new LinearAnimation(
delegate(float progress)
{
ellipse.RadiusX += progress * 10;
ellipse.RadiusY += progress * 10;
int compValue = (int)(128 + (progress * 112));
ellipse.FillColor = Color.FromArgb(
compValue,
compValue,
compValue);
})
{ Duration = ActDuration };
IAnimation ellipseAnimation2 = new Delay() { Duration = ActDuration };
IAnimation ellipseAnimation3 = new LinearAnimation(
delegate(float progress)
{
ellipse.RadiusX -= progress * 10;
int compValue = (int)(240 - (progress * 224));
ellipse.FillColor = Color.FromArgb(
compValue,
compValue,
compValue);
})
{ Duration = ActDuration };
IAnimation ellipseAnimation4 = new LinearAnimation(
delegate(float progress)
{
ellipse.RadiusY -= progress * 10;
int compValue = (int)(16 + (progress * 112));
ellipse.FillColor = Color.FromArgb(
compValue,
compValue,
compValue);
})
{ Duration = ActDuration };
IAnimation fullEllipseAnimation = new SequentialAnimation() { ellipseAnimation1, ellipseAnimation2, ellipseAnimation3, ellipseAnimation4 };
scene.Animation = new ParallelAnimation() { fullLineAnimation, fullEllipseAnimation };
// playing the scene on the newly created ApngImage
ApngOptions createOptions = new ApngOptions
{
Source = new FileCreateSource("vector_animation.png", false),
ColorType = PngColorType.TruecolorWithAlpha,
};
using (ApngImage image = (ApngImage)Image.Create(createOptions, SceneWidth, SceneHeigth))
{
image.DefaultFrameTime = FrameDuration;
scene.Play(image, TotalDuration);
image.Save();
}
/////////////////////////// Scene.cs /////////////////////////////
using System.Collections.Generic;
using Aspose.Imaging.FileFormats.Apng;
using Graphics = Aspose.Imaging.Graphics;
// The graphics scene
public class Scene
{
private readonly List<IGraphicsObject> graphicsObjects = new List<IGraphicsObject>();
public IAnimation Animation { get; set; }
public void AddObject(IGraphicsObject graphicsObject)
{
this.graphicsObjects.Add(graphicsObject);
}
public void Play(ApngImage animationImage, uint totalDuration)
{
uint frameDuration = animationImage.DefaultFrameTime;
uint numFrames = totalDuration / frameDuration;
uint totalElapsed = 0;
for (uint frameIndex = 0; frameIndex < numFrames; frameIndex++)
{
if (this.Animation != null)
{
this.Animation.Update(totalElapsed);
}
ApngFrame frame = animationImage.PageCount == 0 || frameIndex > 0
? animationImage.AddFrame()
: (ApngFrame)animationImage.Pages[0];
Graphics graphics = new Graphics(frame);
graphics.SmoothingMode = SmoothingMode.AntiAlias;
foreach (IGraphicsObject graphicsObject in this.graphicsObjects)
{
graphicsObject.Render(graphics);
}
totalElapsed += frameDuration;
}
}
}
/////////////////////////// IGraphicsObject.cs /////////////////////////////
using Graphics = Aspose.Imaging.Graphics;
// The graphics object
public interface IGraphicsObject
{
void Render(Graphics graphics);
}
/////////////////////////// Line.cs /////////////////////////////
using Graphics = Aspose.Imaging.Graphics;
// The line
public class Line : IGraphicsObject
{
public PointF StartPoint { get; set; }
public PointF EndPoint { get; set; }
public float LineWidth { get; set; }
public Color Color { get; set; }
public void Render(Graphics graphics)
{
graphics.DrawLine(new Pen(this.Color, this.LineWidth), this.StartPoint, this.EndPoint);
}
}
/////////////////////////// Ellipse.cs /////////////////////////////
using Aspose.Imaging.Brushes;
using Graphics = Aspose.Imaging.Graphics;
// The ellipse
public class Ellipse : IGraphicsObject
{
public Color FillColor { get; set; }
public PointF CenterPoint { get; set; }
public float RadiusX { get; set; }
public float RadiusY { get; set; }
public void Render(Graphics graphics)
{
graphics.FillEllipse(
new SolidBrush(this.FillColor),
this.CenterPoint.X - this.RadiusX,
this.CenterPoint.Y - this.RadiusY,
this.RadiusX * 2,
this.RadiusY * 2);
}
}
/////////////////////////// IAnimation.cs /////////////////////////////
// The animation
public interface IAnimation
{
// The animation duration, in milliseconds.
uint Duration { get; set; }
void Update(uint elapsed);
}
/////////////////////////// LinearAnimation.cs /////////////////////////////
// The linear animation
public class LinearAnimation : IAnimation
{
private readonly AnimationProgressHandler progressHandler;
public delegate void AnimationProgressHandler(float progress);
public LinearAnimation(AnimationProgressHandler progressHandler)
{
if (progressHandler == null)
{
throw new System.ArgumentNullException("progressHandler");
}
this.progressHandler = progressHandler;
}
public uint Duration { get; set; }
public void Update(uint elapsed)
{
if (elapsed <= this.Duration)
{
this.progressHandler.Invoke((float)elapsed / this.Duration);
}
}
}
/////////////////////////// Delay.cs /////////////////////////////
// The simple delay between other animations
public class Delay : IAnimation
{
public uint Duration { get; set; }
public void Update(uint elapsed)
{
// nop
}
}
/////////////////////////// ParallelAnimation.cs /////////////////////////////
using System.Collections.Generic;
// The parallel animation processor
public class ParallelAnimation : List<IAnimation>, IAnimation
{
public uint Duration
{
get
{
uint maxDuration = 0;
foreach (IAnimation animation in this)
{
if (maxDuration < animation.Duration)
{
maxDuration = animation.Duration;
}
}
return maxDuration;
}
set
{
throw new System.NotSupportedException();
}
}
public void Update(uint elapsed)
{
foreach (IAnimation animation in this)
{
animation.Update(elapsed);
}
}
}
/////////////////////////// SequentialAnimation.cs /////////////////////////////
using System.Collections.Generic;
// The sequential animation processor
public class SequentialAnimation : List<IAnimation>, IAnimation
{
public uint Duration
{
get
{
uint summDuration = 0;
foreach (IAnimation animation in this)
{
summDuration += animation.Duration;
}
return summDuration;
}
set
{
throw new System.NotSupportedException();
}
}
public void Update(uint elapsed)
{
uint totalDuration = 0;
foreach (IAnimation animation in this)
{
if (totalDuration > elapsed)
{
break;
}
animation.Update(elapsed - totalDuration);
totalDuration += animation.Duration;
}
}
}
// Example 1. Creating an image and setting its pixels.
using System.Diagnostics;
using Aspose.Imaging;
using Aspose.Imaging.ImageOptions;
using Aspose.Imaging.FileFormats.Png;
using Aspose.Imaging.FileFormats.Apng;
// Load pixels from source raster image
Size imageSize;
int[] imagePixels;
using (RasterImage sourceImage = (RasterImage)Image.Load("not_animated.png"))
{
imageSize = sourceImage.Size;
imagePixels = sourceImage.LoadArgb32Pixels(sourceImage.Bounds);
}
// Create APNG image and set its pixels
using (ApngImage image = (ApngImage)Image.Create(
new ApngOptions()
{
Source = new FileCreateSource("created_apng.png", false),
ColorType = PngColorType.TruecolorWithAlpha
},
imageSize.Width,
imageSize.Height))
{
image.SaveArgb32Pixels(image.Bounds, imagePixels);
image.Save();
}
// Check output file format
using (Image image = Image.Load("created_apng.png")) {
Debug.Assert(image.FileFormat == FileFormat.Apng);
Debug.Assert(image is ApngImage);
}
static void Main()
{
using (var image = (TiffImage)Image.Load("Sample.tif"))
{
image.ActiveFrame.PathResources = new List<PathResource> { new PathResource
{
BlockId = 2000, // Block Id according to Photoshop specification
Name = "My Clipping Path", // Path name
Records = CreateRecords(0.2f, 0.2f, 0.8f, 0.2f, 0.8f, 0.8f, 0.2f, 0.8f) // Create path records using coordinates
}};
image.Save("ImageWithPath.tif");
}
}
private static List<VectorPathRecord> CreateRecords(params float[] coordinates)
{
var records = CreateBezierRecords(coordinates); // Create Bezier records using coordinates
records.Insert(0, new LengthRecord // LengthRecord required by Photoshop specification
{
IsOpen = false, // Lets create closed path
RecordCount = (ushort)records.Count // Record count in the path
});
return records;
}
private static List<VectorPathRecord> CreateBezierRecords(float[] coordinates)
{
return CoordinatesToPoints(coordinates)
.Select(CreateBezierRecord)
.ToList();
}
private static IEnumerable<PointF> CoordinatesToPoints(float[] coordinates)
{
for (var index = 0; index < coordinates.Length; index += 2)
yield return new PointF(coordinates[index], coordinates[index + 1]);
}
private static VectorPathRecord CreateBezierRecord(PointF point)
{
return new BezierKnotRecord { PathPoints = new[] { point, point, point } };
}
static void Main()
{
using (var image = (TiffImage)Image.Load(@"d:\Data\SampleNoPaths.tif"))
{
image.ActiveFrame.PathResources = new List<PathResource> { new PathResource
{
BlockId = 2000, // Block Id according to Photoshop specification
Name = "My Path", // Path name
Records = CreateRecords(LoadPathPoints(@"d:\Data\PathPoints.txt")) // Create path records using coordinates
}};
image.Save(@"d:\SampleWithPaths.tif");
}
}
private static float[] LoadPathPoints(string filePath)
{
return File.ReadAllText(filePath)
.Split(new[] { " ", "\r\n" }, StringSplitOptions.RemoveEmptyEntries)
.Select(float.Parse)
.ToArray();
}
private static List<VectorPathRecord> CreateRecords(params float[] coordinates)
{
var records = CreateBezierRecords(coordinates); // Create Bezier records using coordinates
records.Insert(0, new LengthRecord // LengthRecord required by Photoshop specification
{
IsOpen = false, // Lets create closed path
RecordCount = (ushort)records.Count // Record count in the path
});
return records;
}
private static List<VectorPathRecord> CreateBezierRecords(float[] coordinates)
{
return CoordinatesToPoints(coordinates)
.Select(CreateBezierRecord)
.ToList();
}
private static IEnumerable<PointF> CoordinatesToPoints(float[] coordinates)
{
for (var index = 0; index < coordinates.Length; index += 2)
yield return new PointF(coordinates[index], coordinates[index + 1]);
}
private static VectorPathRecord CreateBezierRecord(PointF point)
{
return new BezierKnotRecord { PathPoints = new[] { point, point, point } };
}
// Create an instance of CAD Metered class
Aspose.Imaging.Metered metered = new Aspose.Imaging.Metered();
// Access the setMeteredKey property and pass public and private keys as parameters
metered.SetMeteredKey("*****", "*****");
// Get metered data amount before calling API
decimal amountbefore = Aspose.Imaging.Metered.GetConsumptionQuantity();
// Display information
Console.WriteLine("Amount Consumed Before: " + amountbefore.ToString());
// Get metered data amount After calling API
decimal amountafter = Aspose.Imaging.Metered.GetConsumptionQuantity();
// Display information
Console.WriteLine("Amount Consumed After: " + amountafter.ToString());
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
// Create an instance of JpegOptions and set its various properties
JpegOptions imageOptions = new JpegOptions();
// Create an instance of FileCreateSource and assign it to Source property
imageOptions.Source = new FileCreateSource(dataDir + "Two_images_result_out.bmp", false);
// Create an instance of Image and define canvas size
using (var image = Image.Create(imageOptions, 600, 600))
{
// Create and initialize an instance of Graphics, Clear the image surface with white color and Draw Image
var graphics = new Graphics(image);
graphics.Clear(Color.White);
graphics.DrawImage(Image.Load(dataDir + "sample_1.bmp"), 0, 0, 600, 300);
graphics.DrawImage(Image.Load(dataDir + "File1.bmp"), 0, 300, 600, 300);
image.Save();
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
// Creates an instance of BmpOptions and set its various properties
BmpOptions ImageOptions = new BmpOptions();
ImageOptions.BitsPerPixel = 24;
// Define the source property for the instance of BmpOptions Second boolean parameter determines if the file is temporal or not
ImageOptions.Source = new FileCreateSource(dataDir + "CreatingAnImageBySettingPath_out.bmp", false);
// Creates an instance of Image and call Create method by passing the BmpOptions object
using (Image image = Image.Create(ImageOptions, 500, 500))
{
image.Save(dataDir + "CreatingAnImageBySettingPath1_out.bmp");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
// Creates an instance of BmpOptions and set its various properties
BmpOptions ImageOptions = new BmpOptions();
ImageOptions.BitsPerPixel = 24;
// Create an instance of System.IO.Stream
Stream stream = new FileStream(dataDir + "sample_out.bmp", FileMode.Create);
// Define the source property for the instance of BmpOptions Second boolean parameter determines if the Stream is disposed once get out of scope
ImageOptions.Source = new StreamSource(stream, true);
// Creates an instance of Image and call Create method by passing the BmpOptions object
using (Image image = Image.Create(ImageOptions, 500, 500))
{
// Do some image processing
image.Save(dataDir + "CreatingImageUsingStream_out.bmp");
}
// Creates an instance of FileStream
using (FileStream stream = new FileStream(dataDir + "DrawingArc_out.bmp", FileMode.Create))
{
// Create an instance of BmpOptions and set its various properties
BmpOptions saveOptions = new BmpOptions();
saveOptions.BitsPerPixel = 32;
// Set the Source for BmpOptions and create an instance of Image
saveOptions.Source = new StreamSource(stream);
using (Image image = Image.Create(saveOptions, 100, 100))
{
// Create and initialize an instance of Graphics class and clear Graphics surface
Graphics graphic = new Graphics(image);
graphic.Clear(Color.Yellow);
// Draw an arc shape by specifying the Pen object having red black color and coordinates, height, width, start & end angles
int width = 100;
int height = 200;
int startAngle = 45;
int sweepAngle = 270;
// Draw arc to screen and save all changes.
graphic.DrawArc(new Pen(Color.Black), 0, 0, width, height, startAngle, sweepAngle);
image.Save();
}
stream.Close();
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
// Creates an instance of FileStream
using (FileStream stream = new FileStream(dataDir + "DrawingBezier_out.bmp", FileMode.Create))
{
// Create an instance of BmpOptions and set its various properties
BmpOptions saveOptions = new BmpOptions();
saveOptions.BitsPerPixel = 32;
// Set the Source for BmpOptions and Create an instance of Image
saveOptions.Source = new StreamSource(stream);
using (Image image = Image.Create(saveOptions, 100, 100))
{
// Create and initialize an instance of Graphics class and clear Graphics surface
Graphics graphic = new Graphics(image);
graphic.Clear(Color.Yellow);
// Initializes the instance of PEN class with black color and width
Pen BlackPen = new Pen(Color.Black, 3);
float startX = 10;
float startY = 25;
float controlX1 = 20;
float controlY1 = 5;
float controlX2 = 55;
float controlY2 = 10;
float endX = 90;
float endY = 25;
// Draw a Bezier shape by specifying the Pen object having black color and co-ordinate Points and save all changes.
graphic.DrawBezier(BlackPen, startX, startY, controlX1, controlY1, controlX2, controlY2, endX, endY);
image.Save();
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
// Creates an instance of FileStream
using (FileStream stream = new FileStream(dataDir + "DrawingEllipse_out.bmp", FileMode.Create))
{
// Create an instance of BmpOptions and set its various properties
BmpOptions saveOptions = new BmpOptions();
saveOptions.BitsPerPixel = 32;
saveOptions.Source = new StreamSource(stream);
// Create an instance of Image
using (Image image = Image.Create(saveOptions, 100, 100))
{
// Create and initialize an instance of Graphics class and Clear Graphics surface
Graphics graphic = new Graphics(image);
graphic.Clear(Color.Yellow);
// Draw a dotted ellipse shape by specifying the Pen object having red color and a surrounding Rectangle
graphic.DrawEllipse(new Pen(Color.Red), new Rectangle(30, 10, 40, 80));
// Draw a continuous ellipse shape by specifying the Pen object having solid brush with blue color and a surrounding Rectangle
graphic.DrawEllipse(new Pen(new SolidBrush(Color.Blue)), new Rectangle(10, 30, 80, 40));
image.Save();
}
stream.Close();
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages() + "SolidLines_out.bmp";
// Creates an instance of FileStream
using (FileStream stream = new FileStream(dataDir, FileMode.Create))
{
// Create an instance of BmpOptions and set its various properties
BmpOptions saveOptions = new BmpOptions();
saveOptions.BitsPerPixel = 32;
saveOptions.Source = new StreamSource(stream);
// Create an instance of Image
using (Image image = Image.Create(saveOptions, 100, 100))
{
// Create and initialize an instance of Graphics class and Clear Graphics surface
Graphics graphic = new Graphics(image);
graphic.Clear(Color.Yellow);
// Draw two dotted diagonal lines by specifying the Pen object having blue color and co-ordinate Points
graphic.DrawLine(new Pen(Color.Blue), 9, 9, 90, 90);
graphic.DrawLine(new Pen(Color.Blue), 9, 90, 90, 9);
// Draw a four continuous line by specifying the Pen object having Solid Brush with red color and two point structures
graphic.DrawLine(new Pen(new SolidBrush(Color.Red)), new Point(9, 9), new Point(9, 90));
graphic.DrawLine(new Pen(new SolidBrush(Color.Aqua)), new Point(9, 90), new Point(90, 90));
graphic.DrawLine(new Pen(new SolidBrush(Color.Black)), new Point(90, 90), new Point(90, 9));
graphic.DrawLine(new Pen(new SolidBrush(Color.White)), new Point(90, 9), new Point(9, 9));
image.Save();
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages() + "SampleRectangle_out.bmp";
// Creates an instance of FileStream
using (FileStream stream = new FileStream(dataDir, FileMode.Create))
{
// Create an instance of BmpOptions and set its various properties
BmpOptions saveOptions = new BmpOptions();
saveOptions.BitsPerPixel = 32;
// Set the Source for BmpOptions and Create an instance of Image
saveOptions.Source = new StreamSource(stream);
using (Image image = Image.Create(saveOptions, 100, 100))
{
// Create and initialize an instance of Graphics class, Clear Graphics surface, Draw a rectangle shapes and save all changes.
Graphics graphic = new Graphics(image);
graphic.Clear(Color.Yellow);
graphic.DrawRectangle(new Pen(Color.Red), new Rectangle(30, 10, 40, 80));
graphic.DrawRectangle(new Pen(new SolidBrush(Color.Blue)), new Rectangle(10, 30, 80, 40));
image.Save();
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages() + "SampleImage_out.bmp";
// Create an instance of BmpOptions and set its various properties
BmpOptions imageOptions = new BmpOptions();
imageOptions.BitsPerPixel = 24;
// Create an instance of FileCreateSource and assign it to Source property
imageOptions.Source = new FileCreateSource(dataDir, false);
using (var image = Image.Create(imageOptions, 500, 500))
{
var graphics = new Graphics(image);
// Clear the image surface with white color and Create and initialize a Pen object with blue color
graphics.Clear(Color.White);
var pen = new Pen(Color.Blue);
// Draw Ellipse by defining the bounding rectangle of width 150 and height 100 also Draw a polygon using the LinearGradientBrush
graphics.DrawEllipse(pen, new Rectangle(10, 10, 150, 100));
using (var linearGradientBrush = new LinearGradientBrush(image.Bounds, Color.Red, Color.White, 45f))
{
graphics.FillPolygon(linearGradientBrush, new[] { new Point(200, 200), new Point(400, 200), new Point(250, 350) });
}
image.Save();
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
// Create an instance of BmpOptions and set its various properties
BmpOptions ImageOptions = new BmpOptions();
ImageOptions.BitsPerPixel = 24;
// Create an instance of FileCreateSource and assign it to Source property
ImageOptions.Source = new FileCreateSource(dataDir + "sample_1.bmp", false);
// Create an instance of Image and initialize an instance of Graphics
using (Image image = Image.Create(ImageOptions, 500, 500))
{
Graphics graphics = new Graphics(image);
graphics.Clear(Color.White);
// Create an instance of GraphicsPath and Instance of Figure, add EllipseShape, RectangleShape and TextShape to the figure
GraphicsPath graphicspath = new GraphicsPath();
Figure figure = new Figure();
figure.AddShape(new EllipseShape(new RectangleF(0, 0, 499, 499)));
figure.AddShape(new RectangleShape(new RectangleF(0, 0, 499, 499)));
figure.AddShape(new TextShape("Aspose.Imaging", new RectangleF(170, 225, 170, 100), new Font("Arial", 20), StringFormat.GenericTypographic));
graphicspath.AddFigures(new[] { figure });
graphics.DrawPath(new Pen(Color.Blue), graphicspath);
// Create an instance of HatchBrush and set its properties also Fill path by supplying the brush and GraphicsPath objects
HatchBrush hatchbrush = new HatchBrush();
hatchbrush.BackgroundColor = Color.Brown;
hatchbrush.ForegroundColor = Color.Blue;
hatchbrush.HatchStyle = HatchStyle.Vertical;
graphics.FillPath(hatchbrush, graphicspath);
image.Save();
Console.WriteLine("Processing completed successfully.");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
// Load the image to be drawn
using (RasterImage imageToDraw = (RasterImage)Image.Load(dataDir + "asposenet_220_src01.png"))
{
// Load the image for drawing on it (drawing surface)
using (EmfImage canvasImage = (EmfImage)Image.Load(dataDir + "input.emf"))
{
EmfRecorderGraphics2D graphics = EmfRecorderGraphics2D.FromEmfImage(canvasImage);
// Draw a rectagular part of the raster image within the specified bounds of the vector image (drawing surface).
// Note that because the source size is not equal to the destination one, the drawn image is stretched horizontally and vertically.
graphics.DrawImage(
imageToDraw,
new Rectangle(67, 67, canvasImage.Width, canvasImage.Height),
new Rectangle(0, 0, imageToDraw.Width, imageToDraw.Height),
GraphicsUnit.Pixel);
// Save the result image
using (EmfImage resultImage = graphics.EndRecording())
{
resultImage.Save(dataDir + "input.DrawImage.emf");
}
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
// Load the image to be drawn
using (RasterImage imageToDraw = (RasterImage)Image.Load(dataDir + "asposenet_220_src01.png"))
{
// Load the image for drawing on it (drawing surface)
using (SvgImage canvasImage = (SvgImage)Image.Load(dataDir + "asposenet_220_src02.svg"))
{
// Drawing on an existing Svg image.
Aspose.Imaging.FileFormats.Svg.Graphics.SvgGraphics2D graphics = new Aspose.Imaging.FileFormats.Svg.Graphics.SvgGraphics2D(canvasImage);
// Draw a rectagular part of the raster image within the specified bounds of the vector image (drawing surface).
// Note that because the source size is equal to the destination one, the drawn image is not stretched.
graphics.DrawImage(
new Rectangle(0, 0, imageToDraw.Width, imageToDraw.Height),
new Rectangle(67, 67, imageToDraw.Width, imageToDraw.Height),
imageToDraw);
// Save the result image
using (SvgImage resultImage = graphics.EndRecording())
{
resultImage.Save(dataDir + "asposenet_220_src02.DrawImage.svg");
}
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
// Load the image to be drawn
using (RasterImage imageToDraw = (RasterImage)Image.Load(dataDir + "asposenet_220_src01.png"))
{
// Load the image for drawing on it (drawing surface)
using (WmfImage canvasImage = (WmfImage)Image.Load(dataDir + "asposenet_222_wmf_200.wmf"))
{
WmfRecorderGraphics2D graphics = WmfRecorderGraphics2D.FromWmfImage(canvasImage);
// Draw a rectagular part of the raster image within the specified bounds of the vector image (drawing surface).
// Note that because the source size is not equal to the destination one, the drawn image is stretched horizontally and vertically.
graphics.DrawImage(
imageToDraw,
new Rectangle(67, 67, canvasImage.Width, canvasImage.Height),
new Rectangle(0, 0, imageToDraw.Width, imageToDraw.Height),
GraphicsUnit.Pixel);
// Save the result image
using (WmfImage resultImage = graphics.EndRecording())
{
resultImage.Save(dataDir + "asposenet_222_wmf_200.DrawImage.wmf");
}
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
using (MemoryStream drawnImageStream = new MemoryStream())
{
// First, rasterize Svg to Png and write the result to a stream.
using (SvgImage svgImage = (SvgImage)Image.Load(dataDir + "asposenet_220_src02.svg"))
{
SvgRasterizationOptions rasterizationOptions = new SvgRasterizationOptions();
rasterizationOptions.PageSize = svgImage.Size;
PngOptions saveOptions = new PngOptions();
saveOptions.VectorRasterizationOptions = rasterizationOptions;
svgImage.Save(drawnImageStream, saveOptions);
// Now load a Png image from stream for further drawing.
drawnImageStream.Seek(0, System.IO.SeekOrigin.Begin);
using (RasterImage imageToDraw = (RasterImage)Image.Load(drawnImageStream))
{
// Drawing on the existing Svg image.
Aspose.Imaging.FileFormats.Svg.Graphics.SvgGraphics2D graphics = new Aspose.Imaging.FileFormats.Svg.Graphics.SvgGraphics2D(svgImage);
// Scale down the entire drawn image by 2 times and draw it to the center of the drawing surface.
int width = imageToDraw.Width / 2;
int height = imageToDraw.Height / 2;
Point origin = new Point((svgImage.Width - width) / 2, (svgImage.Height - height) / 2);
Size size = new Size(width, height);
graphics.DrawImage(imageToDraw, origin, size);
// Save the result image
using (SvgImage resultImage = graphics.EndRecording())
{
resultImage.Save(dataDir + "asposenet_220_src02.DrawVectorImage.svg");
}
}
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
string filePath = "Flower.png"; // specify your path
using (PngImage image = (PngImage)Image.Load(filePath))
{
float opacity = image.ImageOpacity; // opacity = 0,470798
Console.WriteLine(opacity);
if (opacity == 0)
{
// The image is fully transparent.
}
}
}
string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();
ImageOptionsBase saveOptions = new PngOptions();
InterruptMonitor monitor = new InterruptMonitor();
SaveImageWorker worker = new SaveImageWorker(dataDir + "big.jpg", dataDir + "big_out.png", saveOptions, monitor);
Thread thread = new Thread(new ThreadStart(worker.ThreadProc));
try
{
thread.Start();
// The timeout should be less than the time required for full image conversion (without interruption).
Thread.Sleep(3000);
// Interrupt the process
monitor.Interrupt();
Console.WriteLine("Interrupting the save thread #{0} at {1}", thread.ManagedThreadId, System.DateTime.Now);
// Wait for interruption...
thread.Join();
}
finally
{
// If the file to be deleted does not exist, no exception is thrown.
File.Delete(dataDir + "big_out.png");
}
}
/// <summary>
/// Initiates image conversion and waits for its interruption.
/// </summary>
private class SaveImageWorker
{
/// <summary>
/// The path to the input image.
/// </summary>
private readonly string inputPath;
/// <summary>
/// The path to the output image.
/// </summary>
private readonly string outputPath;
/// <summary>
/// The interrupt monitor.
/// </summary>
private readonly InterruptMonitor monitor;
/// <summary>
/// The save options.
/// </summary>
private readonly ImageOptionsBase saveOptions;
/// <summary>
/// Initializes a new instance of the <see cref="SaveImageWorker" /> class.
/// </summary>
/// <param name="inputPath">The path to the input image.</param>
/// <param name="outputPath">The path to the output image.</param>
/// <param name="saveOptions">The save options.</param>
/// <param name="monitor">The interrupt monitor.</param>
public SaveImageWorker(string inputPath, string outputPath, ImageOptionsBase saveOptions, InterruptMonitor monitor)
{
this.inputPath = inputPath;
this.outputPath = outputPath;
this.saveOptions = saveOptions;
this.monitor = monitor;
}
/// <summary>
/// Tries to convert image from one format to another. Handles interruption.
/// </summary>
public void ThreadProc()
{
using (Image image = Image.Load(this.inputPath))
{
InterruptMonitor.ThreadLocalInstance = this.monitor;
try
{
image.Save(this.outputPath, this.saveOptions);
}
catch (OperationInterruptedException e)
{
Console.WriteLine("The save thread #{0} finishes at {1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now);
Console.WriteLine(e);
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
InterruptMonitor.ThreadLocalInstance = null;
}
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PSD();
using (Image image = Image.Load("testReplacementNotAvailableFonts.psd", new PsdLoadOptions() { DefaultReplacementFont = "Arial" }))
{
PsdImage psdImage = (PsdImage)image;
psdImage.Save(dataDir+"result.png", new PngOptions() { ColorType = PngColorType.TruecolorWithAlpha });
}
// Load an existing JPG image
using (Image image = Image.Load(dataDir + "SampleTiff1.tiff"))
{
// Declare a String object with Watermark Text
string theString = "45 Degree Rotated Text";
// Create and initialize an instance of Graphics class and Initialize an object of SizeF to store image Size
Graphics graphics = new Graphics(image);
SizeF sz = graphics.Image.Size;
// Creates an instance of Font, initialize it with Font Face, Size and Style
Font font = new Font("Times New Roman", 20, FontStyle.Bold);
// Create an instance of SolidBrush and set its various properties
SolidBrush brush = new SolidBrush();
brush.Color = Color.Red;
brush.Opacity = 0;
// Initialize an object of StringFormat class and set its various properties
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;
// Create an object of Matrix class for transformation
Matrix matrix = new Matrix();
// First a translation then a rotation
matrix.Translate(sz.Width / 2, sz.Height / 2);
matrix.Rotate(-45.0f);
// Set the Transformation through Matrix
graphics.Transform = matrix;
// Draw the string on Image Save output to disk
graphics.DrawString(theString, font, brush, 0, 0, format);
image.Save(dataDir + "AddDiagonalWatermarkToImage_out.jpg");
}
TiffOptions outputSettings = new TiffOptions(TiffExpectedFormat.Default);
outputSettings.BitsPerSample = new ushort[] { 1 };
outputSettings.Compression = TiffCompressions.CcittFax3;
outputSettings.Photometric = TiffPhotometrics.MinIsWhite;
outputSettings.Source = new StreamSource(new MemoryStream());
int newWidth = 500;
int newHeight = 500;
string path = dataDir + "AddFramesToTIFFImage_out.tif";
using (TiffImage tiffImage = (TiffImage)Image.Create(outputSettings, newWidth, newHeight))
{
int index = 0;
foreach (var file in Directory.GetFiles(dataDir, "*.jpg"))
{
using (RasterImage ri = (RasterImage)Image.Load(file))
{
ri.Resize(newWidth, newHeight, ResizeType.NearestNeighbourResample);
TiffFrame frame = tiffImage.ActiveFrame;
if (index > 0)
{
frame = new TiffFrame(new TiffOptions(outputSettings) /*ensure options are cloned for each frame*/,
newWidth, newHeight);
// If there is a TIFF image loaded you need to enumerate the frames and perform the following
// Frame = TiffFrame.CreateFrameFrom(sourceFrame, outputSettings);
}
frame.SavePixels(frame.Bounds, ri.LoadPixels(ri.Bounds));
if (index > 0)
{
tiffImage.AddFrame(frame);
}
index++;
}
}
tiffImage.Save(path);
}
// Create an instance of Image and load the primary image
using (Image canvas = Image.Load(dataDir + "SampleTiff1.tiff"))
{
// Create another instance of Image and load the secondary image containing the signature graphics
using (Image signature = Image.Load(dataDir + "signature.gif"))
{
// Create an instance of Graphics class and initialize it using the object of the primary image
Graphics graphics = new Graphics(canvas);
// Call the DrawImage method while passing the instance of secondary image and appropriate location. The following snippet tries to draw the secondary image at the right bottom of the primary image
graphics.DrawImage(signature, new Point(canvas.Height - signature.Height, canvas.Width - signature.Width));
canvas.Save(dataDir + "AddSignatureToImage_out.png", new PngOptions());
}
}
// Display Status.
Console.WriteLine("Watermark added successfully.");
// Load an image in an instance of Image
using (Image image__1 = Image.Load(dataDir + Convert.ToString("aspose-logo.jpg")))
{
// Cast object of Image to RasterImage
RasterImage rasterImage = (RasterImage)image__1;
// Check if RasterImage is cached and Cache RasterImage for better performance
if (!rasterImage.IsCached)
{
rasterImage.CacheData();
}
// Adjust the brightness
rasterImage.AdjustBrightness(70);
// Create an instance of TiffOptions for the resultant image, Set various properties for the object of TiffOptions and Save the resultant image
TiffOptions tiffOptions = new TiffOptions(TiffExpectedFormat.Default);
tiffOptions.BitsPerSample = new ushort[] {8,8,8};
tiffOptions.Photometric = TiffPhotometrics.Rgb;
rasterImage.Save(dataDir + Convert.ToString("AdjustBrightness_out.tiff"), tiffOptions);
}
// Load an image in an instance of Image
using (Image image = Image.Load(dataDir + "aspose-logo.jpg"))
{
// Cast object of Image to RasterImage
RasterImage rasterImage = (RasterImage)image;
// Check if RasterImage is cached and Cache RasterImage for better performance
if (!rasterImage.IsCached)
{
rasterImage.CacheData();
}
// Adjust the contrast
rasterImage.AdjustContrast(10);
// Create an instance of TiffOptions for the resultant image, Set various properties for the object of TiffOptions and Save the resultant image to TIFF format
TiffOptions tiffOptions = new TiffOptions(TiffExpectedFormat.Default);
tiffOptions.BitsPerSample = new ushort[] { 8, 8, 8 };
tiffOptions.Photometric = TiffPhotometrics.Rgb;
rasterImage.Save(dataDir + "AdjustContrast_out.tiff", tiffOptions);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load an image in an instance of Image
using (Image image = Image.Load(dataDir + "aspose-logo.jpg"))
{
// Cast object of Image to RasterImage
RasterImage rasterImage = (RasterImage)image;
// Check if RasterImage is cached and Cache RasterImage for better performance
if (!rasterImage.IsCached)
{
rasterImage.CacheData();
}
// Adjust the gamma
rasterImage.AdjustGamma(2.2f, 2.2f, 2.2f);
// Create an instance of TiffOptions for the resultant image, Set various properties for the object of TiffOptions and Save the resultant image to TIFF format
TiffOptions tiffOptions = new TiffOptions(TiffExpectedFormat.Default);
tiffOptions.BitsPerSample = new ushort[] { 8, 8, 8 };
tiffOptions.Photometric = TiffPhotometrics.Rgb;
rasterImage.Save(dataDir + "AdjustGamma_out.tiff", tiffOptions);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load an image and convert the image instance to TiffImage
using (TiffImage image = (TiffImage)Image.Load(dataDir + "SampleTiff1.tiff"))
{
// Call the align resolution method and Save the results to output path.
image.AlignResolutions();
image.Save(dataDir + "AlignHorizontalAndVeticalResolutionsOfImage_out.tiff");
int framesCount = image.Frames.Length;
for (int i = 0; i < framesCount; i++)
{
TiffFrame frame = image.Frames[i];
// All resolutions after aligment must be equal
Console.WriteLine("Horizontal and vertical resolutions are equal:" + ((int)frame.VerticalResolution == (int)frame.HorizontalResolution));
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load the image
using (Image image = Image.Load(dataDir + "asposelogo.gif"))
{
// Caste the image into RasterImage
RasterImage rasterImage = image as RasterImage;
if (rasterImage == null)
{
return;
}
// Create an instance of GaussWienerFilterOptions class and set the radius size and smooth value.
GaussWienerFilterOptions options = new GaussWienerFilterOptions(12, 3);
options.Grayscale = true;
// Apply MedianFilterOptions filter to RasterImage object and Save the resultant image
rasterImage.Filter(image.Bounds, options);
image.Save(dataDir + "ApplyGaussWienerFilter_out.gif");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load the image
using (Image image = Image.Load(dataDir + "asposelogo.gif"))
{
// Caste the image into RasterImage
RasterImage rasterImage = image as RasterImage;
if (rasterImage == null)
{
return;
}
// Create an instance of GaussWienerFilterOptions class and set the radius size and smooth value.
GaussWienerFilterOptions options = new GaussWienerFilterOptions(5, 1.5);
options.Brightness = 1;
// Apply MedianFilterOptions filter to RasterImage object and Save the resultant image
rasterImage.Filter(image.Bounds, options);
image.Save(dataDir + "ApplyGaussWienerFilter_out.gif");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load the image
using (Image image = Image.Load(dataDir + "asposelogo.gif"))
{
// Caste the image into RasterImage
RasterImage rasterImage = image as RasterImage;
if (rasterImage == null)
{
return;
}
// Create an instance of MotionWienerFilterOptions class and set the length, smooth value and angle.
MotionWienerFilterOptions options = new MotionWienerFilterOptions(50, 9, 90);
options.Grayscale = true;
// Apply MedianFilterOptions filter to RasterImage object and Save the resultant image
rasterImage.Filter(image.Bounds, options);
image.Save(dataDir + "ApplyingMotionWienerFilter_out.gif");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load the noisy image
using (Image image = Image.Load(dataDir + "asposelogo.gif"))
{
// Caste the image into RasterImage
RasterImage rasterImage = image as RasterImage;
if (rasterImage == null)
{
return;
}
// Create an instance of MedianFilterOptions class and set the size, Apply MedianFilterOptions filter to RasterImage object and Save the resultant image
MedianFilterOptions options = new MedianFilterOptions(4);
rasterImage.Filter(image.Bounds, options);
image.Save(dataDir + "median_test_denoise_out.gif");
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
string sourceFileName = dataDir + "Colored by Faith_small.png";
string inputPointsFileName = dataDir + "Colored by Faith_small.dat";
AutoMaskingArgs maskingArgs = new AutoMaskingArgs();
FillInputPoints(inputPointsFileName, maskingArgs);
string outputFileName = dataDir + "Colored by Faith_small_auto.png";
using (RasterImage image = (RasterImage)Image.Load(sourceFileName))
{
MaskingOptions maskingOptions = new MaskingOptions()
{
Method = SegmentationMethod.GraphCut,
Args = maskingArgs,
Decompose = false,
ExportOptions =
new PngOptions()
{
ColorType = PngColorType.TruecolorWithAlpha,
Source = new StreamSource(new MemoryStream())
},
};
MaskingResult[] maskingResults = new ImageMasking(image).Decompose(maskingOptions);
using (Image resultImage = maskingResults[1].GetImage())
{
resultImage.Save(outputFileName);
}
}
private static void FillInputPoints(string filePath, AutoMaskingArgs autoMaskingArgs)
{
BinaryFormatter serializer = new BinaryFormatter();
using (Stream stream = File.OpenRead(filePath))
{
bool hasObjectRectangles = (bool)serializer.Deserialize(stream);
bool hasObjectPoints = (bool)serializer.Deserialize(stream);
autoMaskingArgs.ObjectsRectangles = null;
autoMaskingArgs.ObjectsPoints = null;
if (hasObjectRectangles)
{
autoMaskingArgs.ObjectsRectangles = ((System.Drawing.Rectangle[])serializer.Deserialize(stream))
.Select(rect => new Aspose.Imaging.Rectangle(rect.X, rect.Y, rect.Width, rect.Height))
.ToArray();
}
if (hasObjectPoints)
{
autoMaskingArgs.ObjectsPoints = ((System.Drawing.Point[][])serializer.Deserialize(stream))
.Select(pointArray => pointArray
.Select(point => new Aspose.Imaging.Point(point.X, point.Y))
.ToArray())
.ToArray();
}
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load an image in an instance of Image
using (Image image = Image.Load(dataDir + "aspose-logo.jpg"))
{
// Cast the image to RasterCachedImage and Check if image is cached
RasterCachedImage rasterCachedImage = (RasterCachedImage)image;
if (!rasterCachedImage.IsCached)
{
// Cache image if not already cached
rasterCachedImage.CacheData();
}
// Binarize image with predefined fixed threshold and Save the resultant image
rasterCachedImage.BinarizeFixed(100);
rasterCachedImage.Save(dataDir + "BinarizationWithFixedThreshold_out.jpg");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load an image in an instance of Image
using (Image image = Image.Load(dataDir + "aspose-logo.jpg"))
{
// Cast the image to RasterCachedImage and Check if image is cached
RasterCachedImage rasterCachedImage = (RasterCachedImage)image;
if (!rasterCachedImage.IsCached)
{
// Cache image if not already cached
rasterCachedImage.CacheData();
}
// Binarize image with Otsu Thresholding and Save the resultant image
rasterCachedImage.BinarizeOtsu();
rasterCachedImage.Save(dataDir + "BinarizationWithOtsuThreshold_out.jpg");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load the image
using (Image image = Image.Load(dataDir + "asposelogo.gif"))
{
// Convert the image into RasterImage, Pass Bounds[rectangle] of image and GaussianBlurFilterOptions instance to Filter method and Save the results
RasterImage rasterImage = (RasterImage)image;
rasterImage.Filter(rasterImage.Bounds, new GaussianBlurFilterOptions(5, 5));
rasterImage.Save(dataDir + "BlurAnImage_out.gif");
}
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
using (BmpImage image = (BmpImage)Image.Load(dataDir))
{
Aspose.Imaging.ImageOptions.PdfOptions exportOptions = new PdfOptions();
exportOptions.PdfDocumentInfo = new Aspose.Imaging.FileFormats.Pdf.PdfDocumentInfo();
image.Save(dataDir, exportOptions);
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages() + "sample.bmp";
// Load an existing image.
using (var objimage = (BmpImage)Image.Load(dataDir))
{
// Define threshold value, Call BinarizeBradley method and pass the threshold value as parameter and Save the output image
double threshold = 0.15;
objimage.BinarizeBradley(threshold);
objimage.Save(dataDir + "binarized_out.png");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_CDR();
string inputFileName = dataDir + "test.cdr";
FileFormat expectedFileFormat = FileFormat.Cdr;
using (Image image = Image.Load(inputFileName))
{
if (expectedFileFormat != image.FileFormat)
{
throw new Exception("Image FileFormat is not {expectedFileFormat}");
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_CMX();
string[] fileNames = new string[] {
"Rectangle.cmx",
"Rectangle+Fill.cmx",
"Ellipse.cmx",
"Ellipse+fill.cmx",
"brushes.cmx",
"outlines.cmx",
"order.cmx",
"many_images.cmx",
};
foreach (string fileName in fileNames)
{
using (Image image = Image.Load(dataDir + fileName))
{
image.Save(
dataDir + fileName + ".docpage.png",
new PngOptions
{
VectorRasterizationOptions =
new CmxRasterizationOptions()
{
Positioning = PositioningTypes.DefinedByDocument,
SmoothingMode = SmoothingMode.AntiAlias
}
});
}
}
// Load an existing JPG image
using (JpegImage image = (JpegImage)Image.Load(dataDir + "aspose-logo_tn.jpg"))
{
StreamSource rgbprofile = new StreamSource(File.OpenRead(dataDir + "rgb.icc"));
StreamSource cmykprofile = new StreamSource(File.OpenRead(dataDir + "cmyk.icc"));
image.DestinationRgbColorProfile = rgbprofile;
image.DestinationCmykColorProfile = cmykprofile;
image.Save(dataDir + "ColorConversionUsingDefaultProfiles_out.icc");
}
// Load an existing JPG image
using (JpegImage image = (JpegImage)Image.Load(dataDir + "aspose-logo_tn.jpg"))
{
StreamSource rgbprofile = new StreamSource(File.OpenRead(dataDir + "rgb.icc"));
StreamSource cmykprofile = new StreamSource(File.OpenRead(dataDir + "cmyk.icc"));
image.RgbColorProfile = rgbprofile;
image.CmykColorProfile = cmykprofile;
Color[] colors = image.LoadPixels(new Rectangle(0, 0, image.Width, image.Height));
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load an image through file path location or stream
Image image = Image.Load(dataDir + "SampleTiff1.tiff");
// Create an instance of TiffOptions for the resultant image
TiffOptions outputSettings = new TiffOptions(TiffExpectedFormat.Default);
// Set BitsPerSample, Photometric mode & Compression mode
outputSettings.BitsPerSample = new ushort[] { 4 };
outputSettings.Compression = TiffCompressions.AdobeDeflate;
outputSettings.Photometric = TiffPhotometrics.Palette;
// Set graycale palette
outputSettings.Palette = ColorPaletteHelper.Create4BitGrayscale(false);
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Load an image through file path location or stream
Image image = Image.Load(dataDir + "SampleTiff.tiff");
// Create an instance of TiffOptions for the resultant image
TiffOptions outputSettings = new TiffOptions(TiffExpectedFormat.Default);
// Set BitsPerSample, Compression, Photometric mode and graycale palette
outputSettings.BitsPerSample = new ushort[] { 4 };
outputSettings.Compression = TiffCompressions.Lzw;
outputSettings.Photometric = TiffPhotometrics.Palette;
outputSettings.Palette = ColorPaletteHelper.Create4BitGrayscale(false);
image.Save(dataDir + "SampleTiff_out.tiff", outputSettings);
List<string> files = new List<string>(new[] { dataDir + "TestDemo.tiff", dataDir + "sample.tiff" });
TiffOptions createOptions = new TiffOptions(TiffExpectedFormat.Default);
createOptions.BitsPerSample = new ushort[] { 1 };
createOptions.Orientation = TiffOrientations.TopLeft;
createOptions.Photometric = TiffPhotometrics.MinIsBlack;
createOptions.Compression = TiffCompressions.CcittFax3;
createOptions.FillOrder = TiffFillOrders.Lsb2Msb;
// Create a new image by passing the TiffOptions and size of first frame, we will remove the first frame at the end, cause it will be empty
TiffImage output = null;
try
{
List<TiffImage> images = new List<TiffImage>();
try
{
foreach (var file in files)
{
// Create an instance of TiffImage and load the source image
TiffImage input = (TiffImage)Image.Load(file);
images.Add(input); // Do not dispose before data is fetched. Data is fetched on 'Save' later.
foreach (var frame in input.Frames)
{
if (output == null)
{
// Create a new tiff image with first frame defined.
output = new TiffImage(TiffFrame.CopyFrame(frame));
}
else
{
// Add copied frame to destination image
output.AddFrame(TiffFrame.CopyFrame(frame));
}
}
}
if (output != null)
{
// Save the result
output.Save(dataDir + "ConcatenateTiffImagesHavingSeveralFrames_out.tif", createOptions);
}
}
finally
{
foreach (TiffImage image in images)
{
image.Dispose();
}
}
}
catch (Exception ex)
{
}
// Create instances of FileStream and initialize with Tiff images
FileStream fileStream = new FileStream(dataDir + "TestDemo.tif", FileMode.Open);
FileStream fileStream1 = new FileStream(dataDir + "sample.tif", FileMode.Open);
// Create an instance of TiffImage and load the destination image from filestream
using (TiffImage image = (TiffImage) Image.Load(fileStream))
{
// Create an instance of TiffImage and load the source image from filestream
using (TiffImage image1 = (TiffImage) Image.Load(fileStream1))
{
// Create an instance of TIffFrame and copy active frame of source image
TiffFrame frame = TiffFrame.CopyFrame(image1.ActiveFrame);
// Add copied frame to destination image
image.AddFrame(frame);
}
// Save the image with changes
image.Save(dataDir + "ConcatenatingTIFFImagesfromStream_out.tif");
// Close the FileStreams
fileStream.Close();
fileStream1.Close();
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();
// Create a copy of original image to avoid any alteration
File.Copy(dataDir + "demo.tif", dataDir + "TestDemo.tif", true);
// Create an instance of TiffImage and load the copied destination image
using (TiffImage image = (TiffImage)Image.Load(dataDir + "TestDemo.tif"))
{
// Create an instance of TiffImage and load the source image
using (TiffImage image1 = (TiffImage)Image.Load(dataDir + "sample.tif"))
{
// Create an instance of TIffFrame and copy active frame of source image, Add copied frame to destination image and Save the image with changes.
TiffFrame frame = TiffFrame.CopyFrame(image1.ActiveFrame);
image.AddFrame(frame);
image.Save(dataDir + "ConcatTIFFImages_out.tiff");
}