How to resize image without loosing aspect ratio and quality

I have tried following two methods to resize the image while doing the mail merge
first approach:-

public void ImageFieldMerging(ImageFieldMergingArgs args)
{
    if (args.FieldName.Equals("testField"))
    {
        DocumentBuilder builder = new DocumentBuilder(args.Document);
        builder.MoveToMergeField(args.FieldName);
        builder.InsertImage(args.FieldValue.ToString(), 32, 32);
    }
}

This approach does not maintain the aspect ratio
Approach 2:-

NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);
foreach (Shape shape in shapes)
{
    if (shape.HasImage)
    {
        //MemoryStream stream = new MemoryStream(shape.ImageData.ImageBytes);
        Image img = Image.FromStream(stream);
        ////resize image
        mg = ResizeImage(img, 32, 32);
        shape.ImageData.SetImage(img);
        shape.Width = 32;
        shape.Height = 32;
        shape.AspectRatioLocked = true;
    }
    foreach (Shape sh in shape.GetChildNodes(NodeType.Shape, true))
    {

        if (shape.HasImage)
        {
            shape.AspectRatioLocked = true;
        }
    }
}
private static Image ResizeImage(Image sourceImage, int targetWidth, int targetHeight)
{
    float ratioWidth = (float)sourceImage.Width / targetWidth;
    float ratioHeight = (float)sourceImage.Height / targetHeight;
    if (ratioWidth > ratioHeight)
        targetHeight = (int)(targetHeight * (ratioHeight / ratioWidth));
    else
    {
        if (ratioWidth < ratioHeight)
            targetWidth = (int)(targetWidth * (ratioWidth / ratioHeight));
    }

    Image outputImage = sourceImage.GetThumbnailImage(targetWidth, targetHeight, null, new IntPtr());
    return outputImage;
}

This approach reduces the quality of image.
So, how to reduce the image size without losing the quality as we do in ms word.

@SachinSingh Please use the following code to resize image upon executing mail merge keeping the image aspect ratio:

public void ImageFieldMerging(ImageFieldMergingArgs args)
{
    if (args.FieldName.Equals("testField"))
    {
        DocumentBuilder builder = new DocumentBuilder(args.Document);
        builder.MoveToMergeField(args.FieldName);
        Shape img = builder.InsertImage(args.FieldValue.ToString());
        img.AspectRatioLocked = true;
        img.Height = 32;
        img.Width = 32;
    }
}
1 Like

Thanks, it worked very well.

1 Like