Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- I need to save one image than I need to crop it on many images and save to the FK model.
- I decided to use post_save signal to save each cropped image.
- models.py
- class Map(models.Model):
- id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
- title = models.TextField()
- image = models.ImageField(upload_to='map', null=True, blank=True)
- class Meta:
- verbose_name = _('Map')
- verbose_name_plural = _('Maps')
- def __str__(self):
- return str(self.id)
- class Tile(models.Model):
- map = models.ForeignKey(Map)
- x = models.IntegerField()
- y = models.IntegerField()
- z = models.IntegerField()
- tile = models.BinaryField(blank=True, null=True)
- image = models.ImageField('Tile Image', upload_to='map', null=True, blank=True)
- @classmethod
- def create(cls, map, x, y, z, tile, image):
- tile = cls(map=map, x=x, y=y, z=z, tile=tile, image=image)
- tile.save()
- signals.py
- @receiver(post_save, sender=Map)
- def map_saver(sender, instance, k=0, **kwargs):
- import time
- from PIL import Image
- try:
- from StringIO import StringIO
- except ImportError:
- from io import StringIO
- from io import BytesIO
- from django.core.files.base import ContentFile
- from django.core.files.temp import NamedTemporaryFile
- path = f'{settings.MEDIA_ROOT}{instance.image}'
- im = Image.open(path)
- x = im.size[0]
- y = im.size[1]
- for i in range(0,x,256):
- for j in range(0,y,256):
- box = (j, i, j+256, i+256)
- try:
- a = im.crop(box)
- box = list(box)
- for id, item in enumerate(box):
- item = item // 256
- box[id] = item
- thumb_io = BytesIO()
- a.save(thumb_io, format='JPEG')
- image = ContentFile(thumb_io.getvalue())
- # Tile.create(map=instance, x=box[0], y=box[3], z=k, tile=None, image=image)
- It doesn't work.
- except:
- pass
- k +=1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement