file_operation.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. # coding=utf-8
  2. import os
  3. import requests
  4. from django.conf import settings
  5. from django.utils import timezone
  6. from django.utils.deconstruct import deconstructible
  7. from PIL import Image
  8. def resizePicture(file, width):
  9. '''如果图片宽度或高度超过width,将图片宽度或高度修改为width'''
  10. try:
  11. img = Image.open(file)
  12. w, h = img.size
  13. if w > width or h > width:
  14. if w > h:
  15. size = (width, int(h * width / w))
  16. elif w < h:
  17. size = (int(w * width / h), width)
  18. else:
  19. size = (width, width)
  20. img = img.resize(size)
  21. img.save(file)
  22. except Exception as e:
  23. pass
  24. def resizePictureWith(file, width):
  25. '''如果图片宽度或高度超过width,将图片宽度或高度修改为width'''
  26. try:
  27. img = Image.open(file)
  28. w, h = img.size
  29. if w > width:
  30. size = (width, int(h * width / w))
  31. img = img.resize(size)
  32. img.save(file)
  33. except Exception as e:
  34. pass
  35. def UploadFile(file, upload_path, width=None):
  36. upload_path = PathAndRename(upload_path)
  37. filename = "%s%s.%s" % (
  38. upload_path.path,
  39. timezone.now().strftime('%Y%m%d%H%M%S%f'),
  40. file.name.split('.')[-1]
  41. )
  42. filename = filename.lower()
  43. full_filename = "%s/%s" % (settings.MEDIA_ROOT, filename)
  44. with open(full_filename, 'wb+') as destination:
  45. for chunk in file.chunks():
  46. destination.write(chunk)
  47. if width:
  48. resizePictureWith(full_filename, width)
  49. return filename
  50. def DownloadFace(url, save_path, ext):
  51. upload_path = PathAndRename(save_path)
  52. filename = "%s%s.%s" % (
  53. upload_path.path,
  54. timezone.now().strftime('%Y%m%d%H%M%S%f'),
  55. ext
  56. )
  57. filename = filename.lower()
  58. full_filename = "%s/%s" % (settings.MEDIA_ROOT, filename)
  59. response = requests.get(url)
  60. img = response.content
  61. with open(full_filename, 'wb+') as destination:
  62. destination.write(img)
  63. return filename
  64. def DeleteFile(filename):
  65. img_path = '%s/%s' % (settings.MEDIA_ROOT, filename)
  66. try:
  67. if os.path.exists(img_path):
  68. os.remove(img_path)
  69. except:
  70. pass
  71. @deconstructible
  72. class PathAndRename(object):
  73. def __init__(self, sub_path):
  74. self.path = sub_path
  75. self.full_path = "%s/%s" % (settings.MEDIA_ROOT, sub_path)
  76. if not os.path.exists(self.full_path):
  77. os.makedirs(self.full_path)
  78. def __call__(self, instance, filename):
  79. ext = filename.split('.')[-1]
  80. t = timezone.now().strftime('%Y%m%d%H%M%S%f')
  81. if instance.pk:
  82. filename = '{}-{}.{}'.format(instance.pk, t, ext)
  83. else:
  84. filename = '{}.{}'.format(t, ext)
  85. return os.path.join(self.path, filename)