Skip to main content

Publishing Images as Variants

For several versions (was it 5.3?) it is possible to publish Multimedia Components as variants. It means that in template code, we can choose to publish a representation of the MMComponent instead of the original. When unpublishing a MMComponent, all its variants are unpublished as well.

A big use case of variants is publishing images with different resolutions. In Tridion, we keep only one version of the MMComponent (i.e. the one with highest resolution), and during publishing we can produce as many variants as we need via templating. This post details this use case.

I wrote a TBB that performs the resize. The TBB takes 4 parameters:

  • Width - the new width (in pixels) of the image (optional);
  • Height - the new height (in pixels) of the image (optional);
  • Aspect Ratio - Yes/No whether to keep the original's aspect ratio (boolean, optional);
  • ImageTcmUri - the TcmUri of the image (mandatory);
When Aspect Ratio = Yes, either Width or Height need be specified. Otherwise, both Width and Height are required.

Read Parameters
string val = m_Package.GetValue("Width");
width = String.IsNullOrEmpty(val) ? -1 : Convert.ToInt32(val);

val = m_Package.GetValue("Height");
height = String.IsNullOrEmpty(val) ? -1 : Convert.ToInt32(val);

imageTcmUri = m_Package.GetValue("ImageTcmUri");
if (String.IsNullOrEmpty(imageTcmUri))
{
     throw new Exception("Mandatory parameter ImageTcmUri cannot be empty");
}
else if (!TcmUri.IsValid(imageTcmUri))
{
     imageTcmUri = m_Package.GetValue(imageTcmUri); // double lookup
     if (String.IsNullOrEmpty(imageTcmUri) || !TcmUri.IsValid(imageTcmUri))
     {
          throw new Exception("Invalid parameter ImageTcmUri");
     }
}

aspectRatio = "Yes".Equals(m_Package.GetValue("AspectRatio"));

Main Logic

First, I read the MMComponent from Engine, get its BinaryContent, then create a bitmap (System.Drawing.Bitmap) containing the original image.

For simplicity sake, I removed a lot of checks from the code below. Obviously, the code should be safe, so do implement checks like mmc != null, binaryContent != null, MMC is actually an image (check its mime-type) before loading it into a Bitmap.

Next, the original bitmap is resized. I will present this method in the following section. The resized bitmap is then saved into a Stream. Make sure to implement the other mime-types here as well!

Finally, the resized image is then published using the RenderedItem.AddBinary() method, which takes as input the new image stream, filename, variant id, MMComponent and mime-type.

Sample code:
Component mmc = m_Engine.GetObject(imageTcmUri) as Component;
BinaryContent binaryContent = mmc.BinaryContent;
byte[] binaryBytes = binaryContent.GetByteArray();
Bitmap bitmap = new Bitmap(new MemoryStream(binaryBytes));

Bitmap resizedBitmap = ResizeBitmap(bitmap);

MemoryStream resizedStream = new MemoryStream();
resizedBitmap.Save(resizedStream, ImageFormat.Jpeg);

string newFilename = GetNewFilename();
string variantId = GetVariant();
Binary binary = m_Engine.PublishingContext.RenderedItem.AddBinary(
    resizedStream, newFilename, variantId, mmc,
    binaryContent.MultimediaType.MimeType);

Resize Bitmap

This method is the one having nothing to do with Tridion. Is simply using the .NET framework System.Drawing namespaces to produce a new resized Bitmap.

The interesting parts are just the last 6 lines of code, anything before that is just computation of the new image width and height.

The good part about this function is that it preserves the alpha channel on transparent PNGs, thus no special treatment case is necessary. I tested this function on JPG, GIF, PNG and BMP.

