Files
penracourses/helpers/images.py
T
2021-02-13 20:13:57 +00:00

57 lines
1.7 KiB
Python

import base64
import mimetypes
from io import BytesIO
from PIL import Image, ImageFile
import pydicom
from .pydicom_PIL import get_PIL_image
def image_as_base64(image_file):
"""
:param `image_file` for the complete path of image.
:param `format` is format for image, eg: `png` or `jpg`.
"""
# if not os.path.isfile(image_file):
# return None
encoded_string = ""
# with open(image_file, 'rb') as img_f:
# encoded_string = base64.b64encode(img_f.read())
encoded_string = base64.b64encode(image_file.file.read())
mimetype, enc = mimetypes.guess_type(image_file.path)
return "data:image/{};base64,{}".format(mimetype, encoded_string.decode("utf-8"))
def pil_dicom_image(source, exif_orientation=True, **options):
"""
Try to open the source file directly using PIL, ignoring any errors.
exif_orientation
If EXIF orientation data is present, perform any required reorientation
before passing the data along the processing pipeline.
"""
# Use a BytesIO wrapper because if the source is an incomplete file like
# object, PIL may have problems with it. For example, some image types
# require tell and seek methods that are not present on all storage
# File objects.
#if not source:
# return
#source = BytesIO(source.read())
ds = pydicom.read_file("filename")
image = get_PIL_image(ds)
#with Image.open(source) as image:
# # Fully load the image now to catch any problems with the image contents.
# try:
# ImageFile.LOAD_TRUNCATED_IMAGES = True
# image.load()
# finally:
# ImageFile.LOAD_TRUNCATED_IMAGES = False
#if exif_orientation:
# image = utils.exif_orientation(image)
return image