Rich Harvey
Rich Harvey

Reputation: 13

Micropython MemoryError when trying to get image from URL

Hi I’ve bought the dispay pack2 (https://shop.pimoroni.com/products/pico-display-pack-2-0?variant=39374122582099) and am trying to display an image. If I download the image and put it on the pi pico w then the image displays OK. I’m trying to get the image to be downloaded from a URL and displayed but am getting

MemoryError: memory allocation failed, allocating 21760 bytes

I’m new to this sort of coding and am struggling to see what I’m doing wrong. here is my full py code

`

import network
import urequests
import time
import picographics
import jpegdec
from pimoroni import Button



wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("SSID","password")
time.sleep(5)
print(wlan.isconnected())


display = picographics.PicoGraphics(display=picographics.DISPLAY_PICO_DISPLAY_2, rotate=0)
display.set_backlight(0.8)

# Create a new JPEG decoder for our PicoGraphics
j = jpegdec.JPEG(display)

# Open the JPEG file
#j.open_file("squid.jpg")

# Decode the JPEG
#j.decode(0, 0, jpegdec.JPEG_SCALE_FULL)

if wlan.isconnected():
    
    res = urequests.get(url='https://squirrel365.io/tmp/squid.jpg')
   
    j.open_RAM(memoryview(res.content))

    # Decode the JPEG
    j.decode(0, 0, jpegdec.JPEG_SCALE_FULL)

    # Display the result
    display.update()

` Any ideas?

Kedge

I've tested and can get plain text back from the URL, as soon as I try and get an image I get the memory error

Upvotes: 0

Views: 642

Answers (1)

larsks
larsks

Reputation: 312360

You're not doing anything "wrong"; you're just working with a device that has very limited resources. What if you re-arrange your code to perform the fetch before initializing any graphics resources, write the data to a file, and then have the jpeg module read it from disk? Something like:

import jpegdec
import network
import picographics
import time
import urequests

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("SSID","password")

while not wlan.isconnected():
    print('waiting for network')
    time.sleep(1)

res = urequests.get(url='https://squirrel365.io/tmp/squid.jpg')
with open('squid.jpg', 'wb') as fd:
    fd.write(res.content)

display = picographics.PicoGraphics(display=picographics.DISPLAY_PICO_DISPLAY_2, rotate=0)
display.set_backlight(0.8)

# Create a new JPEG decoder for our PicoGraphics
j = jpegdec.JPEG(display)

# Open the JPEG file
j.open_file("squid.jpg")

# Decode the JPEG
j.decode(0, 0, jpegdec.JPEG_SCALE_FULL)

# Display the result
display.update()

You can sometimes free up additional memory by adding an explicit garbage collection to your code:

import gc

.
.
.

with open('squid.jpg', 'wb') as fd:
    fd.write(res.content)

gc.collect()

Upvotes: 0

Related Questions