MARKAND Bhatt
MARKAND Bhatt

Reputation: 2650

Strech image to fill the transparent background using Magick.NET

I have an image (attached). enter image description here

I want the image to be stretched out to cover the yellow area.

I am using c#, magick.net

What will be the best approach?

Upvotes: 0

Views: 1605

Answers (1)

Andrea
Andrea

Reputation: 12405

I propose the following approach:

  1. read input image saving original size
  2. remove the transparent* area using trim
  3. stretch the (now smaller) image to the original size

*If the yellow area in your sample image is actually transparent you can leave fuzz = 0 in the following code, otherwise you'll have to adjust the value to be sure to remove all the unwanted area.

string srcImageFullPath = "c:\input.png";
int fuzz = 0;
string destImageFullPath = "c:\output.png";

// Read image from file
using (MagickImage image = new MagickImage(srcImageFullPath))
{
    //save height/width of the original image
    int height = image.Page.Height;
    int width = image.Page.Width;

    //set fuzz percentage
    image.ColorFuzz = new ImageMagick.Percentage(fuzz);

    //trim borders
    image.Trim();

    //resize image to original size
    MagickGeometry size = new MagickGeometry(width, height);
    size.IgnoreAspectRatio = true;
    image.Resize(size);

    // Save the result
    image.Write(destImageFullPath);
}

In the following picture you can see the original image on the left, and the image after resizing on the right:

enter image description here

Notes

  1. Trim removes any border that has the same color of the pixels in the corner of you image (see here for the details)
  2. Since the yellow border in your sample image is not made of a single color you can use Fuzz to remove "similar" colors (more info here). As said before if your border is transparent just leave fuzz = 0

Upvotes: 3

Related Questions