11

Python's Pillow doesn't seems to support AVIF files yet, and other packages like pyheif, only support reading. Is there any Python tool to convert jpg images to the new avif format?

Ander
  • 5,093
  • 7
  • 41
  • 70

3 Answers3

8

You can to do this with pillow and pillow-avif-plugin:

from PIL import Image
import pillow_avif

JPGimg = Image.open(<filename> + 'jpg')
JPGimg.save(<filename> + '.AVIF','AVIF')

You need to install pillow AVIF to do that.

pip install pillow-avif-plugin

Renza Polza
  • 87
  • 1
  • 8
  • Does it need the line `import pillow_avif`? Doesn't seems to be used. – Ander Oct 14 '21 at 07:54
  • Yes. Pillow use functions from this library to work with AVIF files. This is plugin's work. (I think Pillow try to use function by the text the user get into, and if no function has this name Pillow return error) – Dov Wachtfogel Oct 14 '21 at 08:01
  • In short, pillow use pillow_avif – Dov Wachtfogel Oct 14 '21 at 08:07
  • Seems to work on OS X, @Dov Wachtfogel, have you managed to make it work on a Linux Alpine or Debian image? I have created a Docker image using python:3.7.12-alpine3.14 and RUN apk add --no-cache jpeg-dev libwebp-dev libavif-dev but when I run your sample code it retrieves RuntimeError: Failed to encode image: No codec available I guess it is some missing dependency, but no idea how to fix it. – – Ander Oct 14 '21 at 15:37
1

The best I could come with so far was installing libavif:

brew install libavif

And encode the jpg files directly by executing the avif encoder:

import subprocess


input_file = '/some-path/file1.jpg'
output_file = '/some-path/file1.avif'
subprocess.run(f"avifenc --min 0 --max 63 -a end-usage=q -a cq-level=18 -a tune=ssim {input_file} {output_file}", shell=True)


The options --min 0 --max 63 -a end-usage=q -a cq-level=18 -a tune=ssim are some recommended settings for AVIF images.

Ander
  • 5,093
  • 7
  • 41
  • 70
0

As far as I know, there is no support for 'avif' right now. But there are API supports. For example, this API is doing well. Maybe security issues could occur. The website doesn't look good, but functionally doing well.

I've checked up API source code a little, and I found out that you could make this conversion without needing this API. API is using magick command to make this conversion. I don't know how to use this command, but I think you could figure it out if you search a little, or check out the source code.

munir.aygun
  • 414
  • 1
  • 4
  • 11