Introducing Livops 2.0! Promo codeCEOgives you 8,000 so‘m on your balance.What’s new

Bad Request: PHOTO_INVALID_DIMENSIONS — Telegram sendPhoto size rules and the fix

Bad Request: PHOTO_INVALID_DIMENSIONS means Telegram would not take the image as a photo because of its shape or size: for sendPhoto, width plus height must not exceed 10000 pixels and the longer side may be at most 20 times the shorter. Long screenshots, receipts and panoramas break these rules. Resize or pad the image with Pillow, split a tall one into an album, or send the original file with sendDocument.

By Livops team, the people who build and run LivopsUpdated

Telegram’s answer to a sendPhoto the server refused for its dimensions, as the Bot API server formats a 400 error[3]:

{"ok":false,"error_code":400,"description":"Bad Request: PHOTO_INVALID_DIMENSIONS"}

PHOTO_INVALID_DIMENSIONS is Telegram’s own error code, described in its API as “The photo dimensions are invalid.”[2] Your library wraps it:

Library What you see
aiogram 3 TelegramBadRequest: Telegram server says - Bad Request: PHOTO_INVALID_DIMENSIONS[4][5]
python-telegram-bot telegram.error.BadRequest: Photo_invalid_dimensions[8][9]

This page gives the rules a photo has to meet, in Telegram’s words, the images that usually break them, and four fixes with Pillow code. It ends with what to check on Livops.

The rules, as Telegram states them

The Bot API documents three limits for the photo in sendPhoto[1]:

Rule Limit
File size at most 10 MB
Width + height must not exceed 10000 in total
Aspect ratio width and height ratio at most 20

The file size limit is covered with Telegram’s other file limits in file is too big. The other two rules are about the image’s dimensions, which is what PHOTO_INVALID_DIMENSIONS names. Read the ratio both ways: the long side may be at most 20 times the short side, whether the image is tall or wide.

sendDocument has no dimension rule in the docs; bots can send files of any type up to 50 MB with it[1].

Which images break the rules

The arithmetic is quick. A few common shapes:

Image Size (px) Width + height Ratio As a photo
Phone screenshot 1080 × 2400 3480 2.2 passes
Long scrolling screenshot 1080 × 8000 9080 7.4 passes
Very long scrolling screenshot 1170 × 25000 26170 21.4 fails both rules
Receipt from a thermal printer template 384 × 9000 9384 23.4 fails the ratio
Panorama 12000 × 2000 14000 6 fails the total
Chart rendered at high resolution 8000 × 4000 12000 2 fails the total

So the usual sources are full-page screenshots of chats, web pages or reports; receipts and cheques the bot draws itself; panoramas; and images a bot renders at a large size for print.

Check before you send

Read the size with Pillow; Image.size is a (width, height) tuple in pixels, and Image.open reads only the header until the pixels are needed[11]:

from io import BytesIO
from PIL import Image

MAX_SUM = 10_000   # width + height
MAX_RATIO = 20     # long side / short side


def fits_telegram_photo(width: int, height: int) -> bool:
    return width + height <= MAX_SUM and max(width, height) / min(width, height) <= MAX_RATIO


with Image.open(BytesIO(data)) as img:
    ok = fits_telegram_photo(*img.size)

Fix 1: send it as a document

When the user needs every pixel, such as a receipt they will zoom into, do not fit it into a photo. Send the original file with sendDocument, which has the 50 MB limit and no dimension rule[1]. Upload the bytes; a photo cannot be resent as a document by its file_id, because the type cannot change on resend[1].

# aiogram 3
from aiogram.types import BufferedInputFile

await message.answer_document(BufferedInputFile(data, filename="receipt.png"))
# python-telegram-bot
await context.bot.send_document(chat_id, document=data, filename="receipt.png")

aiogram uploads bytes with BufferedInputFile[6]; python-telegram-bot’s send_photo and send_document accept bytes and a filename[10]. A good pattern is to try the photo, and fall back to the document on this error (Fix 4).

Fix 2: resize and pad with Pillow

When a preview is enough, make the image fit. Two steps, in this order:

  1. Ratio over 20: pad the short side. ImageOps.pad returns a resized and padded version of the image, expanded to fill the requested aspect ratio and size, with a background color you choose[12].
  2. Width + height over 10000: shrink. Image.thumbnail resizes in place to no larger than the given size and keeps the aspect ratio[11].
