71 lines
2.1 KiB
Python
71 lines
2.1 KiB
Python
import base64
|
|
import mimetypes
|
|
|
|
from io import BytesIO
|
|
|
|
from PIL import Image, ImageFile
|
|
|
|
import pydicom
|
|
|
|
try:
|
|
from .pydicom_PIL import get_PIL_image
|
|
except:
|
|
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)
|
|
if "dicom" in mimetype:
|
|
return "data:{};base64,{}".format(mimetype, encoded_string.decode("utf-8"))
|
|
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())
|
|
|
|
# open file with pydicom
|
|
ds = pydicom.read_file(source)
|
|
|
|
# return the image file
|
|
return 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)
|
|
|
|
|
|
|
|
def show_PIL(dataset):
|
|
"""Display an image using the Python Imaging Library (PIL)"""
|
|
im = get_PIL_image(dataset)
|
|
im.show() |