# HG changeset patch # User ymh # Date 1529073957 -7200 # Node ID 3e48e2e2c0ce4ca01dfd4a9af845467f8d3ca243 # Parent 2c172934dae26daed54cfe9e53f810f444dcc0bc Create a generic import image command diff -r 2c172934dae2 -r 3e48e2e2c0ce src/iconolab/management/commands/importimages.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/iconolab/management/commands/importimages.py Fri Jun 15 16:45:57 2018 +0200 @@ -0,0 +1,90 @@ +import json +import os +import shutil + +from django.conf import settings +from django.core.management.base import BaseCommand +from PIL import Image as ImagePIL +from sorl.thumbnail import get_thumbnail + +from iconolab.models import Image, ImageStats, Item, ItemMetadata + + +class BaseImportImagesCommand(BaseCommand): + + def handle(self, *args, **options): + raise NotImplementedError + + def create_item_and_metadata( + self, + natural_key, + collection, + metadata_dict, + image_files, + options, + source_dir, + target_dir + ): + print('#### Creating item '+natural_key+' (natural key) in database') + item_object = Item.objects.create( + collection=collection + ) + + ItemMetadata.objects.create( + item=item_object, + metadata=json.dumps(metadata_dict), + natural_key=natural_key + ) + + print('#### Computing item image(s)') + for image in image_files: + (image_name, ext) = os.path.splitext(image) + if options.get('no-jpg-conversion') or ext in settings.NO_IMG_CONVERSION_EXTS: + print('##### Copying file '+str(image)+' without converting') + image_path = os.path.join(target_dir, image) + new_image_name = image + shutil.copy(os.path.join(source_dir, image), target_dir) + try: + im = ImagePIL.open(os.path.join(target_dir, image)) + im_width, im_height = im.size + except Exception as e: + print(e) + continue + else: + image_path = os.path.join(target_dir, image_name) + '.jpg' + new_image_name = image_name+'.jpg' + if os.path.isfile(image_path): + print('##### A jpeg file already exists in target dir for ' + image) + try: + im = ImagePIL.open(image_path) + im_width, im_height = im.size + except Exception as e: + print(e) + continue + else: + jpeg_img_path = image_path + try: + im = ImagePIL.open(os.path.join(source_dir, image)) + print('##### Generating or copying jpeg for '+image) + im.thumbnail(im.size) + im.save(jpeg_img_path, 'JPEG', quality=options.get( + 'jpeg_quality', settings.IMG_JPG_DEFAULT_QUALITY)) + im_width, im_height = im.size + except Exception as e: + print(e) + continue + new_image = Image.objects.create( + item=item_object, + media='uploads/'+new_image_name, + name=new_image_name, + height=im_height, + width=im_width + ) + ImageStats.objects.create( + image=new_image + ) + print('### Generating thumbnails for item '+natural_key) + for image in item_object.images.all(): + for size in settings.PREGENERATE_THUMBNAILS_SIZES: + print('#### Thumbnail for size '+size) + get_thumbnail(image.media, size, crop=False)