Advertisement
Guest User

Untitled

a guest
Jan 21st, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. I need to save one image than I need to crop it on many images and save to the FK model.
  2. I decided to use post_save signal to save each cropped image.
  3.  
  4. models.py
  5. class Map(models.Model):
  6. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  7. title = models.TextField()
  8. image = models.ImageField(upload_to='map', null=True, blank=True)
  9.  
  10. class Meta:
  11. verbose_name = _('Map')
  12. verbose_name_plural = _('Maps')
  13.  
  14.  
  15. def __str__(self):
  16. return str(self.id)
  17.  
  18.  
  19. class Tile(models.Model):
  20. map = models.ForeignKey(Map)
  21. x = models.IntegerField()
  22. y = models.IntegerField()
  23. z = models.IntegerField()
  24. tile = models.BinaryField(blank=True, null=True)
  25. image = models.ImageField('Tile Image', upload_to='map', null=True, blank=True)
  26.  
  27. @classmethod
  28. def create(cls, map, x, y, z, tile, image):
  29. tile = cls(map=map, x=x, y=y, z=z, tile=tile, image=image)
  30. tile.save()
  31.  
  32.  
  33. signals.py
  34.  
  35. @receiver(post_save, sender=Map)
  36. def map_saver(sender, instance, k=0, **kwargs):
  37. import time
  38. from PIL import Image
  39. try:
  40. from StringIO import StringIO
  41. except ImportError:
  42. from io import StringIO
  43. from io import BytesIO
  44. from django.core.files.base import ContentFile
  45. from django.core.files.temp import NamedTemporaryFile
  46.  
  47. path = f'{settings.MEDIA_ROOT}{instance.image}'
  48. im = Image.open(path)
  49. x = im.size[0]
  50. y = im.size[1]
  51. for i in range(0,x,256):
  52. for j in range(0,y,256):
  53. box = (j, i, j+256, i+256)
  54.  
  55.  
  56. try:
  57. a = im.crop(box)
  58. box = list(box)
  59.  
  60. for id, item in enumerate(box):
  61. item = item // 256
  62. box[id] = item
  63.  
  64. thumb_io = BytesIO()
  65. a.save(thumb_io, format='JPEG')
  66. image = ContentFile(thumb_io.getvalue())
  67. # Tile.create(map=instance, x=box[0], y=box[3], z=k, tile=None, image=image)
  68. It doesn't work.
  69.  
  70.  
  71.  
  72. except:
  73. pass
  74. k +=1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement