Search code examples
c#imageepplus

C# EPPlus resize pictures to fit in the cell


I am trying to place a picture into B1 cell. picture is getting inserted but height is getting bigger than original image. how automatically height is getting stretched?

I am using EPPlus version 4.0.6.0 & .Net version 4.5.2. using VS IDE 2013.

Here is the output screenshot.

enter image description here

Desired output screenshot

enter image description here

here is the code sample which i used to place picture into B1 cell.

imgCompanyLogo = Image.FromFile(@"C:\Users\tridip\Desktop\Test1\www_files\image002.png");
ws.Column(2).Width = Convert.ToDouble((45 + 0.11));
ws.Row(1).Height = Convert.ToDouble((46.5 + 0.11));
ExcelPicture pic = ws.Drawings.AddPicture("Logo", imgCompanyLogo);
pic.SetPosition(0, 0, 1, 0);
pic.SetSize(316, 60);

if i commented or not commented this line pic.SetPosition(0, 0, 1, 0); but always getting same output where picture is getting stretched.

see the original image how it looks like. link here https://ibb.co/PCxw3v0

what is the mistake in my code? or suggest a fix by which i can get my desired output.


Solution

  • This issue resolved. i place image at the end before saving excel file. here is the code.

        if (imgCompanyLogo != null)
        {
            decimal mdw = ws.Workbook.MaxFontWidth;
            int pixelHeight = (int)(ws.Row(1).Height / 0.75);
            int pixelWidth = (int)decimal.Truncate(((256 * (decimal)ws.Column(2).Width + decimal.Truncate(128 / (decimal)mdw)) / 256) * mdw);
        
            var picture = ws.Drawings.AddPicture("Test", imgCompanyLogo);
            picture.SetSize(pixelWidth, pixelHeight);
            //picture.EditAs = OfficeOpenXml.Drawing.eEditAs.TwoCell;
            picture.SetPosition(0, 0, 1, 0);
        }
    output.Save();
    

    Thanks