2013-06-11

Using a custom format in ImageVault to specify compression quality in jpg images

If you want to request an converted image in ImageVault and also specify the compression quality for a jpeg image you cannot use the LINQ syntax in the C# API of ImageVault. The LINQ engine only wraps some functions in the API and compression quality is not yet added to the mix.
To do this we need to use another approach and access the service methods directly (like the LINQ parser does internally).

First we need a client.
var client = ClientFactory.GetSdkClient();
Then we need to create a format that has the correct parameters.
//Compression quality can be set on ImageFormats where 100 is maximum quality
var format = new ImageFormat {
  CompressionQuality = 80,
  MediaFormatOutputType = MediaFormatOutputTypes.Jpeg;
};
format.Effects.Add(new ResizeEffect(200, 200));
Here we created an ImageFormat and specifies the Compression quality to 80 and specify that we want to have a jpeg output image. We can then add other effects to it, like in this case, a Resize effect.

Next step is to create a query that will be used to find the media we are looking for.
var q = new MediaItemQuery {
  //we filter out the items we want to retrieve (in this case media with id 485)
  Filter = { Id = new List<int> { 485 } },
  //and supply the format that we want to populate
  Populate = {
    MediaFormats = { format },
    PublishIdentifier = client.PublishIdentifier
  }
};
This query will filter out image with id 485 and populate the found MediaItem with the requested formats (in this case the one that we defined above).
Note that we have not created the format, this will be done automatically (or if a matching format is found, it will be reused). These format are called system formats and is not visible in the UI.
We also specify a publish identifier that will generate the urls to the converted media as public urls (no authentication).

This query is then passed to the service method.
//first create the media service channel
var mediaService = client.CreateChannel<IMediaService>();
//we then pass the query object to the find method
var mediaItem = mediaService.Find(q).Single();
//and since we only requested one Format, the converted image url will reside 
//in the first MediaConversion of the item.
var url = mediaItem.MediaConversions[0].Url;
When all is done we have the url to the converted (and published) jpeg image.
Note: the client.PublishIdentifier will be set if you are in an EPiServer site or if you configure it in the imagevault.client.config. You can also set this manually.