ImageTask Class

Provides methods for processing a source image in a chained manner and saving the resulting image(s). This class also allows reading source image information and metadata. ImageInfo class can be preferred to this class if no processing is required.

Definition

Namespace: GleamTech.ImageUltimate
Assembly: GleamTech.ImageUltimate (in GleamTech.ImageUltimate.dll) Version: 5.8.7
C#
public sealed class ImageTask : ImageTaskBase<ImageTask>, 
	IDisposable
Inheritance
Object    ImageTaskBaseImageTask    ImageTask
Implements
IDisposable

Example

C#
//Convert "c:\SomeFolder\InputFile.png" to "c:\SomeFolder\OutputFile.jpg"
using (var imageTask = new ImageTask(@"c:\SomeFolder\InputFile.png"))
    imageTask.Save(@"c:\SomeFolder\OutputFile.jpg");

//---------------------------------------

//Convert with a virtual path string:
//See below for other path string examples.
using (var imageTask = new ImageTask("~/SomeFolder/InputFile.png"))
    imageTask.Save(@"c:\SomeFolder\OutputFile.jpg");

//Convert with a URL string:
//See below for other path string examples.
using (var imageTask = new ImageTask("http://example.com/SomeFolder/InputFile.png"))
    imageTask.Save(@"c:\SomeFolder\OutputFile.jpg");

//Convert with a Data URL string:
//See below for other path string examples.
using (var imageTask = new ImageTask("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"))
    imageTask.Save(@"c:\SomeFolder\OutputFile.jpg");

//Convert with a file provider instance:
//See below for other file provider examples (UNC Path, AmazonS3, AzureBlob, Database etc.).
var fileProvider = new FileSystemFileProvider
{
    File = "InputFile.png",
    Location = new PhysicalLocation
    {
        Path = @"c:\SomeFolder"
    }
};
using (var imageTask = new ImageTask(fileProvider))
    imageTask.Save(@"c:\SomeFolder\OutputFile.jpg");

//Convert with a provider string:
//See below for other provider string examples (UNC Path, AmazonS3, AzureBlob, Database etc.).
using (var imageTask = new ImageTask(@"Type=FileSystem; File=InputFile.png; Location='Type=Physical; Path=c:\SomeFolder'"))
    imageTask.Save(@"c:\SomeFolder\OutputFile.jpg");

C#
//Get EXIF thumbnail if exists or resize:
using (var imageTask = new ImageTask(@"C:\Input\Picture1.jpg"))
    imageTask.Thumbnail(160).Save(@"C:\Output\Thumbnail1.jpg");

//Just resize:
using (var imageTask = new ImageTask(@"C:\Input\Picture1.jpg"))
    imageTask.ResizeWidth(200).Save(@"C:\Output\Picture2.jpg");

C#
//Using Undo for multiple outputs:
using (var imageTask = new ImageTask(@"C:\Input\Picture1.jpg", enableUndo: true))
    imageTask.ResizeWidth(200).Save(@"C:\Output\Picture2.jpg")
        .Undo().ResizeHeight(400).Rotate(90).Save(@"C:\Output\Picture3.png")
        .UndoAll().Save(outputStream, ImageFormat.Png);

C#
//Modifying EXIF metadata:
using (var imageTask = new ImageTask(@"C:\Input\Picture1.jpg"))
{
    imageTask.Info.ExifDictionary.Remove(ExifTag.Image.Software);
    imageTask.Info.ExifDictionary.Set(ExifTag.Image.Artist, "UPDATED Artist TAG");

    imageTask.Info.IptcDictionary.Remove(IptcTag.Application2.Byline);
    imageTask.Info.IptcDictionary.Set(IptcTag.Application2.ObjectName, "UPDATED ObjectName TAG");

    imageTask.Save(@"C:\Output\Picture2.jpg");
}

  Notes to Callers

Below are the examples for setting a FileProvider parameter/property.

Setting a plain string:

C#
FileProvider fileProvider;

//Setting a physical/virtual path string:
//These strings are parsed as a FileSystemFileProvider instance with a PhysicalLocation instance.
fileProvider = @"c:\SomeFolder\SomeFile.ext";
//Note that virtual paths can only be resolved in a web application
//and on Linux paths starting with "/" are physical paths and not virtual paths.
fileProvider = "/SomeFolder/SomeFile.ext";
fileProvider = "~/SomeFolder/SomeFile.ext"; //"~" means relative to web application root.

//Setting a URL or a Data URL string:
//Strings starting with "http://" or "https://" are parsed as a UrlFileProvider instance.
//Strings starting with "data:" are parsed as a DataUrlFileProvider instance.
fileProvider = "http://example.com/SomeFolder/SomeFile.ext";
fileProvider = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";

