123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- # coding=utf-8
- import os
- import requests
- from django.conf import settings
- from django.utils import timezone
- from django.utils.deconstruct import deconstructible
- from PIL import Image
- def resizePicture(file, width):
- '''如果图片宽度或高度超过width,将图片宽度或高度修改为width'''
- try:
- img = Image.open(file)
- w, h = img.size
- if w > width or h > width:
- if w > h:
- size = (width, int(h * width / w))
- elif w < h:
- size = (int(w * width / h), width)
- else:
- size = (width, width)
- img = img.resize(size)
- img.save(file)
- except Exception as e:
- pass
- def resizePictureWith(file, width):
- '''如果图片宽度或高度超过width,将图片宽度或高度修改为width'''
- try:
- img = Image.open(file)
- w, h = img.size
- if w > width:
- size = (width, int(h * width / w))
- img = img.resize(size)
- img.save(file)
- except Exception as e:
- pass
- def UploadFile(file, upload_path, width=None):
- upload_path = PathAndRename(upload_path)
- filename = "%s%s.%s" % (
- upload_path.path,
- timezone.now().strftime('%Y%m%d%H%M%S%f'),
- file.name.split('.')[-1]
- )
- filename = filename.lower()
- full_filename = "%s/%s" % (settings.MEDIA_ROOT, filename)
- with open(full_filename, 'wb+') as destination:
- for chunk in file.chunks():
- destination.write(chunk)
- if width:
- resizePictureWith(full_filename, width)
- return filename
- def DownloadFace(url, save_path, ext):
- upload_path = PathAndRename(save_path)
- filename = "%s%s.%s" % (
- upload_path.path,
- timezone.now().strftime('%Y%m%d%H%M%S%f'),
- ext
- )
- filename = filename.lower()
- full_filename = "%s/%s" % (settings.MEDIA_ROOT, filename)
- response = requests.get(url)
- img = response.content
- with open(full_filename, 'wb+') as destination:
- destination.write(img)
- return filename
- def DeleteFile(filename):
- img_path = '%s/%s' % (settings.MEDIA_ROOT, filename)
- try:
- if os.path.exists(img_path):
- os.remove(img_path)
- except:
- pass
- @deconstructible
- class PathAndRename(object):
- def __init__(self, sub_path):
- self.path = sub_path
- self.full_path = "%s/%s" % (settings.MEDIA_ROOT, sub_path)
- if not os.path.exists(self.full_path):
- os.makedirs(self.full_path)
- def __call__(self, instance, filename):
- ext = filename.split('.')[-1]
- t = timezone.now().strftime('%Y%m%d%H%M%S%f')
- if instance.pk:
- filename = '{}-{}.{}'.format(instance.pk, t, ext)
- else:
- filename = '{}.{}'.format(t, ext)
- return os.path.join(self.path, filename)
|