-1

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?

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • 1
    Maybe try entering `-1` for both the width and height as mentioned [here](https://msdn.microsoft.com/en-us/library/office/ff198302.aspx). – Quantic Mar 18 '16 at 19:39
  • 2
    And what happens if you copy and paste the image yourself? As mentioned [here](http://superuser.com/questions/211020/prevent-outlook-2010-insert-picture-resizing-image), Excel displays images based on physical size, so it uses the image's DPI setting to scale it; it does not simply map 1 image pixel to 1 screen pixel, that only happens when the images DPI is the same as the Windows setting. You might have to read in the image to the Image class, change its Vertical and HorizontalResolution properties, then resave it to temp file and add that temp file to the spreadsheet. – Quantic Mar 18 '16 at 19:44
  • You can set the dpi of the image very easily! – TaW Mar 18 '16 at 19:46
  • @TaW: But is knowing what to set it *to* easy? Or just a matter of trial and exception? – B. Clay Shannon-B. Crow Raven Mar 18 '16 at 20:14
  • @Quantic: If you can make the "-1" comment an answer, I'll mark it as such; it works fine, making the first two args 0 and the second two -1. – B. Clay Shannon-B. Crow Raven Mar 18 '16 at 20:23

1 Answers1

1

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

Quantic
  • 1,779
  • 19
  • 30