Pygame error unsupported image format

Hi I'm trying to follow these instructions from my last question: Pygame: how to load 150 images and present each one for only .5sec per trial This is the code I currently have and I'm unsure wher...

The first mistake is the same as in your previous question: types= '*.tif'. That means types is a string, but you actually wanted a tuple with the allowed file types: types = '*.tif', (the comma turns it into a tuple). So you iterate over the letters in '*.tif' and pass them to glob.glob which gives you all files in the directory and of course image_list.append(pygame.image.load(artwork).convert()) can’t work if you pass it for example a .py file.

The next mistake is the stimulus = pygame.image.load('image_list') line which doesn’t work because you need to pass a complete file name or path to the load function. I think your stimulus variable should actually be the current_image.

Here’s a complete example that also shows you how to implement a timer.

import glob
import random
import pygame


pygame.init()
clock = pygame.time.Clock()
window = pygame.display.set_mode((640, 480))

file_types = '*.tif',  # The comma turns it into a tuple.
# file_types = ['*.tif']  # Or use a list.
artfile_names = []
for file_type in file_types:
    artfile_names.extend(glob.glob(file_type))

image_list = []
for artwork in artfile_names:
    image_list.append(pygame.image.load(artwork).convert())

random.shuffle(image_list)

index = 0
current_image = image_list[index]
previous_time = pygame.time.get_ticks()

done = False

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    # Calcualte the passed time, then increment the index, use
    # modulo to keep it in the correct range and finally change
    # the image.
    current_time = pygame.time.get_ticks()
    if current_time - previous_time > 500: # milliseconds
        index += 1
        index %= len(image_list)
        current_image = image_list[index]
        previous_time = current_time

    # Draw everything.
    window.fill((30, 30, 30))  # Clear the screen.
    # Blit the current image.
    window.blit(current_image, (100, 100))

    pygame.display.update()
    clock.tick(30)

Содержание

  1. Raspberry Pi OS/Windows: pg.image.load(fileobj) doesn’t load jpegs in pygame 2 #1516
  2. Comments
  3. pygame.error: Unsupported image format #307
  4. Comments
  5. pygame.error Неподдерживаемый формат изображения
  6. 2 ответы
  7. test_load_extended cannot load tiff and webp: Unsupported image format about pygame HOT 7 CLOSED
  8. Comments (7)
  9. Game fails at start #4
  10. Comments

Raspberry Pi OS/Windows: pg.image.load(fileobj) doesn’t load jpegs in pygame 2 #1516

  • write unit test for BytesIO jpg/png image loading.
  • fix loading jpg/png from BytesIO

this code works in pygame 1.9.6, but return pygame.error: Unsupported image format in pygame 2 dev6

The text was updated successfully, but these errors were encountered:

I could not reproduce your problem. Could you post the JPEG file?

I could reproduce on Win10.

It seems to be just jpgs, I tested gif, tif, and png without issue.

I can also confirm this issue in dev10

pygame.error: Unsupported image format

I was banging my head against the wall until I realized it worked fine in pygame 1.9.6

Edit: For clarification, the imgurl in this case is a jpg. It works just fine when it’s a png.

For me it’s happening on all .jpg BytesIO objects and not on any .png BytesIO objects.

BUT I’ve been testing this and so far I can only reproduce this issue on Raspbian Buster (my main pygame usage platform).

I could not reproduce the issue on OSX Catalina, nor on Arch Linux (x64).

I’d be curious to know if the OP had this issue on Raspbian specifically, also.

@slackerbob What SDL2 version are you using on raspbian?

To those who suffer from this bug, can you please try using the file name parameter and try again?
The docs even say: load(fileobj, namehint=»») , and I’d be inclined to print a warning going forward when no dummy filename is provided via namehint to infer the data type. Maybe we could have a mime type parameter also.

Pygame will automatically determine the image type (e.g., GIF or bitmap) and create a new Surface object from the data. In some cases it will need to know the file extension (e.g., GIF images should end in «.gif»). If you pass a raw file-like object, you may also want to pass the original filename as the namehint argument.

It is very unfortunate that this was allowed in the first place, now we need to live with the backward compatibility.

Источник

pygame.error: Unsupported image format #307

