Skip to content

Commit

Permalink
v1.0 changes
Browse files Browse the repository at this point in the history
  • Loading branch information
weiztech committed Jul 6, 2019
1 parent 08992d5 commit 0d25f7e
Show file tree
Hide file tree
Showing 6 changed files with 59 additions and 22 deletions.
18 changes: 14 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,18 @@
# PyMODM-ImageFileField
ImageFileField for PyMODM

Configuration Media Path and Media Url
```
import imagefilefield
# Required
imagefilefield.FILEFIELD_MEDIA_PATH = os.path.join(BASE_DIR, "media/")
# Optional
imagefilefield.FILEFIELD_MEDIA_URL = "/media/" # Default Value
```


```
from os.path import join
Expand All @@ -19,8 +31,7 @@ class TestImage(MongoModel):
text = fields.CharField()
image = ImageFileField(
upload_to=join(MEDIA_ROOT, "test_image/%Y/%m/%d/"),
blank=True,
media_url=join(MEDIA_URL, "test_image/%Y/%m/%d/"))
blank=True)
# using custom size
image2 = ImageFileField(
upload_to=join(MEDIA_ROOT, "test_image/%Y/%m/%d/"),
Expand All @@ -29,8 +40,7 @@ class TestImage(MongoModel):
"small": {"size": (200, 100), "smartcrop": True},
"medium": {"size": (525, 625), "smartcrop": True},
"big": {"size": (700, 700), "smartcrop": True}
}
media_url=join(MEDIA_URL, "test_image/%Y/%m/%d/"))
})
created = fields.DateTimeField(default=timezone.now)
```
2 changes: 2 additions & 0 deletions imagefilefield/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
FILEFIELD_MEDIA_PATH = None
FILEFIELD_MEDIA_URL = "/media/"
17 changes: 16 additions & 1 deletion imagefilefield/fields.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,41 @@
from pymodm.fields import ImageField

from imagefilefield.files import ImageFieldToFile
import imagefilefield


class ImageFileField(ImageField):
_wrapper_class = ImageFieldToFile

@property
def base_media_path(self):
return imagefilefield.FILEFIELD_MEDIA_PATH

@property
def base_media_url(self):
return imagefilefield.FILEFIELD_MEDIA_URL

def __init__(self, *args, **kwargs):
# add custom params upload_to
if not kwargs.get("upload_to"):
raise ValueError("upload_to params is required")
self.upload_to = kwargs.pop("upload_to")
self.image_sizes = kwargs.pop("image_sizes", None)
self.media_url = kwargs.pop("media_url", "/media/")
super().__init__(*args, **kwargs)

def to_mongo(self, value):
file_obj = self.to_python(value)
# Save the file and return its name.
if not file_obj._committed:
if not self.base_media_path:
raise ValueError("imagefilefield.FILEFIELD_MEDIA_PATH cannot be none")

file_obj.save(value.file_id, value)

# load saved gridfs files data from storage
# for make the data available to next process
file_obj.file = file_obj.storage.open(file_obj.file_id)

# create image with specific sizes settings
file_obj.create_image_sizes()

Expand Down
36 changes: 22 additions & 14 deletions imagefilefield/files.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from os import path, makedirs
from typing import Tuple, Union
from io import BytesIO
from datetime import datetime

from PIL import Image
from pymodm.files import ImageFieldFile
Expand All @@ -11,31 +10,39 @@

class ImageFieldToFile(ImageFieldFile):

def generate_image_path(self, key_size, base_path):
'''
return full image path
'''
media_path = path.join(
base_path,
self.field.upload_to,
"{}_{}.{}".format(key_size, str(self.file_id), self.image.format.lower()))
media_path = ("{:%s}" % (media_path)).format(self.file.uploadDate)
return media_path

@property
def images(self):
'''
return url created images base on defined sizes
'''
sizes = self.get_sizes
media_url = self.field.media_url
images = {}

for key in sizes.keys():
media_path = path.join(
media_url,
"{}_{}.{}".format(key, str(self.file_id), self.image.format.lower()))
media_path = ("{:%s}" % (media_path)).format(self.file.uploadDate)
images[key] = media_path
images[key] = self.generate_image_path(key, self.field.base_media_url)
return images

@property
def get_sizes(self):
'''
return the specified image sizes
'''
return self.field.image_sizes or getattr(self.instance, "IMAGE_SIZES", None)

def create_image_path(self, key: str) -> str:
# file path
fpath = path.join(
self.field.upload_to,
"{}_{}.{}".format(key, str(self.file_id), self.image.format.lower()))
fpath = "{:%s}" % (fpath)
fpath = fpath.format(datetime.utcnow())
fpath = self.generate_image_path(key, self.field.base_media_path)
# try create folder path if not exists
folder_path = "/".join(fpath.split("/")[:-1])
try:
Expand All @@ -46,16 +53,17 @@ def create_image_path(self, key: str) -> str:
return fpath

def image_to_file(self, key: str, size: Tuple[int, int],
image_path: str=None, smartcrop: bool = False) -> str:
image_path: Union[BytesIO, str, None]=None,
smartcrop: bool = False) -> str:
'''
method for convert image to desired size
image: image binary file or image buffer
size: (width, height)
smart_crop: if not active will only use PIL `thumbnail` resizer
'''
fpath = self.create_image_path(key)

# image data could be path file or BytesIo data
image_data: Union[BytesIO, str]
if image_path:
image_data = image_path
else:
Expand Down
4 changes: 3 additions & 1 deletion imagefilefield/smartcrop.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,7 @@ def smart_crop(image, target_width, target_height, destination, do_resize):

crop_pos = exact_crop(center, width, height, target_width, target_height)

cropped = original[int(crop_pos['top']): int(crop_pos['bottom']), int(crop_pos['left']): int(crop_pos['right'])]
cropped = original[
int(crop_pos['top']): int(crop_pos['bottom']),
int(crop_pos['left']): int(crop_pos['right'])]
cv2.imwrite(destination, cropped)
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from setuptools import setup

setup(name='PYMODM-IMAGEFILEFIELD',
version='0.1',
version='1.0',
description='ImageFileField for PyMODM module',
url='https://github.com/weiztech/PyMODM-ImageFileField',
author='Jensen',
Expand All @@ -13,4 +13,4 @@
'opencv-python>=3.4.0.12'
],
keywords='ImageFileField PyMODM-ImageFileField',
zip_safe=False)
zip_safe=False)

0 comments on commit 0d25f7e

Please sign in to comment.