import math
from io import BytesIO
from PIL import Image, ImageOps

MAX_SUM = 10_000
MAX_RATIO = 20
SAFE_RATIO = 19   # a margin, so rounding never lands on 20.01


def to_telegram_photo(data: bytes) -> bytes:
    img = ImageOps.exif_transpose(Image.open(BytesIO(data))).convert("RGB")
    w, h = img.size

    # 1. Too narrow or too flat: pad the short side with white.
    if max(w, h) / min(w, h) > MAX_RATIO:
        if h > w:
            size = (math.ceil(h / SAFE_RATIO), h)
        else:
            size = (w, math.ceil(w / SAFE_RATIO))
        img = ImageOps.pad(img, size, color="white")
        w, h = img.size

    # 2. Too big: shrink until width + height fits.
    if w + h > MAX_SUM:
        scale = MAX_SUM / (w + h)
        img.thumbnail((int(w * scale), int(h * scale)))

    out = BytesIO()
    img.save(out, format="JPEG", quality=85)
    return out.getvalue()

Some details from Pillow’s docs:

  • ImageOps.exif_transpose turns the image the way its EXIF Orientation tag says, so a phone photo is measured the way it is seen[12].
  • Pillow’s JPEG files hold L, RGB or CMYK data[13]; convert("RGB") returns an RGB copy of the image[11], so a PNG screenshot can be saved as JPEG.
  • JPEG quality runs from 0 to 95, default 75; values above 95 make large files with hardly any gain[13]. Check the result against the 10 MB photo limit too[1].
  • When saving to a file object such as BytesIO, you must name the format[11].

We ran this on a 1170 × 25000 screenshot, a 384 × 9000 receipt and a 12000 × 2000 panorama: they came out 500 × 9498, 474 × 9000 and 8568 × 1428, all within the rules. Note what step 2 does to the long screenshot: 500 pixels wide is hard to read. For tall images, Fix 3 is better.

Fix 3: split a tall image into an album

Cut a long screenshot into pieces that each pass the rules, and send them together. sendMediaGroup sends 2 to 10 photos as an album[1]. Image.crop takes a (left, upper, right, lower) box[11]:

def split_tall(data: bytes) -> list[bytes]:
    img = ImageOps.exif_transpose(Image.open(BytesIO(data))).convert("RGB")
    w, h = img.size
    step = min(SAFE_RATIO * w, MAX_SUM - w)   # the tallest piece that passes
    pieces = math.ceil(h / step)
    step = math.ceil(h / pieces)              # equal pieces, no thin last strip
    parts = []
    for top in range(0, h, step):
        out = BytesIO()
        img.crop((0, top, w, min(top + step, h))).save(out, format="JPEG", quality=85)
        parts.append(out.getvalue())
    return parts
# aiogram 3
from aiogram.types import BufferedInputFile, InputMediaPhoto

parts = split_tall(data)
if len(parts) == 1:
    await message.answer_photo(BufferedInputFile(parts[0], filename="page.jpg"))
else:
    for i in range(0, len(parts), 10):   # an album holds 2 to 10
        batch = parts[i:i + 10]
        if len(batch) == 1:
            await message.answer_photo(BufferedInputFile(batch[0], filename="page.jpg"))
        else:
            await message.answer_media_group([
                InputMediaPhoto(media=BufferedInputFile(p, filename=f"page-{i + n}.jpg"))
                for n, p in enumerate(batch)
            ])

The 1170 × 25000 screenshot becomes three pieces of 1170 × about 8334, each at full width. aiogram’s Message has answer_photo, answer_document and answer_media_group[7], and an InputMediaPhoto can carry a newly uploaded file as its media[1][6].

Fix 4: catch the error and fall back

Keep the check in front, and still catch the error, so a bot never fails silently on an image you did not foresee:

# aiogram 3
from aiogram.exceptions import TelegramBadRequest
from aiogram.types import BufferedInputFile

try:
    await message.answer_photo(BufferedInputFile(data, filename="image.png"))
except TelegramBadRequest as e:
    if "PHOTO_INVALID_DIMENSIONS" not in e.message:
        raise
    await message.answer_document(BufferedInputFile(data, filename="image.png"))
