Please ignore secret bonuses. Secret tests do NOT award bonus. Max hw grade is 30+2 bonus efficiency

Do you need help?

image.py modulo io e metodo _repr_png_

a
a.pietroluongo (11250 points)
20 39 131
in Programmare in python by (11.3k points)

Salve,volevo sapere come funziona il metodo _repr_png __ contenuto nel file image.py e  a cosa serve il modulo io

class Immagine:
   def __init__(self, img):
        self.pixels = img
    def _repr_png_(self):
        img = png.from_array(self.pixels, 'RGB')
        b = io.BytesIO()
        img.save(b)
        return b.getvalue()

364 views

1 Answer

andrea.sterbini (208020 points)
756 1270 2377
by (208k points)
_repr_png_ serve a fornire una immagine a ipython in modo da visualizzarla direttamente nella console.
Per convertire dal nostro formato di matrice di triple rgb all'immagine png ho usato il metodo png.from_array che crea un oggetto di tipo png.
L'oggetto BytesIO serve a creare un buffer in memoria che può essere utilizzato come se fosse un file per salvarci dentro l'oggetto png ma senza creare files.
Alla fine leggo dalla memoria il blocco di byte dell'immagine
a
a.pietroluongo (11250 points)
20 39 131
by (11.3k points)
edited by
Grazie mi trovo, ma avrei potuto usare anche with open( , 'wb') as f:
...     f.write( )
?
andrea.sterbini (208020 points)
756 1270 2377
by (208k points)
No, quello crea un file su disco