Please include the log file
$ singularity
Singularity 1.00 (commit: 2ebc2f3)
Running under Python 3.9.5 (default, Jul 15 2021, 11:19:42) [GCC 10.3.0]
pygame 2.0.1 (SDL 2.0.10, Python 3.9.5)
Hello from the pygame community. https://www.pygame.org/contribute.html
The error-log configured as /home/user/.local/share/singularity/log/error.log (lazily created when something is logged)
Traceback (most recent call last):
File «/usr/bin/singularity», line 33, in
sys.exit(load_entry_point(‘Endgame-Singularity==1.0’, ‘gui_scripts’, ‘singularity’)())
File «/usr/lib/python3.9/site-packages/singularity/init.py», line 366, in main
gg.init_graphics_system()
File «/usr/lib/python3.9/site-packages/singularity/code/graphics/g.py», line 118, in init_graphics_system
theme.current.init_cache()
File «/usr/lib/python3.9/site-packages/singularity/code/graphics/theme.py», line 173, in init_cache
self._variants[variant].init_cache()
File «/usr/lib/python3.9/site-packages/singularity/code/graphics/theme.py», line 222, in init_cache
g.images[image_name] = g.load_image(image_filename)
File «/usr/lib/python3.9/site-packages/singularity/code/graphics/g.py», line 204, in load_image
image = pygame.image.load(filename).convert()
pygame.error: Unsupported image format

$ cat /home/user/.local/share/singularity/log/error.log
cat: /home/user/.local/share/singularity/log/error.log: No such file or directory

Additional context
the name of the file it tries to open is
/usr/lib/python3.9/site-packages/singularity/data/themes/default/images/earth.jpg

$ file /usr/lib/python3.9/site-packages/singularity/data/themes/default/images/earth.jpg
/usr/lib/python3.9/site-packages/singularity/data/themes/default/images/earth.jpg: JPEG image data, JFIF standard 1.02, resolution (DPI), density 72×72, segment length 16, baseline, precision 8, 2048×1024, components 3

$ du -b /usr/lib/python3.9/site-packages/singularity/data/themes/default/images/earth.jpg
266599 /usr/lib/python3.9/site-packages/singularity/data/themes/default/images/earth.jpg

I understand that this is the problem of my linux system, not the game, but i think that maintainers of distribution will not solve this without some tips on how to do this.

The text was updated successfully, but these errors were encountered:

Источник

pygame.error Неподдерживаемый формат изображения

запускаю Python 3.3.0 с pygame ‘1.9.2pre’, следуя учебному пособию, новичок в python, честно говоря, не вижу, где я ошибся, выглядит так же, как в учебнике, однако ему уже 4 года. Спасибо за помощь!

Я получаю сообщение об ошибке — неподдерживаемый формат изображения для обоих. Я пробовал jpg и png, спецификация версии говорит, что поддерживает их оба.

2 ответы

Я бы предположил, что окно pygame не закрывается из-за ошибки в вашем коде. Вы можете выйти из оболочки python, чтобы выйти из окна pygame, но здесь ошибка является основной проблемой.

Если вы импортируете изображения таким образом, убедитесь, что изображения находятся в той же папке или месте, что и ваш файл .py. Я не понимаю, откуда вы взяли mouse_r.

ответ дан 19 авг.

На данный момент могу порекомендовать 2 варианта. Удалите pygame полностью и переустановите, используя эту ссылку здесь: lfd.uci.edu/

gohlke/pythonlibs/#pygame . где вы можете получить pygame для python 3.3.0 . Откройте свои изображения в редакторе изображений (xnView) и сохраните как тип изображения bmp, чтобы вы могли без проблем загрузить в pygame — Грег Пекори

С изображениями в формате bmp? Если вы запускаете оболочку Python, import pygame , и запустите функцию pygame.image.get_extended() какой номер он возвращает? — Грег Пекори

Это должно быть правильно. Возвращаемое значение 1 указывает, что вы должны иметь возможность загружать все форматы изображений. Боюсь, я не понимаю, в чем проблема. — Грег Пекори

Возможно, вы использовали здесь неправильное имя переменной:

Я смотрел тот же учебник раньше и кажется, что mouse_r должно быть mouse_c .

Попробуйте использовать полное имя каталога при загрузке изображений:

ответ дан 19 авг.

Кажется, настоящая проблема здесь в том, что pygame не поддерживает формат jpeg, так как код в моем ответе тоже не работает. В документации Pygame указано, что pygame будет поддерживать только типы изображений bmp, если не построен с полной поддержкой изображений. Но это не проблема ни меня, ни многих других. Вопрос в том, почему? — Грег Пекори

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками python image pygame exit or задайте свой вопрос.

Источник

test_load_extended cannot load tiff and webp: Unsupported image format about pygame HOT 7 CLOSED

what result do you get on this platform when you run:

in the python console?

I suspect this platform is running through the arm 64 blitter path in SDL2 which produce slightly different results, if you look at the existing test that is failing we already skip this test for platforms with a name of ‘arm’ or ‘aarch64’. I expect we need to add whatever this one is to the skip list.

