commit ff6a649386b36704df121423995f099d068c0af9 Author: Jeena Date: Sun Jul 31 20:09:59 2022 +0900 Initial commit diff --git a/Pipfile b/Pipfile new file mode 100644 index 0000000..8ffecc4 --- /dev/null +++ b/Pipfile @@ -0,0 +1,14 @@ +[[source]] +url = "https://pypi.org/simple" +verify_ssl = true +name = "pypi" + +[packages] +pyheif = "*" +Pillow = "*" +piexif = "*" + +[dev-packages] + +[requires] +python_version = "3.10" diff --git a/README.md b/README.md new file mode 100644 index 0000000..bd5486b --- /dev/null +++ b/README.md @@ -0,0 +1,22 @@ +heic2jpeg +========= + +This script solves the problem that none of the browsers can show Apples HEIC pictures, many online services like Flickr don't allow their upload and it's also dificult to show them on the TV. + +The solution is to transcode them into JPEG, but none of the tools available would copy all the EXIF data like "Date taken" or "Orientation" so that it is impossible to sort them and there is a lot of manual work involved to rotate them manually afterwards. + +This script tries to copy as much metadata as necessary to avoid all the manual work. + +Installation +------------ + +pipenv install +pipenv shell + +Usage +----- + + ./heic2jpeg.py original.heic + +It will save the picture in the same directory, with the same name but as a JPEG and the ending `.jpeg`. + diff --git a/heic2jpeg.py b/heic2jpeg.py new file mode 100755 index 0000000..3e8da57 --- /dev/null +++ b/heic2jpeg.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 + +import sys +import io +import pyheif +import piexif +from PIL import Image +from pathlib import Path + +class Heic2Jpeg: + def __init__(self, path): + self.path = Path(path) + self.img = None + + def decodeImage(self): + self.himage = pyheif.read_heif(self.path) + self.img = Image.frombytes( + self.himage.mode, + self.himage.size, + self.himage.data, + "raw", + self.himage.mode, + self.himage.stride) + + def getExif(self): + for metadata in self.himage.metadata or []: + if metadata['type'] == 'Exif': + # pyheif.read_heif() rotates the picture + # we need to remove the Orientation from EXIF + exif_dict = piexif.load(metadata['data']) + if exif_dict["0th"] and exif_dict["0th"][piexif.ImageIFD.Orientation]: + exif_dict["0th"][piexif.ImageIFD.Orientation] = 1 + + return piexif.dump(exif_dict) + + def safe(self, quality=85): + if self.img == None: + self.decodeImage() + + self.img.save( + self.path.with_suffix('.jpg'), + format="JPEG", + quality=quality, + exif=self.getExif()) + +if __name__ == "__main__": + if len(sys.argv) != 2: + print("Usage: heic2jpeg.py path/to/picture.heic") + else: + img_path = sys.argv[1] + h2j = Heic2Jpeg(img_path) + h2j.safe()