How to keep the ratio of image using AddPicture with a Stream

Posted by: renaud.roland on 13 September 2022, 4:09 pm EST

    • Post Options:
    • Link

    Posted 13 September 2022, 4:09 pm EST

    I’m working on a sheet where i should add the logo of a company if there is one.

    i face a problem as all the logo don’t have the same size, so the image is twisted.

    Here is my method to add the picture :

     public void AddLogo(Guid? brokerEnterpriseId, IWorksheet workingSheet)
            {
                var ets = _enterpriseQueryProcessor.Query()
                    .Where(x => x.Id == brokerEnterpriseId)
                    .FirstOrDefault();
    
                if (ets.LogoUrl == null)
                {
                    workingSheet.Range["A2"].Value = ets.Name;
                    return;
                }
    
                using (WebClient webClient = new WebClient())
                {
                    
                    byte[] data = webClient.DownloadData(ets.LogoUrl);
                    var str = new MemoryStream(data);
                   workingSheet.Shapes.AddPicture(str, ImageType.PNG, 10,3,50,50);
                }
    
            }
    

    Is there any solution to keep the ratio when using “AddPicture” ? Or any solution ?

    Thanks in advance.

  • Posted 14 September 2022, 6:53 pm EST

    Hello Roland,

    There is no direct way to keep the aspect ratio of the image when adding the picture to the excel sheet.

    As a workaround, you can calculate the aspect ratio of the image and set the picture height and width accordingly.

    Image img = Image.FromStream(str);
    double aspectRatio = (double)img.Height/img.Width;
    workingSheet.Shapes.AddPicture(img.ToStream(), ImageType.PNG, 10, 3, 50.0* aspectRatio, 50.0* aspectRatio);
    

    If you need any other help, please let us know.

    Regards,

    Prabhat Sharma.

Need extra support?

Upgrade your support plan and get personal unlimited phone support with our customer engagement team

Learn More

Forum Channels