import random import numpy as np from PIL import Image import os from uuid import uuid4 from django.utils.deconstruct import deconstructible from django.core.files import File from PIL import Image from io import BytesIO from turismoREST import settings def vectorImagen(n): ubica2 = 0 M = np.zeros((300, 300), dtype=np.uint8) for i in range(1, 11): aux2 = ubica2 ubica2 = i * 30 ubica = 0 for j in range(1, 11): r = random.randint(0, n) aux = ubica ubica = j * 30 M[aux2:ubica2, aux:ubica] = r return M def imagenPerfil(username): M = np.zeros((300, 300, 3), dtype=np.uint8) M[:, :, 0] = vectorImagen(128) M[:, :, 1] = vectorImagen(128) M[:, :, 2] = vectorImagen(128) #path = '/home/wtredata/kotti/api/Devmaster/Media/' path = settings.MEDIA_ROOT nombre = 'perfil/'+str(username)+'.png' #nombre = 'Media/perfil/' + str(username) + '.png' pil_img = Image.fromarray(M) pil_img.save(path+'/'+nombre) #cv2.imwrite(nombre, M) return nombre def compress(image): im = Image.open(image) width, height = im.size if (width > height): if(width > 1024): height = height*((width-1024)/width) width = 1024 elif (height > width): if(height > 1024): width = width*((height-1024)/height) height = 1024 elif (height == width): if(width > 1024): width = 1024 height = 1024 im = im.resize((width, height)) im_io = BytesIO() if im.mode != 'RGB': im = im.convert('RGB') im.save(im_io, 'PNG', quality=90) else: im.save(im_io, 'JPEG', quality=90) new_image = File(im_io, name=image.name) return new_image @deconstructible class UploadToPathAndRename(object): def __init__(self, path): self.sub_path = path def __call__(self, instance, filename): ext = filename.split('.')[-1] # get filename if instance.pk: filename = '{}.{}'.format(instance.pk, ext) else: # set filename as random string filename = '{}.{}'.format(uuid4().hex, ext) # return the whole path to the file return os.path.join(self.sub_path, filename)