Setting a MemoryFileProvider instance, to connect to a file in a byte array (byte) or a MemoryStream:

C#
FileProvider fileProvider;

//Setting a MemoryFileProvider instance,
//to connect to a file in a byte array (byte[]) or a MemoryStream:
//Optional parameter dateModified: used for detailed file info, e.g. for generating better cache keys.
fileProvider = new MemoryFileProvider(
    "SomeFile.ext", //file can also be set as a relative path "SomeFolder/SomeFile.ext".
    yourByteArray,
    yourFileDateModified //Provide dateModified to prevent cache key conflicts.
);
fileProvider = new MemoryFileProvider(
    "SomeFile.ext", //file can also be set as a relative path "SomeFolder/SomeFile.ext".
    yourMemoryStream,
    yourFileDateModified //Provide dateModified to prevent cache key conflicts.
);

//Create with empty MemoryStream
//Note that this instance should be written (filled with data via OpenWrite method) before being read
fileProvider = new MemoryFileProvider("SomeFolder/SomeFile.ext");

Setting a StreamFileProvider instance, to connect to a file in a Stream:

C#
FileProvider fileProvider;

//Setting a StreamFileProvider instance,
//to connect to a file in a Stream:
//Optional parameters dateModified and size: used for detailed file info, e.g. for generating better cache keys.
fileProvider = new StreamFileProvider(
    "SomeFile.ext", //file can also be set as a relative path "SomeFolder/SomeFile.ext".
    yourStream,
    yourFileDateModified, //Provide dateModified to prevent cache key conflicts.
    yourFileSize //Provide size only if your stream is not seekable to prevent cache key conflicts.
);

Setting a FileSystemFileProvider instance with a PhysicalLocation instance, to connect to physical file system:

C#
FileProvider fileProvider;

//Setting a physical file provider via a FileSystemFileProvider instance:
fileProvider = new FileSystemFileProvider
{
    File = "SomeFile.ext",
    Location = new PhysicalLocation
    {
        //Path can also be virtual path string like "~/SomeFolder" in a web application.
        Path = @"c:\SomeFolder"
    }
};

//Setting a physical file provider via a provider string (same as above):
//In a provider string, if a value contains semi-colon character, that value should be enclosed
//in single quotes (eg. Password='PASS;WORD') or double quotes (eg. Password="PASS;WORD").
fileProvider = @"Type=FileSystem; File=SomeFile.ext; Location='Type=Physical; Path=c:\SomeFolder'";

//---------------------------------------

//Setting a FileSystemFileProvider instance with a PhysicalLocation instance,
//to connect as a specific Windows user to a UNC path or a protected local path:
//UserName can be specified as "Domain\User", "User@Domain" (UPN format), "Machine\User", "User" (local user).
fileProvider = new FileSystemFileProvider
{
    File = "SomeFile.ext",
    Location = new PhysicalLocation
    {
        Path = @"\\server\share", //Path can be a UNC path or a local path
        UserName = "USERNAME",
        Password = "PASSWORD"
    }
};

//Setting a physical file provider via a provider string, to connect as a specific user (same as above):
//In a provider string, if a value contains semi-colon character, that value should be enclosed
//in single quotes (eg. Password='PASS;WORD') or double quotes (eg. Password="PASS;WORD").
fileProvider = @"Type=FileSystem; File=SomeFile.ext; Location='Path=\\server\share; User Name=USERNAME; Password=PASSWORD'";

//---------------------------------------

//Setting a physical file provider via a FileSystemFileProvider instance, to connect as the authenticated user:
//If Windows Authentication is used in IIS for this site, location can be specified like this
//to connect as the already authenticated user: 
fileProvider = new FileSystemFileProvider
{
    File = "SomeFile.ext",
    Location = new PhysicalLocation
    {
        Path = @"\\server\share", //Path can be a UNC path or a local path
        AuthenticatedUser = AuthenticatedUser.Windows
    }
};

//Setting a physical file provider via a provider string, to connect as the authenticated user:
fileProvider = @"Type=FileSystem; File=SomeFile.ext; Location='Path=\\server\share; Authenticated User=Windows'";

Setting a FileSystemFileProvider instance with an AzureBlobLocation instance, to connect to Azure Blob cloud file system:

C#
FileProvider fileProvider;