# python-telegram-bot: the message reads "Photo_invalid_dimensions", so compare in lower case
from telegram.error import BadRequest

try:
    await context.bot.send_photo(chat_id, photo=data, filename="image.png")
except BadRequest as e:
    if "photo_invalid_dimensions" not in e.message.lower():
        raise
    await context.bot.send_document(chat_id, document=data, filename="image.png")

aiogram raises TelegramBadRequest for a 400 and keeps Telegram’s description as message[4][5]. python-telegram-bot maps 400 to BadRequest, drops the Bad Request: prefix and capitalizes the rest, which turns the code into Photo_invalid_dimensions[8][9].

On Livops

  • Add Pillow to requirements.txt. The import is PIL, the package is Pillow; without it the bot stops with No module named 'PIL'.
  • Work in memory or in DATA_DIR. The code above never touches the disk. If you do write image files, the code folder is read-only while the bot runs, and /tmp is wiped on every restart and deploy and holds 128 MB. /app/data (the DATA_DIR variable) is the project’s own disk. See Files and data.
  • Large images belong in a bucket. For lots of images and large files, add an S3 storage bucket and send a link.
  • Logs. The error lines are on the project’s Logs page; livops logs <service> -f follows them from the terminal (CLI).

A bot costs 19 credits a month (19,000 so’m); see Pricing. If Telegram answers wrong file identifier when you resend a file, see wrong file identifier.

Questions

What are Telegram's size rules for a photo sent by a bot?

For sendPhoto the Bot API says the photo must be at most 10 MB, its width and height must not exceed 10000 in total, and the ratio of width and height must be at most 20. A 1080 by 8000 screenshot passes; a 1170 by 25000 one does not, and neither does a 384 by 9000 receipt.

Is PHOTO_INVALID_DIMENSIONS about the file size in MB?

No. It is about the shape and pixel size of the image. The 10 MB limit for photos is a separate rule in the same sentence of the docs, so check both: the dimensions and the file size.

How do I send a very long screenshot without losing quality?

Send the original file with sendDocument: the documented limit there is 50 MB, with no dimension rule. Or cut it into pieces that each pass the photo rules and send them as an album of 2 to 10 photos.

Can I resend the photo as a document by its file_id?

No. Telegram does not let you change the file type when resending by file_id, and a photo cannot be sent as a document that way. Upload the original bytes with sendDocument instead.

Does shrinking the image always fix it?

Only for the 10000 pixel total. Shrinking keeps the shape, so an image whose long side is more than 20 times its short side still fails. Pad it, crop it, split it or send it as a document.

Why does python-telegram-bot show Photo_invalid_dimensions in lower case?

python-telegram-bot removes the Bad Request prefix from Telegram's description and capitalizes the rest, which lowercases everything after the first letter. Compare the message in lower case.

Sources

  1. Telegram Bot API — sendPhoto, Sending files, sendDocument, sendMediaGroup (core.telegram.org). Checked .
  2. Telegram API — messages.sendMedia (possible errors) (core.telegram.org). Checked .
  3. Telegram Bot API server source — telegram-bot-api/Client.cpp (raw.githubusercontent.com). Checked .
  4. aiogram source — aiogram/exceptions.py (raw.githubusercontent.com). Checked .
  5. aiogram source — aiogram/client/session/base.py (raw.githubusercontent.com). Checked .
  6. aiogram source — aiogram/types/input_file.py (raw.githubusercontent.com). Checked .
  7. aiogram source — aiogram/types/message.py (raw.githubusercontent.com). Checked .
  8. python-telegram-bot source — telegram/error.py (raw.githubusercontent.com). Checked .
  9. python-telegram-bot source — telegram/request/_baserequest.py (raw.githubusercontent.com). Checked .
  10. python-telegram-bot source — telegram/_bot.py (send_photo, send_document) (raw.githubusercontent.com). Checked .
  11. Pillow docs — Image module (pillow.readthedocs.io). Checked .
  12. Pillow docs — ImageOps module (pillow.readthedocs.io). Checked .
  13. Pillow docs — Image file formats (JPEG) (pillow.readthedocs.io). Checked .

Put your project online today

Connect GitHub or drop a folder. No card is asked for.

Deploy your bot

Got a question? — @livops_uz