def remove_thumbnail(sender, instance, **kwargs): if instance.pk is None: return try: thumbnail.delete(instance.cover_page, delete_file=False) except thumbnail.helpers.ThumbnailError as err: logger.debug('instance: %s error: %s' % (instance, err))
def delete(self, request, *args, **kwargs): self.object = self.get_object() user = request.user blog_posts = BlogPost.objects.published(for_user=user).select_related().filter(user=user) if blog_posts and blog_posts[0]: blog_post = blog_posts[0] blog_post.num_images = blog_post.num_images - self.object.images.all().count() blog_post.save() for image in self.object.images.all(): delete(image.image) content_type_id = ContentType.objects.get_for_model(image).pk deleteObject(request, content_type_id, image.pk) media_root = getattr(settings, 'MEDIA_ROOT', '/') album_dir = self.object.get_album_path() album_abs_dir = os.path.join(media_root, album_dir) os.rmdir(album_abs_dir) content_type_id = ContentType.objects.get_for_model(self.object).pk deleteObject(request, content_type_id, self.object.pk) return HttpResponseRedirect(self.get_success_url())
def delete_thumbnails(self, source): from sorl.thumbnail import delete from sorl.thumbnail.helpers import ThumbnailError try: delete(source) except ThumbnailError: pass
def termination(request): form = TerminationForm() if request.method == "POST": form = TerminationForm(request.POST) if form.is_valid(): person = Person.objects.get(username=request.user) board = Board.objects.filter(user=request.user) picture = Picture.objects.filter(board=board) for p in picture: delete(p.image) p.delete() for b in board: b.delete() friend = Friend.objects.friends(person) for f in friend: Friend.objects.remove_friend(person, f) following = Follow.objects.following(request.user) for f in following: Follow.objects.remove_follower(person, f) for f in following: Follow.objects.remove_follower(person, f) requests = Friend.objects.unread_requests(user=request.user) for f in requests: f.delete() person.is_active = False person.email = None person.date_of_birth = None person.image.delete() person.save() return HttpResponseRedirect(reverse('world:logout_request')) return render(request, 'termination.html', {'form': form})
def _clear_thumbnails(self): """ Actual code to clear the thumbnails. Private. """ delete(self.image, delete_file=False) self.thumbs_created = False self.save()
def delete_old_avatar(sender, instance, **kwargs): if instance.avatar: if not str(instance.avatar).startswith('avatars'): user = instance.user profile = user.get_profile() if profile.avatar: delete(profile.avatar)
def _delete_thumbnail(self, sender, instance=None, delete_file=True, **kwargs): image = getattr(instance, self.attname) if hasattr(image, 'path'): # Use sorl.thumbnail.delete to delete thumbnail # Key Value Store references, cached files and optionally # the source image file thumbnail.delete(image.path, delete_file)
def delete_old_picture_property(file_prop, old_properties): storage = get_storage() old_value = old_properties.get(file_prop) old_storage_file_path = old_value.split(';name=')[-1].split( ';')[0] if old_value else None if old_storage_file_path: storage.delete(old_storage_file_path) delete(old_storage_file_path)
def handle(self, *args, **options): photos = Photo.objects.filter(flip=True, rephoto_of__isnull=True) # print photos.count() for p in photos: # print p.id photo_path = settings.MEDIA_ROOT + "/" + str(p.image) img = Image.open(photo_path) flipped_image = img.transpose(Image.FLIP_LEFT_RIGHT) flipped_image.save(photo_path) delete(p.image, delete_file=False)
def delete(self): # deleting the associated file # trying sorl before file system try: from sorl.thumbnail import delete delete(self.file.file) except: os.remove(self.file.path) super(SFFile, self).delete()
def delete_photo(self, path=None, unset_path=True): from .settings import DEFAULT_PHOTO_URL if not path: path = self.get_photo_full_path() if self.photo and os.path.basename(path) != os.path.basename(DEFAULT_PHOTO_URL): os.remove(path) delete(self.photo, delete_file=True) if unset_path: self.photo = None self.save()
def test_edit_post_with_image(self): self.client.force_login(self.user) new_post = Post.objects.create(text=str(uuid1()), author=self.user) with self.create_temp_text_file() as text_file: response = self.client.post( f'/{self.user.username}/{new_post.id}/edit/', {'text': str(uuid1()), 'image': text_file}) self.check_image_error( response, 'При редактировании сообщения не работает проверка формата изображения.') text_file.close() delete(text_file)
def remove_files(sender, instance, **kwargs): for field in instance._meta.fields: if not isinstance(field, models.FileField): continue file = getattr(instance, field.name) if file and os.path.exists(file.path): try: delete(file) except OSError: pass
def auto_delete_file_on_delete(sender, instance, **kwargs): """ Deletes file from filesystem when corresponding `MediaFile` object is deleted. """ fp = instance.image_file.path fd = os.path.dirname(fp) if instance.image_file: delete(instance.image_file) #removes from cache - sorl thumbnail if len(os.listdir(fd)) == 0: os.rmdir(fd)
def delete_image_files(sender, instance, **kwargs): """ Deletes the original image, created thumbnails, and any entries in sorl's key-value store. """ image_fields = (models.ImageField, thumbnail.ImageField) for field in instance._meta.fields: if isinstance(field, image_fields): # Make Django return ImageFieldFile instead of ImageField fieldfile = getattr(instance, field.name) thumbnail.delete(fieldfile)
def auto_delete_file_on_delete(sender: UserProductImage, instance: UserProductImage, **kwargs): """ Deletes file from filesystem when corresponding `MediaFile` object is deleted. """ fp = instance.file.path fd = os.path.dirname(fp) if instance.file: thumbnail.delete(instance.file) # removes from cache - sorl thumbnail if os.path.exists(fd) and len(os.listdir(fd)) == 0: shutil.rmtree(conf.settings.MEDIA_ROOT + 'uploads/users/' + instance.user_profile.display_name, ignore_errors=True)
def edit_profile(request): inst = User_info.objects.get(user_id=request.user) form = EditProfileForm(instance=inst) img_form = UserImageForm() if request.method == 'POST': """if 'details' in request.POST: form = EditProfileForm(request.POST, instance=inst) if form.is_valid(): edit_profile_obj = form.save(commit=False) about_tags = form.cleaned_data['about_tags'] edit_profile_obj.about_tags.clear() for tag in about_tags: edit_profile_obj.about_tags.add(tag.lower()) edit_profile_obj.save() if 'location' in request.POST and request.POST.get('location'): inst.location_id = request.POST.get('location') inst.save() #edit_profile_obj.about_tags.add(*about_tags) #return HttpResponseRedirect("/accounts/add_interest/")""" if 'location' in request.POST and request.POST.get('location'): inst.location_id = request.POST.get('location') inst.save() elif 'image' in request.POST: img_form = UserImageForm(request.POST, request.FILES) if img_form.is_valid(): if 'avatar' in request.FILES: ext = request.FILES['avatar'].content_type.split('/')[1] request.FILES['avatar'].name = str( request.user) + '.' + str(ext) obj = User_info.objects.get(user_id=request.user) if obj.avatar == 'user_images/root.jpeg': delete(obj.avatar, delete_file=False) else: delete(obj.avatar) obj.avatar = request.FILES['avatar'] obj.save() else: img_form = UserImageForm() return HttpResponseRedirect("/profile/") else: form = EditProfileForm(instance=inst) img_form = UserImageForm() return render(request, "edit_profile.html", { 'form': form, 'img_form': img_form, 'user_obj': inst })
def save(self, *args, **kwargs): if not self.id: # Have to save the image (and imagefield) first super(BaseImage, self).save(*args, **kwargs) # obj is being created for the first time - resize quality = getattr(settings, 'IMAGESTORE_IMAGE_QUALITY', 95) resized = get_thumbnail(self.image, "1000x1000", quality=quality) # Delete the original image and reassign the resized image to the image field self.image.delete() self.image.save(resized.name, ContentFile(resized.read()), True) delete(resized) super(BaseImage, self).save(*args, **kwargs)
def save(self, *args, **kwargs): # On edit # Delete old thumbnails # Is the old photo the same as the new? delete(self.photo, delete_file=False) # Create new for e in self.ThumbnailModeEnum: self.getPhoto(e.getName()) super().save(*args, **kwargs)
def clean_thumbnails(self): Thumbnail.objects.filter(media=self).delete() try: delete(self.original_file.file, delete_file=False) except (IOError, ValueError): pass try: if self.custom_file: delete(self.custom_file.file, delete_file=False) except (IOError, ValueError): pass
def update(self, instance, validated_data): if instance.image != validated_data.get('image', instance.image): # 기존 image과 현재 image이 다르면 파일경로에서 기존 image 삭제 os.remove(os.path.join(settings.MEDIA_ROOT, instance.image.path)) # cached db에 있는 thumbnail도 제거 delete(instance.image) instance.word = validated_data.get('word', instance.word) instance.mean = validated_data.get('mean', instance.mean) instance.example = validated_data.get('example', instance.example) instance.save() return instance
def delete_images(sender, **kwargs): u"""Удаление изображений при удалении объявления.""" instance = kwargs['instance'] all_images = [instance.image_1, instance.image_2,instance.image_3, instance.image_4] for image in all_images: if image: try: thumbnail.delete(image) except IOError as e: logger.error(u'Не удалось удалить изображение: {0}'.format(e))
def crop(self, x=None, y=None, x2=None, y2=None): if not all((x, y, x2, y2)): raise ValueError('All points are required') file_name = self.raw_image.name im = Image.open(self.raw_image.file) cropped = im.copy() cropped = cropped.crop((x, y, x2, y2)) new_file = StringIO() cropped.save(new_file, 'jpeg') file_content = ContentFile(new_file.getvalue()) self.image.save(file_name, file_content) delete(self.image, delete_file=False)
def crop(self, x=None, y=None, x2=None, y2=None): if not all((x, y, x2, y2)): raise ValueError('All points are required') file_name = self.raw_image.name im = Image.open(self.raw_image.file) cropped = im.copy() cropped = cropped.crop((x, y, x2, y2)) new_file = BytesIO() cropped.save(new_file, 'jpeg') file_content = ContentFile(new_file.getvalue()) self.image.save(file_name, file_content) delete(self.image, delete_file=False)
def save(self, *args, **kwargs): """ Override default save operation. Username will be swapped with email. """ self.username = self.email if self.previous_avatar and self.avatar != self.previous_avatar: delete(self.previous_avatar) self.previous_avatar = None super(User, self).save(*args, **kwargs)
def delete_image_files(sender, instance, **kwargs): """ Deletes the original image, created thumbnails, and any entries in sorl's key-value store. """ image_fields = (models.ImageField, thumbnail.ImageField) for field in instance._meta.fields: if isinstance(field, image_fields): # Make Django return ImageFieldFile instead of ImageField fieldfile = getattr(instance, field.name) try: thumbnail.delete(fieldfile) except ThumbnailError: pass
def delete(self, request, *args, **kwargs): self.object = self.get_object() if self.object.image: delete(self.object.image) content_type_id = ContentType.objects.get_for_model(self.object).pk deleteObject(request, content_type_id, self.object.pk) user = request.user blog_posts = BlogPost.objects.published(for_user=user).select_related().filter(user=user) if blog_posts and blog_posts[0]: blog_post = blog_posts[0] blog_post.num_images = blog_post.num_images - 1 blog_post.save() return HttpResponseRedirect(self.get_success_url())
def delete(request, pk): if Image.objects.filter(pk=pk).exists(): img = Image.objects.get(pk=pk) from sorl.thumbnail import delete deleteHist = requests.get('http://histogram:8080/deleteHistogram/' + str(img.pk)) if deleteHist.status_code == 200: delete(img.image) img.delete() else: messages.add_message( request, messages.WARNING, 'Ошибка удаления в Lucene. Изображение не удалено') return redirect('search:all') return HttpResponse(status=204)
def _delete_thumbnail(self, sender, instance=None, delete_file=True, **kwargs): image = getattr(instance, self.attname) if hasattr(image, 'path'): # Use sorl.thumbnail.delete to delete thumbnail # Key Value Store references, cached files and optionally # the source image file if image.path.startswith(settings.MEDIA_ROOT): thumbnail.delete(image.path[len(settings.MEDIA_ROOT):], delete_file) else: thumbnail.delete(image.path, delete_file)
def cat_photo(request, photo_id=None, thumb_size=600, slug=None): p = get_object_or_404(CatPhoto, id=photo_id) thumb_str = str(thumb_size) + 'x' + str(thumb_size) im = get_thumbnail(p.image, thumb_str, upscale=False) try: content = im.read() except IOError: delete(im) im = get_thumbnail(p.image, thumb_str, upscale=False) content = im.read() response = HttpResponse(content, content_type='image/jpg') response['Content-Length'] = len(content) return response
def cat_album_thumb(request, album_id, thumb_size=250): a = CatAlbum.objects.filter(pk=album_id).first() random_image = a.photos.order_by('?').first() thumb_str = str(thumb_size) + 'x' + str(thumb_size) im = get_thumbnail(random_image.image, thumb_str, upscale=False) try: content = im.read() except IOError: delete(im) im = get_thumbnail(random_image.image, thumb_str, upscale=False) content = im.read() response = HttpResponse(content, content_type='image/jpg') response['Content-Length'] = len(content) return response
def auto_delete_image_file_on_delete(sender: ArtisanForumProfile, instance: ArtisanForumProfile, **kwargs): """ Deletes file from filesystem when corresponding `MediaFile` object is deleted. Typed to SafeImageField as a test (should be ImageField) """ if instance.image_file: fp = instance.image_file.path fd = os.path.dirname(fp) if instance.image_file: if os.path.isfile(fp): try: thumbnail.delete(instance.image_file) if len(os.listdir(fd)) == 0: shutil.rmtree(conf.settings.MEDIA_ROOT + '/' + instance.user_profile.display_name, ignore_errors=True) except exceptions.ObjectDoesNotExist as e: logger.error("Error deleting image file : {0}".format(e))
def auto_delete_file_on_change(sender, instance, **kwargs): """ Deletes old file from filesystem when corresponding `MediaFile` object is updated with new file. """ if not instance.pk: return False try: old_file = sender.objects.get(pk=instance.pk).photo except sender.DoesNotExist: return False new_file = instance.photo if not old_file == new_file: delete(old_file.path)
def post_save_task(instance): # logger.info(instance.get_cropping_method_display()) if instance.cropping_method == instance.CROP_PENDING: logger.info('autocrop') left, top, diameter, method = autocrop(instance) instance.cropping_method = method instance.cropping = (left, top, diameter) assert instance.cropping_method != instance.CROP_PENDING instance.save(update_fields=( 'from_top', 'from_left', 'cropping_method', 'crop_diameter')) else: logger.info('rebuild thumbs') # delete thumbnail thumbnail.delete(instance.source_file, delete_file=False) # rebuild thumbnail instance.thumb()
def test_new_post_with_image(self): self.client.force_login(self.user) with self.create_temp_text_file() as text_file: response = self.client.post( '/new/', {'text': 'test', 'image': text_file}) self.check_image_error( response, 'При отправке нового сообщения не работает проверка формата изображения.') text_file.close() delete(text_file) with self.create_temp_image_file() as image_file: new_post = Post.objects.create( text=str(uuid1()), author=self.user, image=image_file.name) self.post_check(new_post) image_file.close() delete(image_file)
def form_valid(self, form): ensure_branding_directory_exists() dest_name = get_branding_disk_file(self.get_destination_filename()) if os.path.exists(dest_name): delete( os.path.join('kanisa', 'branding', self.get_destination_filename())) with open(dest_name, 'wb') as destination: for chunk in form.files['image'].chunks(): destination.write(chunk) messages.success(self.request, ('Image updated - changes may take ' 'a few minutes to take effect.')) return super(BrandingManagementUpdateView, self).form_valid(form)
def rotate(self, rotate_angle): """ Make sure we rotate both images. """ if not self.raw_image: self.raw_image = self.image self.raw_image.save() for image_field in ( # self.raw_image, self.image, ): file_name = image_field.name im = Image.open(image_field.file) rotated = im.copy() rotated = rotated.rotate(rotate_angle) new_file = BytesIO() rotated.save(new_file, 'jpeg') file_content = ContentFile(new_file.getvalue()) image_field.save(file_name, file_content) delete(self.image, delete_file=False)
def auto_delete_file_on_change(sender: UserProductImage, instance:UserProductImage, **kwargs): """ Deletes old file from filesystem when corresponding `MediaFile` object is updated with new file. """ if not instance.pk: return False try: old_image_field = UserProductImage.objects.get(pk=instance.pk) except UserProductImage.DoesNotExist as e: logger.info("New UserProductImage being installed?: {0}".format(e)) return False new_file = instance.file if not old_image_field.file == new_file: if os.path.isfile(old_image_field.file.path): thumbnail.delete(old_image_field) # clear thumbs from cache os.remove(old_image_field.file.path)
def auto_delete_file_on_change(sender, instance, **kwargs): """ Deletes old file from filesystem when corresponding `MediaFile` object is updated with new file. """ if not instance.pk: return False try: old_image_field = UserProductImage.objects.get(pk=instance.pk) except UserProductImage.DoesNotExist: return False new_file = instance.image_file if not old_image_field.file == new_file: if os.path.isfile(old_image_field.file.path): delete(old_image_field) # clear thumbs from cache os.remove(old_image_field.file.path)
def form_valid(self, form): ensure_branding_directory_exists() dest_name = get_branding_disk_file(self.get_destination_filename()) if os.path.exists(dest_name): delete(os.path.join('kanisa', 'branding', self.get_destination_filename())) with open(dest_name, 'wb') as destination: for chunk in form.files['image'].chunks(): destination.write(chunk) messages.success(self.request, ('Image updated - changes may take ' 'a few minutes to take effect.')) return super(BrandingManagementUpdateView, self).form_valid(form)
def remove_old_files(sender, instance, **kwargs): if not instance.id: return try: old_instance = instance.__class__.objects.get(id=instance.id) except instance.DoesNotExist: return for field in instance._meta.fields: if not isinstance(field, models.FileField): continue old_file = getattr(old_instance, field.name) new_file = getattr(instance, field.name) if old_file and old_file != new_file and os.path.exists(old_file.path): try: delete(old_file) except OSError: pass
def test_delete(self): im1 = Item.objects.get(image='100x100.jpg').image im2 = Item.objects.get(image='500x500.jpg').image default.kvstore.get_or_set(ImageFile(im1)) # exists in kvstore and in storage self.assertTrue(bool(default.kvstore.get(ImageFile(im1)))) self.assertTrue(ImageFile(im1).exists()) # delete delete(im1) self.assertFalse(bool(default.kvstore.get(ImageFile(im1)))) self.assertFalse(ImageFile(im1).exists()) default.kvstore.get_or_set(ImageFile(im2)) # exists in kvstore and in storage self.assertTrue(bool(default.kvstore.get(ImageFile(im2)))) self.assertTrue(ImageFile(im2).exists()) # delete delete(im2, delete_file=False) self.assertFalse(bool(default.kvstore.get(ImageFile(im2)))) self.assertTrue(ImageFile(im2).exists())
def upload_photo(request, eb_id=None, id=None): if id: attendee = get_object_or_404(Attendee, id=id) elif eb_id: attendee = get_object_or_404(Attendee, eb_id=eb_id) else: raise Exception("missing parameter") photo = request.FILES['photo'] if not photo: return HttpResponseBadRequest("missing photo") if attendee.photo: thumbnail.delete(attendee.photo.name, delete_file=False) attendee.photo.save(photo.name, photo) photo_url = attendee.photo.url return HttpResponse(json.dumps({ 'eb_id': attendee.eb_id, 'id': attendee.id, 'first_name': attendee.first_name, 'last_name': attendee.last_name, 'photo': photo_url}), mimetype='application/json')
def rotate(self, rotate_angle): """ Make sure we rotate both images. """ if not self.raw_image: self.raw_image = self.image self.raw_image.save() for image_field in ( # self.raw_image, self.image, ): file_name = image_field.name im = Image.open(image_field.file) rotated = im.copy() rotated = rotated.rotate(rotate_angle) new_file = StringIO() rotated.save(new_file, 'jpeg') file_content = ContentFile(new_file.getvalue()) image_field.save(file_name, file_content) delete(self.image, delete_file=False)
def validate_resizable(image): """Check if image can't be resized with solr-thumbnail. Some resizing backend fail to resize specific images so check is needed """ try: # if file is just uploaded then it's not saved. Save it to temp location data = image.file path = default_storage.save('tmp/' + uuid1().hex, ContentFile(data.read())) temp_file = default_storage.open(path) get_thumbnail(temp_file, "100x100") temp_file.close() delete(temp_file) except Exception, msg: if settings.DEBUG: traceback.print_exc() raise ValidationError(u"Image is corrupted: %s" % msg) else: raise ValidationError( u"Image is corrupted and can't be resized by server.")
def validate_resizable(image): """Check if image can't be resized with solr-thumbnail. Some resizing backend fail to resize specific images so check is needed """ try: # if file is just uploaded then it's not saved. Save it to temp location data = image.file path = default_storage.save( 'tmp/' + uuid1().hex, ContentFile(data.read())) temp_file = default_storage.open(path) get_thumbnail(temp_file, "100x100") temp_file.close() delete(temp_file) except Exception, msg: if settings.DEBUG: traceback.print_exc() raise ValidationError(u"Image is corrupted: %s" % msg) else: raise ValidationError( u"Image is corrupted and can't be resized by server.")
def auto_delete_file_on_change(sender, instance, **kwargs): """ Deletes old file from filesystem when corresponding `MediaFile` object is updated with new file. """ if not instance.pk: return False try: old_avatar = Avatar.objects.get(pk=instance.pk) except Avatar.DoesNotExist: return False if 'default_avatars' not in old_avatar.image_file.path: new_file = instance.image_file if not old_avatar.image_file == new_file: if os.path.isfile(old_avatar.image_file.path): try: delete(old_avatar.image_file) except ObjectDoesNotExist as i: pass
def handle(self, *args, **options): medias = Media.objects.filter(properties__width=None) for media in medias: req = requests.get(url=media.source_url, headers={'User-Agent': 'Mozilla/5.0'}, allow_redirects=True) name = urlparse(media.source_url).path.split('/')[-1] if media.properties is None: media.properties = {} if req.status_code == 200: disposition = req.headers.get("Content-Disposition") if disposition: test = disposition.split("=") if len(test) > 1: name = test[1].replace("\"", "") temp = NamedTemporaryFile(delete=True) temp.write(req.content) temp.flush() delete(media.path) media.path.save(name, File(temp)) media.save() MediaSerializer.get_sizes(media, media) else: posts = Post.objects.filter(medias=media) for post in posts: activities = Activity.objects.filter( action_object_content_type_id=29, action_object_object_id=str(post.id)) for activity in activities: media.properties["status"] = "DELETED" activity.db_status = -1 activity.save() print(activity.id) media.properties["width"] = media.path.width media.properties["height"] = media.path.width media.properties["size"] = media.path.size media.save() print(media.id)
def auto_delete_avatar_on_delete(sender, instance, **kwargs): """ Deletes Avatar from filesystem when corresponding `ForumProfile` object is deleted. """ fp = instance.avatar.image_file.path fd = os.path.dirname(fp) if instance.avatar.image_file and 'default_avatars' not in instance.avatar.image_file.path: if os.path.isfile(fp): try: delete(instance.avatar.image_file) instance.avatar.delete() if len(os.listdir(fd)) == 0: os.rmdir(fd) fdu1 = settings.MEDIA_ROOT + \ 'uploads/users/' + \ instance.display_name if os.path.isdir(fdu1): if len(os.listdir(fdu1)) == 0: os.rmdir(fdu1) except ObjectDoesNotExist as i: # TODO: log file missing pass
def delete_pdf_and_cover_page(sender, instance, **kwargs): try: thumbnail.delete(instance.cover_page, delete_file=True) except thumbnail.images.ThumbnailError: pass instance.pdf.delete(False)
def delete(self, using=None): delete(self.image) super(WallImage, self).delete(using)
def delete(self, *args, **kwargs): delete(self.file) self.file.delete(False) super(Picture, self).delete(*args, **kwargs)
def add_watermark(main_folder, image_file, path_watermark, all_size={'x':0,'x2':100,'y':0,'y2':100},opacity=0.5): if all_size['x']=="" or all_size['x2']=="" or all_size['y']=="" \ or all_size['y2']=="" or all_size['w_view']=="" or all_size['h_view']=="": return False path_to_folder = MEDIA_ROOT + main_folder result_file = WATERMARK_PREFIX + image_file path_watermark = MEDIA_ROOT + path_watermark if os.path.isfile(path_to_folder+image_file): shutil.copyfile(path_to_folder+image_file, path_to_folder+result_file) if os.path.isfile(path_to_folder+result_file): os.chmod(path_to_folder+result_file, 0755) result_file_path = path_to_folder+result_file # Открываем текущее изобразение изображение image = Image.open(result_file_path, 'r') w_orig = image.size[0] h_orig = image.size[1] w_koef = float(w_orig)/int(all_size['w_view']) h_koef = float(h_orig)/int(all_size['h_view']) x = int(int(all_size['x'])*w_koef) x2 = int(int(all_size['x2'])*w_koef) y = int(int(all_size['y'])*h_koef) y2 = int(int(all_size['y2'])*h_koef) w_watermark = x2 - x h_watermark = y2 - y if w_watermark!=0 and h_watermark!=0: watermark_size = str(w_watermark)+'x'+str(h_watermark) path_watermark = MEDIA_ROOT.replace('/media/','')+get_thumbnail(path_watermark, watermark_size, crop='center', quality=99).url # Открываем водяной знак if os.path.isfile(path_watermark): watermark = Image.open(path_watermark, 'r') assert opacity >= 0 and opacity <= 1 if opacity < 1: if watermark.mode != 'RGBA': watermark = watermark.convert('RGBA') else: watermark = watermark.copy() alpha = watermark.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(opacity) watermark.putalpha(alpha) layer = Image.new('RGBA', image.size, (0,0,0,0)) layer.paste(watermark, (x, y)) Image.composite(layer, image, layer).save(result_file_path) Image.composite(layer, image, layer).save(result_file_path) # Delete the Key Value Store reference but **not** the file. # Use this if you have changed the source delete(main_folder + result_file, delete_file=False) return result_file return False
def delete_pdf_and_cover_page(sender, instance, **kwargs): thumbnail.delete(instance.cover_page, delete_file=True) instance.pdf.delete(False)
def get(self, request,id, *args, **kwargs): gal = PGallery_Items.objects.get(pk=id) delete(gal.image) gal.delete() messages.success(request,_("Parallax Slide Deleted")) return redirect('/admin/parallax')
def delete_image_files(sender, instance, **kwargs): # delete thumbnails delete(instance.image)
def sorl_delete(**kwargs): from sorl.thumbnail import delete delete(kwargs['file'])