'ImageDraw' object has no attribute 'textsize'
时间: 2023-07-14 22:04:09 浏览: 394
The error message "'ImageDraw' object has no attribute 'textsize'" typically occurs when trying to use the `textsize` method from the `ImageDraw` object in the Python Imaging Library (PIL) or Pillow library. However, the `textsize` method does not exist in the `ImageDraw` object.
To measure the size of text in an image using PIL or Pillow, you can use the `ImageFont` and `ImageDraw` objects together. Here's an example:
```python
from PIL import Image, ImageDraw, ImageFont
# Load the image
image = Image.open("example.jpg")
# Create a font object
font = ImageFont.truetype("arial.ttf", 24)
# Create a draw object
draw = ImageDraw.Draw(image)
# Text to measure
text = "Hello, World!"
# Get the size of the text
text_size = draw.textsize(text, font=font)
# Print the size of the text
print("Text size:", text_size)
# Draw the text on the image
draw.text((10, 10), text, font=font, fill=(255, 255, 255))
# Save the modified image
image.save("output.jpg")
```
Make sure to replace "example.jpg" with the path to your own image file, and "arial.ttf" with the path to a TrueType font file on your system.
This code will load an image, create a font object, create a draw object using the image, measure the size of the text using `textsize`, and then draw the text on the image. Finally, it will save the modified image as "output.jpg".