//Setting a FileSystemFileProvider instance with an AzureBlobLocation instance,
//to connect to Azure Blob cloud file system.
fileProvider = new FileSystemFileProvider
{
    File = "SomeFile.ext",
    Location = new AzureBlobLocation
    {
        //Leave Path empty to connect to the root of the container. 
        //For connecting to subfolders, Path should be specified as a relative path (eg. "some/folder")
        //Path = "some/folder",

        //Get these values from your Azure Portal (Storage Account -> Access Keys -> Connection String)
        Container = "CONTAINER",
        AccountName = "XXX",
        AccountKey = "XXX"
    }
};

//Setting a an Azure Blob file provider via a provider string (same as above):
//In a provider string, if a value contains semi-colon character, that value should be enclosed
//in single quotes (eg. Password='PASS;WORD') or double quotes (eg. Password="PASS;WORD").
fileProvider = @"Type=FileSystem; File=SomeFile.ext; Location='Type=AzureBlob; Container=CONTAINER; Account Name=XXX; Account Key=XXX'";

Setting a FileSystemFileProvider instance with an AmazonS3Location instance, to connect to Amazon S3 cloud file system:

C#
FileProvider fileProvider;

//Setting a FileSystemFileProvider instance with an AmazonS3Location instance,
//to connect to Amazon S3 cloud file system.
fileProvider = new FileSystemFileProvider
{
    File = "SomeFile.ext",
    Location = new AmazonS3Location
    {
        //Leave Path empty to connect to the root of the bucket. 
        //For connecting to subfolders, Path should be specified as a relative path (eg. "some/folder")
        //Path = "some/folder",

        BucketName = "BUCKET",
        Region = "eu-central-1",
        AccessKeyId = "XXX",
        SecretAccessKey = "XXX",
    }
};

//Setting an Amazon S3 file provider via a provider string (same as above):
//In a provider string, if a value contains semi-colon character, that value should be enclosed
//in single quotes (eg. Password='PASS;WORD') or double quotes (eg. Password="PASS;WORD").
fileProvider = @"Type=FileSystem; File=SomeFile.ext; Location='Type=AmazonS3; Bucket Name=BUCKET; Region=eu-central-1; Access Key Id=XXX; Secret Access Key=XXX'";

Setting a UrlFileProvider instance, to connect to a file located at a URL:

C#
FileProvider fileProvider;

//Setting a URL file provider via a UrlFileProvider instance:
//File should start with "http://" or "https://".
fileProvider = new UrlFileProvider
{
    File = "http://example.com/SomeFolder/SomeFile.ext"
};

//Setting a URL file provider via a provider string (same as above):
fileProvider = "Type=Url; File=http://example.com/SomeFolder/SomeFile.ext";

Setting a DataUrlFileProvider instance, to connect to a file encoded in a Data URL:

C#
FileProvider fileProvider;

//Setting a Data URL file provider via a UrlFileProvider instance:
//File should start with "data:".
fileProvider = new DataUrlFileProvider
{
    File = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
};

//Setting a Data URL file provider via a provider string (same as above):
fileProvider = "Type=DataUrl; File='data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'";

Setting a DatabaseFileProvider instance, to connect to a database file system:

C#
FileProvider fileProvider;

//Setting a DatabaseFileProvider instance,
//to connect to a database file system.
fileProvider = new DatabaseFileProvider
{
    File = "SomeFile.ext", //File can also be set as a relative path "SomeFolder/SomeFile.ext".
    ConnectionString = "Data Source=(local); Initial Catalog=SomeDb; Integrated Security=SSPI",
    //ProviderName = "System.Data.SqlClient" //ProviderName default value is "System.Data.SqlClient"

    Table = "SomeTable", //Table default value is "File".

    //Mandatory fields:
    KeyField = "Path", //KeyField default value is "Id".
    ContentField = "Content", //ContentField default value is "Content".

    //Optional fields DateModifiedField and SizeField: used for detailed file info, e.g. for generating better cache keys.
    //NameField = "Name", //NameField used for overriding file name specified in File.
    DateModifiedField = "DateModified", //Provide DateModifiedField to prevent cache key conflicts.
    SizeField = "Size" //Provide SizeField to prevent cache key conflicts.
};

//Setting a database file provider via a provider string (same as above):
//In a provider string, if a value contains semi-colon character, that value should be enclosed
//in single quotes (eg. Password='PASS;WORD') or double quotes (eg. Password="PASS;WORD").
fileProvider = "Type=Database; File=SomeFolder/SomeFile.ext; Connection String='Data Source=(local); Initial Catalog=SomeDb; Integrated Security=SSPI'; Table=SomeTable; Key Field=Path; Content Field=Content";

//---------------------------------------

/*

Sample SQL script to create a table in the database:

CREATE TABLE [File] (
    [Id] [int] IDENTITY(1, 1) PRIMARY KEY,
    [Path] [nvarchar](500) NOT NULL UNIQUE,
    [Name] [nvarchar](100),
    [DateModified] [smalldatetime],
    [Size] [bigint],
    [Content] [varbinary](max)
);

*
*/

Setting a AssemblyResourceFileProvider instance, to connect to a file embedded in an assembly:

C#
FileProvider fileProvider;

//Setting an assembly resource file provider via a AssemblyResourceFileProvider instance:
fileProvider = new AssemblyResourceFileProvider
{
    File = @"SomeFolder\SomeFile.ext",
    Assembly = typeof(SomeType).Assembly,
    BaseNamespace = typeof(SomeType).Namespace
};

//Setting an assembly file provider via a provider string (same as above):
fileProvider = @"Type=AssemblyResource; File=SomeFolder\SomeFile.ext; Assembly=SomeAssembly; Base Namespace=Some.Namespace";

Setting a TemporaryFileProvider instance, to connect to a temporary file:

C#
FileProvider fileProvider;

//Setting a temporary file provider via a TemporaryFileProvider instance:
//Note that this instance should be written (filled with data via OpenWrite method) before being read
fileProvider = new TemporaryFileProvider("SomeFolder/SomeFile.ext");

Setting and implementing a custom file provider:

C#
FileProvider fileProvider;

//Setting a custom file provider:
fileProvider = new CustomFileProvider
{
    File = @"SomeFolder\SomeFile.ext",
    Parameters = new Dictionary<string, string>
    {
        {"parameter1", "value1"}
    }
};
C#
public class CustomFileProvider: FileProvider
{
    public override string File { get; set; }

    //Return true if DoGetInfo method is implemented, and false if not.
    public override bool CanGetInfo => true;

    //Return true if DoOpenRead method is implemented, and false if not.
    public override bool CanOpenRead => true;

    //Return true if DoOpenWrite method is implemented, and false if not.
    public override bool CanOpenWrite => false;

    //Return true only if File identifier is usable across processes/machines.
    public override bool CanSerialize => false;

    protected override FileProviderInfo DoGetInfo()
    {
        //Return info here which corresponds to the identifier in File property.

        //When this file provider is used in DocumentViewer:
        //This method will be called every time DocumentViewer requests a document.
        //The cache key and document format will be determined according to the info you return here.

        string fileName = File;
        DateTime dateModified = DateTime.Now;
        long size = 81920;

        return new FileProviderInfo(fileName, dateModified, size);

        //throw new NotImplementedException();
    }

    protected override Stream DoOpenRead()
    {
        //Open and return a readable stream here which corresponds to the identifier in File property.

        //You can make use of Parameters dictionary which was passed when this provider was initialized.
        //var someParameter = Parameters["parameter1"];

        //When this file provider is used in DocumentViewer:
        //This method will be called only when original input document is required, 
        //For example if DocumentViewer already did the required conversions and cached the results, 
        //it will not be called.

        return readableStream;

        //throw new NotImplementedException();
    }

    protected override Stream DoOpenWrite()
    {
        //Open and return a writable stream here which corresponds to the identifier in File property.

        throw new NotImplementedException();
    }
}

Constructors

ImageTask(Image, Boolean, ImageUltimateConfiguration) Initializes a new instance of the ImageTask class from the specified Image.
ImageTask(Byte, NullableImageFormat, Boolean, ImageUltimateConfiguration) Initializes a new instance of the ImageTask class from the specified image byte array.
ImageTask(FileProvider, NullableImageFormat, Boolean, ImageUltimateConfiguration) Initializes a new instance of the ImageTask class from the specified image file.
ImageTask(Stream, NullableImageFormat, Boolean, ImageUltimateConfiguration) Initializes a new instance of the ImageTask class from the specified image stream.

Properties

Info Gets the source image information and metadata.

Methods

