Search code examples
c#vipslibvips

Netvips Thumbnail does not preserve resolution or remove some parts of image


I'm using NetVips to create some diferent sizes of my image

This is my original imgenter image description here

And this is the result

enter image description here

This is my code:

    public static void GetThumbNail(
        string sourcePath,
        string targetPath,
        int width,
        int height,
        int R = 255,
        int G = 255,
        int B = 255)
    {
        if (targetPath == null)
            targetPath = Path.Combine(Path.GetDirectoryName(sourcePath), $"{Path.GetFileNameWithoutExtension(sourcePath)}_Thumb{Path.GetExtension(sourcePath)}");
        Image main = Image.Black(width, height, 3);
        main = main + new[] { R, G, B };
        Image watermark = Image.Thumbnail(sourcePath, width, height);
        int top = (main.Height - watermark.Height) / 2;
        int left = (main.Width - watermark.Width) / 2;
        // extract related area from main image
        var baseImage = main.Crop(left, top, watermark.Width, watermark.Height);
        // composite the two areas using the PDF "over" mode
        var composite = baseImage.Composite(watermark, Enums.BlendMode.Over);
        // the result will have an alpha, and our base image does not..we must flatten
        // out the alpha before we can insert it back into a plain RGB JPG image
        composite = composite.Flatten();
        // insert composite back in to main image on related area
        var combined = main.Insert(composite, left, top);
        combined.WriteToFile(targetPath);
    }

Solution

  • It looks like you want to thumbnail to fit within a specified width x height, with the thumbnail being padded with a background colour if one dimension is too small, is that right?

    You can use Thumbnail() to fit within a certain width x height, then Gravity() to expand in case one axis is too short.

    I would try (untested):

    Image
        .Thumbnail(sourcePath, width, height)
        .Gravity(Enums.CompassDirection.Centre, width, height, Enums.Extend.Background, new[] { R, G, B })
        .WriteToFile(targetPath);