4

there. I want to change size of picture using openpyxl. width = 11.21 cm. height = 7.69 cm.

or I want to change the size of picture same as the cell.

my code is below. it makes very small size picture. could you help me?

from openpyxl import load_workbook
from openpyxl.drawing.image import Image

filename="1.xlsx"
wb = load_workbook(filename)
ws = wb.worksheets[0]
img = Image('13.5.jpg')
img.width = 11.21
img.height = 7.69
ws.add_image(img, 'B13')
wb.save('1.xlsx')
print("done")
박형렬
  • 377
  • 1
  • 9
  • 24

2 Answers2

6

For clarification to anyone else (keineahnung2345 has the correct post, mine is just supplementary) this is how to set image size:

img = openpyxl.drawing.image.Image('filelocation.png')
img.height = # insert image height in pixels as float or int (e.g. 305.5)
img.width= # insert image width in pixels as float or int (e.g. 405.8)
img.anchor = 'A1' # where you want image to be anchored/start from
sheet.add_image(img) # adding in the image

Again be sure to check dpi which acts as a multiplier on the pixel amount. You can check image size by clicking on the image in excel and inspecting the properties, which should give you a size in inches or centimeters.

For anyone using inches, here is a inches to pixel converter: https://www.unitconverters.net/typography/inch-to-pixel-x.htm

The centimeter converter can be found in the selected answer from keineahnung2345.

Steven Barnard
  • 514
  • 7
  • 12
3

openpyxl.drawing.image.Image is based on PIL.Image. In PIL.Image, the unit of image size is pixel. So you should first calculate the image's width and height in pixel.

The formula is(Ref: Pixel to Centimeter?):

pixels = cms * dpi / 2.54

You can get dpi of that image by img.info['dpi'].

keineahnung2345
  • 2,635
  • 4
  • 13
  • 28
  • openpyxl.drawing.image.Image has no attribute `info`. Here's the source: https://foss.heptapod.net/openpyxl/openpyxl/-/blob/branch/3.1/openpyxl/drawing/image.py Furthermore, it's not clear how a raster pixel array would even need a dots per inch (dpi) value anyway. – Michael Currie Aug 19 '23 at 10:22