How can I prevent an embedded image from overflowing its borders?

I insert an image into an Excel range like this:

private System.Drawing.Image _logo; public ProduceUsageRpt(..., System.Drawing.Image logo) { . . . _logo = logo; } . . . var logoRange = _xlSheet.Range[ _xlSheet.Cells[LOGO_FIRST_ROW, _grandTotalsColumn], _xlSheet.Cells[LOGO_LAST_ROW, _grandTotalsColumn]]; Clipboard.SetDataObject(_logo, true); _xlSheet.Paste(logoRange, _logo); 

Unfortunately, the image is too large for this range (currently row 1 - row 4, column 16). Instead of doing a polite thing and scaling itself so that it matches the prescribed boundaries, it spills over the designated vertical and horizontal spots.

How can I get an image for scaling and limit myself to its “box”?

0
source share
1 answer

I got an answer from adapting one of the related questions here .

While I am making the range large enough, this works:

  . . . var logoRange = _xlSheet.Range[ _xlSheet.Cells[LOGO_FIRST_ROW, _grandTotalsColumn], _xlSheet.Cells[LOGO_LAST_ROW, _grandTotalsColumn+1]]; PlacePicture(_logo, logoRange); } // From Jürgen Tschandl private void PlacePicture(Image picture, Range destination) { Worksheet ws = destination.Worksheet; Clipboard.SetImage(picture); ws.Paste(destination, false); Pictures p = ws.Pictures(System.Reflection.Missing.Value) as Pictures; Picture pic = p.Item(p.Count) as Picture; ScalePicture(pic, (double)destination.Width, (double)destination.Height); } // Also from Jürgen Tschandl private void ScalePicture(Picture pic, double width, double height) { double fX = width / pic.Width; double fY = height / pic.Height; double oldH = pic.Height; if (fX < fY) { pic.Width *= fX; if (pic.Height == oldH) // no change if aspect ratio is locked pic.Height *= fX; pic.Top += (height - pic.Height) / 2; } else { pic.Width *= fY; if (pic.Height == oldH) // no change if aspect ratio is locked pic.Height *= fY; pic.Left += (width - pic.Width) / 2; } } 
0
source

Source: https://habr.com/ru/post/897294/


All Articles