title: Apache POI - Keep original picture scale while fitting within a merged region
body: <p>I need to fit a picture into the center of a merged cell region. The merged cell region is always only one column wide, but multiple rows high.</p>
  
  <p>If the picture does not fit inside the cell region, it needs to resize, while keeping the original proportions.</p>
  
  <pre><code>    int pictureIdx = wb.addPicture(bytes, pictype);
      CreationHelper helper = wb.getCreationHelper();
      Drawing drawing = sheet.createDrawingPatriarch();
      ClientAnchor anchor = helper.createClientAnchor();
      anchor.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE);
      anchor.setCol1(column);
      anchor.setRow1(row);
      anchor.setRow2(row+rowspan);
      anchor.setCol2(column+1);
      Picture pict = drawing.createPicture(anchor, pictureIdx);
      pict.resize();
  
      short rowHeight = (short)0;
      for (int i = row; i&lt;row+rowspan; i++ ) {
          rowHeight += sheet.getRow(i).getHeight();
      }
      int rowHeightPx = heightUnits2Pixel(rowHeight); // (from [https://stackoverflow.com/a/31837639/1320704][1] )
      int columnWidthPx = (int) (sheet.getColumnWidthInPixels(column));
      int pictWidthPx = pict.getImageDimension().width;
      int pictHeightPx = pict.getImageDimension().height;
      float scale = 1;
      if (pictHeightPx &gt; rowHeightPx) {
          float tmpscale = (float)rowHeightPx / (float)pictHeightPx;
          if (tmpscale &lt; scale) scale = tmpscale;
      }
      if (pictWidthPx &gt; columnWidthPx) {
          float tmpscale = (float)columnWidthPx / (float)pictWidthPx;
          if (tmpscale &lt; scale) scale = tmpscale;
      }
      anchor.setDx1(
          (int) ((sheet.getColumnWidthInPixels(column)- pict.getImageDimension().width) /2)
      );
      pict.resize(scale, scale);
  </code></pre>
  
  <p>Here is the result:</p>
  
  <p><a href="https://i.stack.imgur.com/FYVzu.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FYVzu.jpg" alt="enter image description here"></a></p>
  
  <p>As you can see I did not get the desired effect. This picture is a square (256x256) but somehow it got distorted even though scale is passed the same for x and y. Also the height does not match. And it is not centered.</p>
  
  <p>For comparison, here is the same picture in the original size:</p>
  
  <p><a href="https://i.stack.imgur.com/8WyCZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8WyCZ.jpg" alt="enter image description here"></a></p>
  
  <p>And here is what I actually want to achieve:</p>
  
  <p><a href="https://i.stack.imgur.com/KP7Al.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KP7Al.jpg" alt="enter image description here"></a></p>