Blur Blurs the current image with the specified radius. The command is added to the chain and not executed until the actual processing is done.
(Inherited from ImageTaskBaseT)
Brightness Adjusts brightness of the current image by the given amount. The command is added to the chain and not executed until the actual processing is done.
(Inherited from ImageTaskBaseT)
BrightnessContrast Adjusts brightness and contrast of the current image by the given amounts simultaneously. The command is added to the chain and not executed until the actual processing is done.
(Inherited from ImageTaskBaseT)
Contrast Adjusts contrast of the current image by the given amount. The command is added to the chain and not executed until the actual processing is done.
(Inherited from ImageTaskBaseT)
Crop(Rectangle) Crops the current image to the given rectangle. The command is added to the chain and not executed until the actual processing is done.
(Inherited from ImageTaskBaseT)
Crop(Int32, Int32, Int32, Int32) Crops the current image to the given coordinates and size. The command is added to the chain and not executed until the actual processing is done.
(Inherited from ImageTaskBaseT)
DisposeReleases all resources used by this instance.
Enhance Enhances the current image by adjusting colors and gamma automatically. The command is added to the chain and not executed until the actual processing is done.
(Inherited from ImageTaskBaseT)
FixOrientation Adjusts the current image so that its orientation is suitable for viewing (i.e. top-left orientation). The command is added to the chain and not executed until the actual processing is done. This command reads and resets the EXIF image profile setting 'Orientation' and then performs the appropriate 90 degree rotation on the image to orient the image, for correct viewing. When AutoFixOrientationEnabled is set to true, you don't need to call this method manually.
(Inherited from ImageTaskBaseT)
FlipHorizontal Flips the current image horizontally. The image will be mirrored from left to right. The command is added to the chain and not executed until the actual processing is done.
(Inherited from ImageTaskBaseT)
FlipVertical Flips the current image vertically. The image will be mirrored from top to bottom. The command is added to the chain and not executed until the actual processing is done.
(Inherited from ImageTaskBaseT)
LiquidResize Resizes the current image to the given dimensions in content-aware manner (seam carving). The command is added to the chain and not executed until the actual processing is done.
(Inherited from ImageTaskBaseT)
RemoveMetadata Removes all metadata like EXIF, IPTC, XMP fields, clipping paths, color profiles, comments and PNG chunks from the current image. This is always called automatically when using ImageWebTask as image metadata can be a privacy problem for online images. The command is added to the chain and not executed until the actual processing is done.
(Inherited from ImageTaskBaseT)
Resize Resizes the current image to the given dimensions. The command is added to the chain and not executed until the actual processing is done.
(Inherited from ImageTaskBaseT)
ResizeHeight Resizes the current image to the given height while preserving the aspect ratio. This is a shortcut to calling Resize(Int32, Int32, ResizeMode) method with 0 for width value. The command is added to the chain and not executed until the actual processing is done.
(Inherited from ImageTaskBaseT)
ResizeWidth Resizes the current image to the given width while preserving the aspect ratio. This is a shortcut to calling Resize(Int32, Int32, ResizeMode) method with 0 for height value. The command is added to the chain and not executed until the actual processing is done.
(Inherited from ImageTaskBaseT)
Rotate Rotates the current image by the given angle. The command is added to the chain and not executed until the actual processing is done.
(Inherited from ImageTaskBaseT)
Save(FileProvider, NullableImageFormat) Executes all the commands in the chain and saves the resulting image to the specified file.
Save(Stream, NullableImageFormat) Executes all the commands in the chain and saves the resulting image to the specified stream.
SaveAsBase64DataUrl Executes all the commands in the chain and saves the resulting image as a base64 encoded data URL, formatted as "data:[<mediatype>][;base64],<data>".
SaveAsBytes Executes all the commands in the chain and saves the resulting image as a byte array.
SaveAsGleamTechDrawingImage Executes all the commands in the chain and saves the resulting image as a Image. Every call returns a new Image instance which should be disposed by the caller.
Sharpen Sharpens the current image with the specified radius. The command is added to the chain and not executed until the actual processing is done.
(Inherited from ImageTaskBaseT)
Thumbnail Smartly generates a thumbnail from the current image. This method is optimized for thumbnails so you should prefer it over Resize(Int32, Int32, ResizeMode), ResizeWidth(Int32, ResizeMode) or ResizeHeight(Int32, ResizeMode) methods. This command should be the first one in the chain. Most image formats (Jpg, Tiff, Psd and Camera Raw files) can have EXIF thumbnails so this method will first try to read that image from EXIF metadata, remove black stripes above and below it and resize it down further if needed. This will ensure very fast performance when your whole purpose is generating thumbnails. Only if there is no thumbnail in metadata or the thumbnail is smaller than the requested size, the thumbnail will be created by resizing the original image as usual. EXIF thumbnails are typically in size 160x120.
(Inherited from ImageTaskBaseT)
TrimBorders(Double) Trims the borders of any color around the current image. The command is added to the chain and not executed until the actual processing is done.
(Inherited from ImageTaskBaseT)
TrimBorders(Color, Double) Trims the borders of a specific color around the current image. The command is added to the chain and not executed until the actual processing is done.
(Inherited from ImageTaskBaseT)
Undo Undoes the last command in the chain.
UndoAll Undoes all commands in the chain.

See Also