def handle(self, *args, **options): checked = added = 0 images = Image.objects.values_list("phash", flat=True) galleries = Gallery.objects.values_list("slug", flat=True) gallery_path = os.path.join(settings.MEDIA_ROOT, "gallery") for root, dirs, f in os.walk(gallery_path): for dir in dirs: if dir not in galleries: gallery = Gallery(name=dir) gallery.save() else: gallery = Gallery.objects.get(slug=dir) for dir_root, d, files in os.walk(os.path.join(root, dir)): for file in files: file_name = os.path.join(dir_root, file) file_image = PILImage.open(file_name) file_phash = str(phash(file_image)) checked += 1 if file_phash not in images: image = Image(phash=file_phash, gallery=gallery) image.original_image.name = file_name.replace( settings.MEDIA_ROOT, "" )[1:] image.save() self.stdout.write("Saved %s" % image.original_image.name) added += 1 self.stdout.write("Checked %d images, added %d" % (checked, added))
def test_get_exif_data(self): ''' Tests we can extract gps data from an image ''' exif_test_image = os.path.join(settings.BASE_DIR, 'gallery/tests/exif_test.jpg') exif_test_image_destination = ''.join([ settings.MEDIA_ROOT, 'galleries/', str(self.family.id), '/', str(self.gallery.id), '/exif_test.jpg' ]) shutil.copy2(exif_test_image, exif_test_image_destination) image = Image(gallery=self.gallery, family=self.family, original_image=exif_test_image_destination) image._populate_exif_data() self.assertEqual( datetime(2014, 3, 30, 13, 18, 6).replace(tzinfo=utc), image.date_taken) self.assertEqual(True, image.latitude != 0) self.assertEqual(True, image.longitude != 0) #Clear up mess afterwards os.remove(exif_test_image_destination)
def _process_files(self, fs_filenames, root_object, root_phys_path): db_files = root_object.files.all() for file_object in db_files: if file_object.name not in fs_filenames: # if any of images under root doesn't exist -> remove it from db logger.info("scheduling file removal: " + file_object.path) self._removals.append(file_object) else: # update mtime if neeeded self._update_mtime_if_needed(file_object) # add file objects if not found on db db_filenames = {x.name for x in db_files} for missing_file in set(fs_filenames) - db_filenames: file_phys_path = os.path.join(root_phys_path, missing_file) file_mtime = get_mtime_datetime(file_phys_path) if is_jpeg(missing_file): aspect_ratio = self.get_image_aspect_ratio(file_phys_path) raw_filename = self._detect_rawfile(file_phys_path) file_object = Image(name=missing_file, directory=root_object, modification_time=file_mtime, aspect_ratio=aspect_ratio, raw_filename=raw_filename) elif is_video(missing_file): file_object = Video(name=missing_file, directory=root_object, modification_time=file_mtime) else: raise Exception("File should be either Image or Video" + missing_file) file_object.save() logger.info("adding file " + file_object.path)
def snap(request): if request.POST and request.is_ajax(): image_data = b64decode(request.POST.get("image_data", "")) filename = id_generator() + '.png' fh = open(settings.TMP_ROOT + filename, "wb") fh.write(image_data) fh.close() image = getImage(settings.TMP_ROOT) path = settings.TMP_ROOT + image vClase, vScore = classifyScreenshot(path) db = Image(name=filename, image=path, clase=vClase, score=vScore * 100, retrain=0) db.save() vClasif = classRetrieve() record = {} data = serializers.serialize( "json", Time.objects.filter(name=vClase, date=datetime.date.today())) record = data print(record) return HttpResponse(json.dumps({ 'clase': vClase, 'score': str(round((vScore * 100), 2)), 'classif': vClasif, 'record': record }), content_type="application/json")
class ImageTestClass(TestCase): def setUp(self): self.Name = Image(Name='yumyum') self.Description = Image(Description='Good food is therapeutic') self.name = Location(name='Kenya').save() self.cat1 = Category(types='food').save() self.new_Image = Image(Name='yumyum', Description='Good food is therapeutic', location=self.name, category=self.cat1) def test_instance(self): self.assertTrue(isinstance(self.new_Image, Image)) def test_save_method(self): self.new_Image.save_Image() images = Image.objects.all() self.assertTrue(len(images) > 0) def tearDown(self): Image.objects.all().delete() def test_image_update(self): self.new_Image.save_Image() self.newimage = Image.objects.filter(Name='yumyum').update( Description='Best food') self.image_updated = Image.objects.filter(Name='yumyum') self.assertEqual(self.image_updated.Name, 'yumyum')
def test_create_tag(self): ''' Tests create tag api ''' image = Image(gallery=self.gallery, family=self.family, original_image=self.test_image_destination, thumbnail=self.test_image_destination, large_thumbnail=self.test_image_destination) image.save() self.client.login(email='*****@*****.**', password='******') response = self.client.post( '/image={0}/tags/create/'.format(self.image.id), { 'person': self.person.id, 'x1': 0.314159, 'y1': 0.1, 'x2': 0.6, 'y2': 0.2, }) self.assertEqual(200, response.status_code) tag = Tag.objects.get(x1=0.314159) self.assertEqual(self.person.id, tag.person_id) self.assertEqual(0.2, tag.y2)
def setUp(self): ''' Need to create a family and a gallery ''' self.family = Family() self.family.save() self.gallery = Gallery.objects.create(title="test_gallery", family_id=self.family.id) clear_directory(settings.FACE_RECOG_TRAIN_TEST_DIR) self.test_image = os.path.join( settings.BASE_DIR, 'facial_recognition/tests/test_image_woman.jpg') self.test_image_destination = ''.join([ settings.MEDIA_ROOT, 'galleries/', str(self.family.id), '/', str(self.gallery.id), '/test_image.jpg' ]) self.test_image_s3_key = ''.join([ 'galleries/', str(self.family.id), '/', str(self.gallery.id), '/test_image.jpg' ]) directory = ''.join([ settings.MEDIA_ROOT, 'galleries/', str(self.family.id), '/', str(self.gallery.id) ]) if not os.path.exists(directory): os.makedirs(directory) #Copy test image to media area shutil.copy2(self.test_image, self.test_image_destination) self.image = Image(gallery=self.gallery, family=self.family, original_image=''.join([ 'galleries/', str(self.family.id), '/', str(self.gallery.id), '/test_image.jpg' ])) self.image.save() self.image.upload_files_to_s3() self.person = Person(name='Wallace', gender='M', email='*****@*****.**', family_id=self.family.id, language='en') self.person.save() self.tag = Tag.objects.create(image_id=self.image.id, x1=0.279, y1=0.188, x2=0.536, y2=0.381, person_id=self.person.id, face_detected=True)
def test_person_gallery_with_auto_open_image_does_not_load_for_another_family( self): ''' Tests specified photo does not open if in another family ''' #Copy test image to media area shutil.copy2(self.test_image, self.test_image_destination) image = Image(gallery=self.gallery, family=self.another_family, original_image=self.test_image_destination, thumbnail=self.test_image_destination, large_thumbnail=self.test_image_destination) image.save p = Person.objects.create(name='badger', family_id=self.family.id) self.client.login(email='*****@*****.**', password='******') response = self.client.get('/person={0}/photos/image={1}/'.format( p.id, image.id)) self.assertEqual(404, response.status_code) image.delete_image_files()
def test_rotate_image_not_allowed_for_user_in_different_family(self): ''' Tests that user can not rotate image for another family ''' p = Person.objects.create(name='badger', family_id=self.family.id) #Copy test image to media area shutil.copy2(self.test_image, self.test_image_destination) im = Image(gallery=self.gallery, family=self.family, original_image=self.test_image_destination, thumbnail=self.test_image_destination, large_thumbnail=self.test_image_destination) im.save() tag = Tag(image_id=im.id, x1=0.5, y1=0.8, x2=0.5, y2=0.5, person_id=p.id) tag.save() self.client.login(email='*****@*****.**', password='******') response = self.client.post('/image={0}/rotate/'.format(im.id), {'anticlockwise_angle': '90'}) self.assertEqual(404, response.status_code) tag = Tag.objects.get(id=tag.id) self.assertEqual(0.5, tag.x2)
def add_images(request, id): gallery = get_object_or_404(Service, id=id, deleted=False) data = {'gallery': gallery} if request.method == 'POST': images = request.FILES new = Image(name=images['file'], service=gallery) new.save() messages.success(request, 'Imágenes subidas satisfactoriamente.') return render_to_response('galleries/add_images.html', {'data': data}, RequestContext(request))
def setUp(self): self.Name = Image(Name='yumyum') self.Description = Image(Description='Good food is therapeutic') self.name = Location(name='Kenya').save() self.cat1 = Category(types='food').save() self.new_Image = Image(Name='yumyum', Description='Good food is therapeutic', location=self.name, category=self.cat1)
def AddImage(request): if request.method == 'POST': form = AddImageForm(request.POST, request.FILES) if form.is_valid(): i=Image(title=form.cleaned_data['title'], desc=form.cleaned_data['desc'], file=form.cleaned_data['file']) i.save() return HttpResponseRedirect('/') else: form=AddImageForm() return render_to_response('form.html', {'form': form, })
def uploadImage(request): if request.method == 'POST': # images = request.FILES.getlist('images') images = request.FILES.getlist( 'files[]') # ssi-uploader插件返回的数据Key=files[] print(images) for image in images: new_img = Image(img=image) new_img.save() return HttpResponse("1") else: return render(request, 'gallery/upload.html')
def test_make_thumbnails(self): ''' Tests themake thumbnails routine ''' #Copy test image to media area shutil.copy2(self.test_image, self.test_image_destination) image = Image(gallery=self.gallery, family=self.family, original_image=self.test_image_destination) image.make_thumbnails() PIL.Image.open(settings.MEDIA_ROOT+ str(image.thumbnail)) PIL.Image.open(settings.MEDIA_ROOT + str(image.large_thumbnail)) PIL.Image.open(settings.MEDIA_ROOT +str(self.gallery.thumbnail))
def setUp(self): ''' Creates credientials as all views require login ''' self.family = Family() self.family.save() self.user = User.objects.create_user( email='*****@*****.**', password='******', name='White Queen', family_id=self.family.id) self.person = Person.objects.create(name='White Queen', family=self.family) self.person2 = Person.objects.create(name='Black Queen', family=self.family) self.gallery = Gallery.objects.create(family_id=self.family.id, title="gallery") self.test_image = os.path.join(settings.BASE_DIR, 'gallery/tests/test_image.jpg') self.test_image_destination = ''.join([ settings.MEDIA_ROOT, 'galleries/', str(self.family.id), '/', str(self.gallery.id), '/test_image.jpg' ]) directory = ''.join([ settings.MEDIA_ROOT, 'galleries/', str(self.family.id), '/', str(self.gallery.id) ]) if not os.path.exists(directory): os.makedirs(directory) #Copy test image to media area shutil.copy2(self.test_image, self.test_image_destination) self.image = Image(gallery=self.gallery, family=self.family, original_image=self.test_image_destination, thumbnail=self.test_image_destination, large_thumbnail=self.test_image_destination) self.image.save() self.another_family = Family.objects.create() self.another_user = User.objects.create_user( email='*****@*****.**', password='******', name='Queen Of Hearts', family_id=self.another_family.id)
def test_partial_update_remove_thumbnail(self): image = Image(gallery=self.gallery, family=self.family, original_image=''.join([ 'galleries/', str(self.family.id), '/', str(self.gallery.id), '/test_image.jpg' ])) image.save() client = APIClient(HTTP_X_REAL_IP='127.0.0.1') client.force_authenticate(user=self.user) url = '/api/gallery/{0}/'.format(self.gallery.id) data = { 'thumbnail_id': '', } response = client.patch(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTrue('"thumbnail":null' in response.content.decode("utf-8")) json.loads(response.content) image.delete_local_image_files() image.delete_remote_image_files()
def test_geocode_image_location_post(self): ''' Test you can geocode image view ''' #Copy test image to media area shutil.copy2(self.test_image, self.test_image_destination) im = Image( gallery=self.gallery, family=self.family, original_image=self.test_image_destination, thumbnail=self.test_image_destination, large_thumbnail=self.test_image_destination ) im.save() self.client.login(email='*****@*****.**', password='******') response = self.client.post('/image={0}/address/'.format(im.id), {'address': 'Freddie Mercury Statue Montreux Switzerland'}) im.delete_local_image_files() im.delete_remote_image_files() self.assertEqual(200, response.status_code) self.assertEqual(True, b'46.43' in response.content) self.assertEqual(True, b'6.9' in response.content) im = Image.objects.get(id=im.id) self.assertEqual(46.43, round(im.latitude,2)) self.assertEqual(6.9, round(im.longitude,1))
def test_gallery_with_auto_open_image_loads(self): ''' Tests that the gallery view loads when a photo to open by is specified ''' #Copy test image to media area shutil.copy2(self.test_image, self.test_image_destination) im = Image( gallery=self.gallery, family=self.family, original_image=self.test_image_destination, thumbnail=self.test_image_destination, large_thumbnail=self.test_image_destination ) im.save() self.client.login(email='*****@*****.**', password='******') response = self.client.get('/gallery={0}/image={1}/'.format(self.gallery.id, im.id)) im.delete_local_image_files() im.delete_remote_image_files() self.assertEqual(200, response.status_code) self.assertTemplateUsed(response, 'gallery/gallery.html')
def test_image_detail_view_does_not_load_for_another_family(self): ''' Test that the image detail view loads ''' im = Image(gallery=self.gallery, family=self.family, original_image=self.test_image_destination, thumbnail=self.test_image_destination, large_thumbnail=self.test_image_destination) im.save() self.client.login(email='*****@*****.**', password='******') response = self.client.get('/image={0}/details/'.format(im.id)) self.assertEqual(404, response.status_code)
def test_image_delete_another_family(self): ''' Tests that you can't delete another family's image ''' im = Image(gallery=self.gallery, family=self.family, original_image=self.test_image_destination, thumbnail=self.test_image_destination, large_thumbnail=self.test_image_destination) im.save() self.client.login(email='*****@*****.**', password='******') response = self.client.post('/image={0}/delete/'.format(im.id)) self.assertEqual(404, response.status_code)
def setUp(self): ''' Creates credientials as all views require login ''' self.family = Family() self.family.save() self.user = User.objects.create_user(email='arif_mardin:@queenonline.com', password='******', name='Arif Mardin:', family_id=self.family.id) self.gallery = Gallery.objects.create(family_id=self.family.id, title="gallery") self.test_image = os.path.join(settings.BASE_DIR, 'gallery/tests/test_image.jpg') self.test_image_destination = ''.join([settings.MEDIA_ROOT, 'galleries/', str(self.family.id), '/', str(self.gallery.id), '/test_image.jpg']) directory = ''.join([settings.MEDIA_ROOT, 'galleries/', str(self.family.id), '/', str(self.gallery.id)]) if not os.path.exists(directory): os.makedirs(directory) #Copy test image to media area shutil.copy2(self.test_image, self.test_image_destination) self.images = [] for i in range(0,20): self.images.append( Image( gallery=self.gallery, family=self.family, original_image=self.test_image_destination, thumbnail=self.test_image_destination, large_thumbnail=self.test_image_destination ) )
def image(file_and_save=True, **kwargs): """Return a saved image. Requires a users fixture if no creator is provided. """ u = None if 'creator' not in kwargs: u = get_user() defaults = { 'title': 'Some title', 'description': 'Some description', 'creator': u } defaults.update(kwargs) img = Image(**defaults) if not file_and_save: return img if 'file' not in kwargs: with open('apps/upload/tests/media/test.jpg') as f: up_file = File(f) img.file.save(up_file.name, up_file, save=True) return img
def test_create_thumbnail(self): ''' Tests that we can create a thumbnail ''' #Copy test image to media area shutil.copy2(self.test_image, self.test_image_destination) image = Image(gallery=self.gallery, family=self.family, original_image=''.join(['galleries/', str(self.family.id), '/', str(self.gallery.id), '/test_image.jpg'])) thumbnail = settings.MEDIA_ROOT + image._create_thumbnail((500,500)) PIL.Image.open(thumbnail) #Clear up mess afterwards os.remove(self.test_image_destination) os.remove(thumbnail)
class TagTestCase(TestCase): # pragma: no cover ''' Tests for the image class ''' def setUp(self): ''' Need to create a family and a gallery and image ''' self.family = Family() self.family.save() self.person = Person(name='Wallace', gender='M', email='*****@*****.**', family_id=self.family.id, language='en') self.person.save() self.gallery = Gallery.objects.create(title="test_gallery", family_id=self.family.id) self.test_image = os.path.join(settings.BASE_DIR, 'gallery/tests/test_image.jpg') self.test_image_destination = ''.join([settings.MEDIA_ROOT, 'galleries/', str(self.family.id), '/', str(self.gallery.id), '/test_image.jpg']) directory = ''.join([settings.MEDIA_ROOT, 'galleries/', str(self.family.id), '/', str(self.gallery.id)]) if not os.path.exists(directory): os.makedirs(directory) #Copy test image to media area shutil.copy2(self.test_image, self.test_image_destination) self.image = Image(gallery=self.gallery, family=self.family, original_image=''.join(['galleries/', str(self.family.id), '/', str(self.gallery.id), '/test_image.jpg'])) self.image.save() def test_rotate_tag(self): ''' Tests that we can rotate a tag correctly ''' tag = Tag.objects.create(image_id=self.image.id, x1=0.1, y1=0.2, x2=0.3, y2=0.4, person_id=self.person.id) tag.rotate(90) #print(tag.x1) self.assertTrue(abs(0.2 - tag.x1) < 0.0001) #print(tag.y1) self.assertTrue(abs(0.7 - tag.y1) < 0.0001) #print(tag.x2) self.assertTrue(abs(0.4 - tag.x2) < 0.0001) #print(tag.y2) self.assertTrue(abs(0.9 - tag.y2) < 0.0001)
def test_image_delete(self): ''' Tests that you can delete an image through api ''' im = Image(gallery=self.gallery, family=self.family, original_image=self.test_image_destination, thumbnail=self.test_image_destination, large_thumbnail=self.test_image_destination) im.save() self.client.login(email='*****@*****.**', password='******') response = self.client.post('/image={0}/delete/'.format(im.id)) self.assertEqual(302, response.status_code) self.assertEqual(0, Image.objects.filter(id=im.id).count())
def create_image(files, user): """Given an uploaded file, a user, and other data, it creates an Image""" up_file = files.values()[0] check_file_size(up_file, settings.IMAGE_MAX_FILESIZE) try: image = Image.objects.filter(creator=user, is_draft=True) # Delete other drafts, if any: image.exclude(pk=image[0].pk).delete() image = image[0] except IndexError: # No drafts, create one image = Image(creator=user, is_draft=True) # Async uploads fallback to these defaults. image.title = get_draft_title(user) image.description = u'Autosaved draft.' image.locale = settings.WIKI_DEFAULT_LANGUAGE up_file = _image_to_png(up_file) # Finally save the image along with uploading the file. image.file.save(os.path.splitext(up_file.name)[0] + '.png', File(up_file), save=True) (width, height) = _scale_dimensions(image.file.width, image.file.height) delete_url = reverse('gallery.delete_media', args=['image', image.id]) return { 'name': up_file.name, 'url': image.get_absolute_url(), 'thumbnail_url': image.thumbnail_url_if_set(), 'width': width, 'height': height, 'delete_url': delete_url }
def test_make_image_gallery_thumbnail(self): ''' Tests that you can assign a thumbnail to a gallery ''' im = Image( gallery=self.gallery, family=self.family, original_image=self.test_image_destination, thumbnail=self.test_image_destination, large_thumbnail=self.test_image_destination ) im.save() self.client.login(email='*****@*****.**', password='******') response = self.client.post('/image={0}/make_gallery_thumbnail/'.format(im.id)) self.assertEqual(302, response.status_code) self.assertEqual(im.thumbnail, Gallery.objects.get(id=self.gallery.id).thumbnail)
def test_image_detail_view_loads(self): ''' Test that the image detail view loads ''' im = Image(gallery=self.gallery, family=self.family, original_image=self.test_image_destination, thumbnail=self.test_image_destination, large_thumbnail=self.test_image_destination) im.save() self.client.login(email='*****@*****.**', password='******') response = self.client.get('/image={0}/details/'.format(im.id)) self.assertEqual(200, response.status_code) self.assertTemplateUsed(response, 'gallery/image_tagging.html')
def setUp(self): ''' Need to create a family and a gallery and image ''' self.family = Family() self.family.save() self.person = Person(name='Wallace', gender='M', email='*****@*****.**', family_id=self.family.id, language='en') self.person.save() self.gallery = Gallery.objects.create(title="test_gallery", family_id=self.family.id) self.test_image = os.path.join(settings.BASE_DIR, 'gallery/tests/test_image.jpg') self.test_image_destination = ''.join([ settings.MEDIA_ROOT, 'galleries/', str(self.family.id), '/', str(self.gallery.id), '/test_image.jpg' ]) directory = ''.join([ settings.MEDIA_ROOT, 'galleries/', str(self.family.id), '/', str(self.gallery.id) ]) if not os.path.exists(directory): os.makedirs(directory) #Copy test image to media area shutil.copy2(self.test_image, self.test_image_destination) self.image = Image(gallery=self.gallery, family=self.family, original_image=''.join([ 'galleries/', str(self.family.id), '/', str(self.gallery.id), '/test_image.jpg' ])) self.image.save()
def test_image_detail_update_does_not_update_for_non_whitelisted_field(self): ''' Tests that you can update a field on the image using api ''' im = Image( gallery=self.gallery, family=self.family, original_image=self.test_image_destination, thumbnail=self.test_image_destination, large_thumbnail=self.test_image_destination, title='innuendo' ) im.save() self.client.login(email='*****@*****.**', password='******') response = self.client.post('/image={0}/update/'.format(im.id), {'pk': im.id, 'name': 'id', 'value': 1}) self.assertEqual(404, response.status_code)
def search_category(request): if 'image' in request.GET and request.GET["image"]: search_term=request.GET.get("image") search_images=Image.search_by_category(search_term) message=f"{search_term}" return render(request, 'all/images.html', {"message":message, "images": search_images}) else: message="You haven't searched for any term" return render(request, 'all/images.html',{"message": message})
def snap(request): if request.POST and request.is_ajax(): image_data = b64decode(request.POST.get("image_data", "")) filename = id_generator()+'.png' fh = open(settings.TMP_ROOT + filename, "wb") fh.write(image_data) fh.close(); image = getImage(settings.TMP_ROOT) path = settings.TMP_ROOT + image vClase, vScore = classifyScreenshot(path) db = Image(name=filename, image=path, clase=vClase, score=vScore * 100, retrain=0); db.save(); vClasif = classRetrieve() return HttpResponse(json.dumps({ 'clase':vClase ,'score': str(round((vScore * 100), 2)), 'classif':vClasif }), content_type="application/json")
def merge_image_with_overlay(image, overlay, user): image = PILImage.open(image).convert('RGBA') overlay = PILImage.open(overlay).convert('RGBA') image.alpha_composite(overlay.resize(image.size)) buffer = BytesIO() image.convert('RGB').save(buffer, format="JPEG") file = ImageFile(buffer) file = Image(image=file, user=user) file.image.save('snapshot.jpg', buffer)
def test_image_face_detect(self): # Upload new image new_test_image = os.path.join( settings.BASE_DIR, 'facial_recognition/tests/test_image_woman_and_baby.jpg') new_test_image_destination = ''.join([ settings.MEDIA_ROOT, 'galleries/', str(self.family.id), '/', str(self.gallery.id), '/test_image_woman_and_baby.jpg' ]) # Copy to test area shutil.copy2(new_test_image, new_test_image_destination) new_image = Image(gallery=self.gallery, family=self.family, original_image=''.join([ 'galleries/', str(self.family.id), '/', str(self.gallery.id), '/test_image_woman_and_baby.jpg' ])) new_image.save() new_image.upload_files_to_s3() # Create a message to resize tag image_face_detect_queue_id = Queue.objects.get( name='image_face_detect').id message = Message.objects.create(queue_id=image_face_detect_queue_id, integer_data=new_image.id) image_face_detect([message]) suggested_tags = SuggestedTag.objects.filter(image_id=new_image.id) self.assertEqual(2, suggested_tags.count()) self.assertEqual(self.person.id, suggested_tags[0].person_id) new_image.delete_local_image_files() new_image.delete_remote_image_files()
def create_image(files, user): """Given an uploaded file, a user, and other data, it creates an Image""" up_file = files.values()[0] check_file_size(up_file, settings.IMAGE_MAX_FILESIZE) # Async uploads fallback to these defaults. title = get_draft_title(user) description = u'Autosaved draft.' # Use default locale to make sure a user can only have one draft locale = settings.WIKI_DEFAULT_LANGUAGE image = Image(title=title, creator=user, locale=locale, description=description) image.file.save(up_file.name, File(up_file), save=True) (width, height) = _scale_dimensions(image.file.width, image.file.height) delete_url = reverse('gallery.delete_media', args=['image', image.id]) return {'name': up_file.name, 'url': image.get_absolute_url(), 'thumbnail_url': image.thumbnail_url_if_set(), 'width': width, 'height': height, 'delete_url': delete_url}
def search_results(request): if 'image' in request.GET and request.GET["image"]: category = request.GET.get('image') searched_images = Image.search_image(category) message = f"{category}" return render(request, 'search.html', { "message": message, "images": searched_images }) else: message = "You haven't searched for any term" return render(request, 'search.html', {'message': message})
def setUp(self): ''' Creates credientials as all views require login ''' self.family = Family() self.family.save() self.user = User.objects.create_user(email='*****@*****.**', password='******', name='gromit', family_id=self.family.id) self.gallery = Gallery.objects.create(family_id=self.family.id, title="gallery") self.test_image = os.path.join(settings.BASE_DIR, 'gallery/tests/test_image.jpg') self.test_image_destination = ''.join([ settings.MEDIA_ROOT, 'galleries/', str(self.family.id), '/', str(self.gallery.id), '/test_image.jpg' ]) directory = ''.join([ settings.MEDIA_ROOT, 'galleries/', str(self.family.id), '/', str(self.gallery.id) ]) if not os.path.exists(directory): os.makedirs(directory) #Copy test image to media area shutil.copy2(self.test_image, self.test_image_destination) self.images = [] for i in range(0, 3): self.images.append( Image(gallery=self.gallery, family=self.family, title="title{0}".format(i), original_image=self.test_image_destination, thumbnail=self.test_image_destination, large_thumbnail=self.test_image_destination, latitude=i, longitude=i)) self.another_family = Family.objects.create() self.another_user = User.objects.create_user( email='*****@*****.**', password='******', name='shaun', family_id=self.another_family.id)
def create_image(files, user): """Given an uploaded file, a user, and other data, it creates an Image""" up_file = files.values()[0] check_file_size(up_file, settings.IMAGE_MAX_FILESIZE) try: image = Image.objects.filter(creator=user, is_draft=True) # Delete other drafts, if any: image.exclude(pk=image[0].pk).delete() image = image[0] except IndexError: # No drafts, create one image = Image(creator=user, is_draft=True) # Async uploads fallback to these defaults. image.title = get_draft_title(user) image.description = u'Autosaved draft.' image.locale = settings.WIKI_DEFAULT_LANGUAGE up_file = _image_to_png(up_file) # Finally save the image along with uploading the file. image.file.save(os.path.splitext(up_file.name)[0] + '.png', File(up_file), save=True) (width, height) = _scale_dimensions(image.file.width, image.file.height) delete_url = reverse('gallery.delete_media', args=['image', image.id]) return {'name': up_file.name, 'url': image.get_absolute_url(), 'thumbnail_url': image.thumbnail_url_if_set(), 'width': width, 'height': height, 'delete_url': delete_url}
def process_image(self, image_data): """ Takes the dictionary representing an image and saves it to an instance of the gallery.Image model. """ author_name = image_data['account_url'] if author_name: new = Image() new.title = image_data['title'] new.size = image_data['size'] new.hash = image_data['hash'] new.ext = image_data['ext'] # TODO: make sure all these methods are implemented correctly new.author = self.get_or_create_author(author_name) new.timestamp = self.parse_datetime(image_data['timestamp']) new.build_urls(hash) new.save() /* TO SAVE THE FILES IN DOWNLOADS FOLDER */ filename_charset = string.ascii_letters + string.digits file_save_dir = MEDIA_ROOT urllib.urlretrieve ("http://i.imgur.com/"+(new.hash),os.path.join(file_save_dir, (new.hash) + '.jpg'))
def submit_article(request): ''' View for Article Submission ''' ImageFormset = formset_factory(ImageForm, extra=settings.MAX_NUM_IMAGES) if request.method == 'POST': form = ArticleSubmissionForm(request.POST, request.FILES) image_forms = ImageFormset(request.POST, request.FILES) if form.is_valid() and image_forms.is_valid(): title = request.POST['title'] subtitle = request.POST['subtitle'] body = request.POST['body'] editor = request.POST['editor'] authors = request.POST.get('authors', []) tags = request.POST.get('tags', []) files = request.FILES post_body = EnhancedText(body, editor) #Combines body and editor field to for creating post post = None if len(files) == 0: #Will save post as basic post post = BasicPost(title=title, slug=slugify(title), subtitle=subtitle, body=post_body) post.slug = post._get_unique_slug() post.save() elif len(files) == 1: #Will save post as post with simple image image = None image = files.itervalues().next() post = PostWithSimpleImage(title=title, slug=slugify(title), subtitle=subtitle, body=post_body, image=image) post.save() else: #Will save post as post with slideshow gallery = Gallery(title=title) gallery.save() path = os.path.join(settings.MEDIA_ROOT, 'uploads') path = os.path.join(path, 'images') for index, image in enumerate(files): filename_unique = False filename = os.path.join(path, files[image].name) counter = 1 while not filename_unique: if os.path.exists(filename): filename_split = filename.split('.') filename = filename_split[0] extension = filename_split[1] filename = filename + unicode(counter) + '.' + extension else: filename_unique = True image_file = open(filename, 'wb+') for chunk in files[image].chunks(): image_file.write(chunk) image_file.close() filename_split = filename.split(os.sep) base_filename = filename_split[-1] filename = os.path.join('uploads', 'images') filename = os.path.join(filename, base_filename) image = Image(title=title, slug=slugify(title), file=filename) image.slug = image._get_unique_slug() image.save() ordered_image = OrderedImage(gallery=gallery, image=image, position=index) ordered_image.save() post = PostWithSlideshow(title=title, slug=slugify(title), subtitle=subtitle, body=post_body, gallery=gallery) post.save() if post: # Saves the authors and tags of the post for index, author in enumerate(authors): credit = OrderedCredit(credit=Credit.objects.get(id=author), content_object=post, position=index) credit.save() for index, tag in enumerate(tags): tag = TaggedItem(tag=Tag.objects.get(id=tag), object=post) tag.save() article = SubmittedArticle(submitted_by=request.user, object=post) article.save() return HttpResponseRedirect(reverse('submit_article_success')) else: form = ArticleSubmissionForm() image_forms = ImageFormset() return render_to_response('submit_article/add.html', {'form': form, 'image_forms': image_forms, 'max_forms': settings.MAX_NUM_IMAGES}, context_instance=RequestContext(request))
def process_image(self, image_data): """ Takes the dictionary representing an image and saves it to an instance of the gallery.Image model. """ author_name = image_data['account_url'] if author_name: new = Image() new.title = image_data['title'] new.size = image_data['size'] new.hash = image_data['hash'] new.ext = image_data['ext'] # TODO: make sure all these methods are implemented correctly new.author = self.get_or_create_author(author_name) new.timestamp = self.parse_datetime(image_data['timestamp']) new.build_urls() new.save() else: print "Image %(hash)s didn't have an author" % image_data