If someone wants to do an even fancier fix they could add a second test for the SDL2’s alpha blitters that tests just these platforms and their slightly-off blitting results — but it might not be worth it if SDL2 changes these blitting paths in the future to match the existing ones for other platforms.

alexfanqi commented on January 16, 2023

this gives me ‘riscv64’

It is an emerging architecture with lots’ of prospect and already supported by major distros like Ubuntu. FWIW, recently its vector/simd instruction spec had been ractified, but probabily will take a bit longer to match arm’s NEON.

I suspect this platform is running through the arm 64 blitter path in SDL2 which produce slightly different results, if you look at the existing test that is failing we already skip this test for platforms with a name of ‘arm’ or ‘aarch64’. I expect we need to add whatever thisone is to the skip list.

indeed it fixed the issue after adding riscv to skipIf in test_surface for 2.0.0.

alexfanqi commented on January 16, 2023

With the skip list, 2.0.1 and main branch still has AssertionError: Something went wrong in the Test Machinery: total: 1608 != untrusty_total: 1607

ankith26 commented on January 16, 2023

Can you test on the newly released pygame v2.0.2, does the issue reproduce with that as well?

alexfanqi commented on January 16, 2023

Tested on v2.0.2 with previous hardware. The assertion error is still reproduced. Blitter tests failure are also there, so I skipped them like arm.
I then connected a Radeon graphics card. The assertion error goes away. Not sure if it is the pygame.tests.video_test failed, previously on 2.0.1 and 2.0.2 it didn’t show the output of a long series of dots and ‘x’ ‘s’ ‘F’s.

robertpfeiffer commented on January 16, 2023

I don’t think any of us has riscv hardware to test on, apart from the odd soldering iron microcontroller that obviously can’t run a full OS. I don’t know if any of the core developers even has an ARM64 machine (like an M1 mac or an RPi 400).

As far as I know, there is currently no code specific to RISCV in PyGame or SDL. PyGame is mostly being developed on PowerPC, ARMv7, and x86-64. Maybe we need a way to compile everything in a pure-C mode, to see how it would run on a novel architecture. I don’t know if there is any code specific to PowerPC either.

There’s a chance this bug is caused by something in SDL2, or only happens with specific compiler settings. We’d probably need a way to compile and run Python and PyGame in qemu to test that. What compiler did you use? I assume because you use gentoo, you used the same compiler and the same compiler flags for the Linux Kernel, Python, SDL2, and Pygame.

alexfanqi commented on January 16, 2023

Okay, turns out test_video requires opengl and I am testing it headless with the dummy driver. This is not specific to riscv, other arches including amd64 also report similar issue. https://bugs.gentoo.org/790113. Can we skip test_video if SDL_VIDEODRIVER=dummy is present?

update: I reproduced this on amd64 headless without opengl and with pygame version 2.1.2. I was previously wrong about test_video. This time, I comment out that assertion and run the test with python -m pygames.tests -dv . It turns out to be image_test failed silently.

update 1: sorry, it is a downstream issue. sdl2-image was not compiled with tiff or webp support

Источник

Game fails at start #4

pygame 2.0.0.dev1 (SDL 1.2.15, python 3.6.8)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File «launch.py», line 10, in
main()
File «launch.py», line 5, in main
app = Application()
File «/home/gostkin/Documents/path_of_pain/myenv/lib/python3.6/site-packages/path_of_pain_daily_build-0.0.2.dev0-py3.6.egg/path_of_pain/src/states/application.py», line 21, in init
pygame.error: Unsupported image format

The text was updated successfully, but these errors were encountered:

Wait, did you install a built package for Pypi ant tried to launch it instead of instructuon in README?

I’ve set up virtualenv, run setup.py, then run launch.py

And please, provide a clear instruction in README. That is essential for every project.

I forgot to mention that package building isn’t ready yet

Oh, it seems like I was unconcious when I wrote last version of README, I’ll fix it in a moment

And please, provide a clear instruction in README. That is essential for every project.

Actually no idea why this happens. Try my fix that makes pygame use absolute paths for assets opening instead of relative ones. If it doesn’t work, see what is the value of const.IMG_PATH

And why are you using development version of pygame? May be the problem is in this, try stable verson 1.9.6 or 1.9.5

Источник

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

Понравилась статья? Поделить с друзьями:
  • Pygame error failed loading libvorbisfile 3 dll не найден указанный модуль
  • Pycharm ошибка интерпретатора
  • Pycharm как изменить цветовую схему
  • Sc551 00 ricoh ошибка
  • Sc500 ошибка ricoh mp2000