# AUTOGENERATED! DO NOT EDIT! File to edit: Images.ipynb (unless otherwise specified).

__all__ = ['imageFromS3', 'imageFromUrl', 'imageToS3', 'resizeImage', 'showImgS3']

# Cell
from io import BytesIO
from PIL import Image
from s3bz.s3bz import S3
import requests

# Cell
def imageFromS3(bucket:str, key:str, **kwargs):
  url=S3.presign(key,bucket=bucket,expiry=10, **kwargs)
  return imageFromUrl(url)


# Cell
def imageFromUrl(url):
  from io import BytesIO
  image = Image.open(BytesIO(requests.get(url).content))
  return image

# Cell
def imageToS3(image:Image, bucket:str, key:str):
  path = '/tmp/tmpImage'
  print(f'saving image to {bucket}/{key}')
  image.save(path,format='png')
  S3.saveFile(key,path,bucket)
  return True

# Cell
def resizeImage(url:str,width:int):
  from resizeimage import resizeimage
  img = imageFromUrl(url)
  resizedImg = resizeimage.resize_width(img, 200)
  return resizedImg

# Cell
def showImgS3(bucket, key):
  from matplotlib.pyplot import imshow
  import time
  imageFound = False
  while imageFound == False:
    if S3.exist( key,bucket=bucket):
      url = S3.presign(key,expiry='10',bucket=bucket)
      img = imageFromUrl(url)
      imshow(img)
      imageFound = True
    else:
      print('conversion failed or didnt happen')
      time.sleep(1)