I have variable sized images I want to display in a table column. How can I center these images without stretching them to fill the table cell?
While there is no automatic centering behavior for the Image control, you can simulate this by writing an expression for PaddingLeft and PaddingTop to result in a centered image.
Step 1: Clip, don’t Fit
Set the Sizing property of the Image control to Clip. In a table cell, this is the only setting that won’t resize your image. (If your image gets automatically resized, the calculations below won’t work.)
Step 2: Give yourself room to grow
Make your column and row large enough to accomodate your largest image so that the image won’t clip.
Step 3: Turn off CanGrow
For all other cells in the row, turn off CanGrow, so ensure long textual contents won’t cause the row to increase in size (thereby invalidating the calculations below).
Step 4: Reference System.Drawing
To determine the size of the image, you’ll need to add a reference to the System.Drawing assembly in your report. This is in the Report Properties dialog on the References Tab.
Step 5: Calculate padding
To determine the size of the image, you’ll need to load the image from your field into a memory stream and from there load it into a .Net Image object. Since fields are of type Object, you’ll need to cast it to a byte array before loading it into a memory stream.
ImageWidthInPixels = System.Drawing.Image.FromStream(new System.IO.MemoryStream(CType(Fields!Photo.Value,Byte()))).Width
From there, you can calculate the half of the difference between the width of the image and the width of the column.
Padding = (ColumnWidthInInches-ImageWidthInPixels/DPI)/2
DPI is typically 96
The padding property takes a size, which is a string including the size and the units.
PaddingLeft = CStr(Round(Padding,2)) & “in”
Here’s the expression fully expanded:
Now just do the same thing for PaddingTop and you’ve got a fully centered image.
A full working sample of centered images is attached.