3

It seems that the Python method, insert_image, in the xlsxwriter module fails to properly scale images once they become too large (e.g. 3840 pixels wide).

The following code should insert images into the Excel worksheet at 7.5 columns wide. However, the images come in at ~1.25 columns wide.

The sample code works for images that are 1328 and 1920 pixels wide. Does anyone know why insert_image doesn't scale large images correctly?

with xlsxwriter.Workbook('SampleFile.xlsx') as workbook:
    worksheet=workbook.add_worksheet()
    cell_width=64.0
    image_width=3840.0
    cols_wide=7.5
    scale = cell_width*cols_wide/image_width

    worksheet.insert_image('B2', 'SampleImage.png',
                       {'x_scale': scale, 'y_scale': scale})
stuckic
  • 51
  • 5
  • To verify that this is really a XlsxWriter issue you should try insert the same image in Excel manually and see if you get the same or a different result. Also you need to take the DPI of the image into account when scaling the image. See this section from the XlsxWriter docs: https://xlsxwriter.readthedocs.io/working_with_object_positioning.html#image-sizing-and-dpi After that, if you still think this is an XlsxWriter issue then open an issue on Github with a small program that demonstrates the issue and a sample image. – jmcnamara Dec 16 '20 at 17:05
  • 1
    Also, watch out for scaling in Excel for macOS which can be different than versions of Excel for Windows. – jmcnamara Dec 16 '20 at 17:07
  • 2
    Thank you, @jmcnamara. It looks like my large image (3840 pixel width) had a dpi of 600. The other two images that came in at the anticipated size had an image resolution of 72 dpi. – stuckic Dec 17 '20 at 19:02
  • @jmcnamara I've quoted you here: [How to get control of the size and shape of images using .insert_image() with xlsxwriter in macOS?](https://stackoverflow.com/q/75230353/3904031) – uhoh Jan 25 '23 at 06:30

0 Answers0