简体   繁体   中英

how to change size of picture using openpyxl

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")

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'] .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM