Search code examples
c#imageexcel-interopimage-scalingimage-size

Why does an image display at greater that its actual size when pasting into Excel, and how can I get it to display at its natural size?


I've got this code to paste an image into Excel:

. . .
string unitImageLoc = GetUnitImageLoc();
if (unitImageLoc != "image not found")
{
    Image img = Image.FromFile(unitImageLoc);
    int imgWidth = img.Width;
    int imgHeight = img.Height;
    _xlSheet.Shapes.AddPicture(unitImageLoc, 
Microsoft.Office.Core.MsoTriState.msoFalse, 
Microsoft.Office.Core.MsoTriState.msoCTrue, 4, 4, imgWidth, imgHeight); 
}

private string GetUnitImageLoc()
{
    string unitUpper = _unit.ToUpper();
    string candidateFile = string.Format("C:\\RoboReporter\\{0}.png", 
unitUpper);
    if (File.Exists(candidateFile))
    {
        return candidateFile;
    }
    return "image not found";
}

It works, but prints the image larger than its actual size, as seen here (Excel on top, as appears in image viewer on the bottom):

enter image description here

It is not an issue with a specific image: it happens with any:

enter image description here

So do I need to multiply the width and height by 70% or something to get it to be the same?


Solution

  • Try entering -1 for width and height as mentioned here.