How to resize and crop an image in c#?

37 Views Asked by At

I have a function that takes a bitmap and creates a poster while scaling the image. Following is my code that creates a fixedPage and adds the image portion to it.

private FixedDocument CreateMultiplePages(BitmapImage bitmapImage)
    {
        FixedDocument fixedDocument = new FixedDocument();

    int rowsCount = rows > 0 ? rows : 1;
    int colsCount = columns > 0 ? columns : 1;

    double PageWidth = (double)document.PageWidth;
    double PageHeight = (double)document.PageHeight;

    for (int row = 0; row < rowsCount; row++)
    {
        for (int col = 0; col < colsCount; col++)
        {
            FixedPage fixedPage = new FixedPage();
            fixedPage.Width = (double)document.PageWidth;
            fixedPage.Height = (double)document.PageHeight;
            System.Windows.Controls.Image image = new System.Windows.Controls.Image
            {
                Source = bitmapImage,
                Stretch = Stretch.Fill,
                Width = (double)document.ImageScaledWidth,
                Height = (double)document.ImageScaledHeight,
                Margin = new Thickness(-col * PageWidth, -row * PageHeight, 0, 0) // Offset the image
            };

            fixedPage.Children.Add(image);

            PageContent pageContent = new PageContent();
            ((IAddChild)pageContent).AddChild(fixedPage);
            fixedDocument.Pages.Add(pageContent);
        }
    }
    return fixedDocument;
}

ImageScaledWidth and ImageScaledHeight are calculated as:

double totalPageWidth = (double)document.PageWidth * columns;
                double totalPageHeight = (double)document.PageHeight * rows;
                double ratio = totalPageWidth / totalPageHeight;
                if (ImageRatio > ratio)
                    ImageScale = totalPageWidth / ImageWidth;
                else
                    ImageScale = totalPageHeight / ImageHeight;

                document.ImageScaledWidth = (decimal)(ImageWidth * ImageScale);
                document.ImageScaledHeight = (decimal)(ImageHeight * ImageScale);

I need to modify the code in a way that I can resize the original image to document.ImageScaledWidth and document.ImageScaledHeight without making it blur and crop the needed size out of that image for each page. In this way i will be able to add margins in each page around the image. I tried a few methods but they make the image blur. What can I do?

1

There are 1 best solutions below

0
Alaa Adel On

If you're going to use it in a web application, I think Image processor package could help you to resize images on the fly. You can check it here: https://www.nuget.org/packages/ImageProcessor.Web/.

It provides various image processing operations like Resize, Rotate, Rounded Corners, Flip, Crop, Watermark, Filter, Saturation, Brightness, Contrast, Quality, Format, Vignette, Gaussian Blur, Gaussian Sharpen, and Transparency.