def save2images(file,goodsmessage): if not os.path.exists(os.path.join(settings.MEDIA_ROOT, 'images')): os.makedirs(os.path.join(settings.MEDIA_ROOT, 'images')) full_path = os.path.join(settings.MEDIA_ROOT, 'images' , file.name) file_name = file.name if(os.path.exists(full_path)): #新文件名添加了16位随机字符 file_name = file_name[:-len(file_name.split('.')[-1]) - 1] + '_' + \ ''.join(random.sample(string.ascii_letters + string.digits, 16)) + \ '.' + file_name.split('.')[-1] full_path = os.path.join(settings.MEDIA_ROOT, 'images' , file_name) fd = open(full_path,'wb+') for chunks in file.chunks(): fd.write(chunks) fd.close() if(filetype(full_path) == 'unknown'): os.remove(full_path) return None #进行图片剪裁 sm_img = creat_small_img(full_path) big_img = creat_small_img(full_path,'big') if big_img: os.remove(full_path) else: big_img = os.path.join('/media/images',os.path.basename(full_path)) g = GoodsImage(ImgBig=big_img,ImgSma=sm_img) g.save() goodsmessage.Images.add(g) #如果无图就添加一张新图 if not goodsmessage.First_pic: goodsmessage.First_pic = g goodsmessage.save()
def savehead(pic): if not os.path.exists(os.path.join(settings.MEDIA_ROOT, 'head')): os.makedirs(os.path.join(settings.MEDIA_ROOT, 'head')) randname = ''.join(random.sample(string.ascii_letters + string.digits, 24)) randname += '.' + pic.name.split('.')[-1] full_path = os.path.join(settings.MEDIA_ROOT, 'head', randname) fd = open(full_path, 'wb+') for chunks in pic.chunks(): fd.write(chunks) fd.close() if (filetype(full_path) == 'unknown'): os.remove(full_path) return None else: nn = creat_head(full_path) os.remove(full_path) return nn