private Bitmap ResizeBitmap(Bitmap sourceBitmap)
{
     int destWidth = width;
     int destHeight = height;

     if (aspectRatio)
     {
          int sourceWidth = sourceBitmap.Width;
          int sourceHeight = sourceBitmap.Height;

          float nPercent = 0;
          float nPercentW = 0;
          float nPercentH = 0;

          nPercentW = ((float)width / (float)sourceWidth);
          nPercentW = nPercentW < 0 ? 1 : nPercentW;
          nPercentH = ((float)height / (float)sourceHeight);
          nPercentH = nPercentH < 0 ? 1 : nPercentH;

          if (nPercentH < nPercentW)
          {
              nPercent = nPercentH;
          }
          else
          {
              nPercent = nPercentW;
          }

          destWidth = (int)(sourceWidth * nPercent);
          destHeight = (int)(sourceHeight * nPercent);
     }
     else
     {
          if (width < 0)
          {
              destWidth = sourceBitmap.Width;
          }
          if (height < 0)
          {
              destHeight = sourceBitmap.Height;
          }
     }

     Bitmap resultBitmap = new Bitmap(destWidth, destHeight);
     Graphics graphicsd = Graphics.FromImage((Image)resultBitmap);
     graphicsd.InterpolationMode = InterpolationMode.HighQualityBicubic;

     graphicsd.DrawImage(sourceBitmap, 0, 0, destWidth, destHeight);
     graphicsd.Dispose();

     return resultBitmap;
}


Comments

Walter said…
Loved reading this, thanks

Popular posts from this blog

Running sp_updatestats on AWS RDS database

Part of the maintenance tasks that I perform on a MSSQL Content Manager database is to run stored procedure sp_updatestats . exec sp_updatestats However, that is not supported on an AWS RDS instance. The error message below indicates that only the sa  account can perform this: Msg 15247 , Level 16 , State 1 , Procedure sp_updatestats, Line 15 [Batch Start Line 0 ] User does not have permission to perform this action. Instead there are several posts that suggest using UPDATE STATISTICS instead: https://dba.stackexchange.com/questions/145982/sp-updatestats-vs-update-statistics I stumbled upon the following post from 2008 (!!!), https://social.msdn.microsoft.com/Forums/sqlserver/en-US/186e3db0-fe37-4c31-b017-8e7c24d19697/spupdatestats-fails-to-run-with-permission-error-under-dbopriveleged-user , which describes a way to wrap the call to sp_updatestats and execute it under a different user: create procedure dbo.sp_updstats with execute as 'dbo' as

I Have Gone Dark

Maybe it's the Holidays, but my mood has gone pretty dark. That is, regarding the look and feel of my computer and Tridion CME, of course. What I did was to dim the lights on the operating system, so I installed Placebo themes for Windows 7 . I went for the Ashtray look -- great name :) My VM looks now like this: But, once you change the theme on Windows, you should 'match' the theme of your applications. Some skin easily, some not. The Office suite has an in-built scheme, which can be set to Black , but it doesn't actually dim the ribbon tool bars -- it looks quite weird. Yahoo Messenger is skinnable, but you can't change the big white panels where you actually 'chat'. Skype is not skinnable at all. For Chrome, there are plenty of grey themes. Now i'm using Pro Grey . But then I got into changing the theme of websites. While very few offer skinnable interfaces (as GMail does), I had to find a way to darken the websites... Enter Stylish -- a pl

REL Standard Tag Library

The RSTL is a library of REL tags providing standard functionality such as iterating collections, conditionals, imports, assignments, XML XSLT transformations, formatting dates, etc. RSTL distributable is available on my Google Code page under  REL Standard Tag Library . Always use the latest JAR . This post describes each RSTL tag in the library explaining its functionality, attributes and providing examples. For understanding the way expressions are evaluated, please read my post about the  Expression Language used by REL Standard Tag Library . <c:choose> / <c:when> / <c:otherwise> Syntax:     <c:choose>         <c:when test="expr1">             Do something         </c:when>         <c:when test="expr2">             Do something else         </c:when>         <c:otherwise>             Do something otherwise         </c:otherwise>     </c:choose> Att