Convert .heic to png media object

I was banging my head trying to figure it out and use stackoverflow to save me, so here it is!

These files are uploaded by my user’s who take “live” photos on Iphones.


#SERVER SIDE CODE
import anvil.media
import pyheif
from PIL import Image

def convert_heic_to_png(media):
  with anvil.media.TempFile(media) as file_name:
    with open(file_name, 'rb') as file:
      heif_file = pyheif.read_heif(file)
      image = Image.frombytes(
        heif_file.mode, 
        heif_file.size, 
        heif_file.data,
        "raw",
        heif_file.mode,
        heif_file.stride,
        )
      image.save("/tmp/file.png","PNG")

      new_file = anvil.media.from_file("/tmp/file.png", "image/png", f"{media.name.split('.')[0]}.png")
      return new_file
6 Likes