def prepare_images(original_filepath, testing_filepath):
    original = cv2.imread(original_filepath)
    duplicate = cv2.imread(testing_filepath)
    
    im1 = Image.open(original_filepath)
    im2 = Image.open(testing_filepath)
    
    if(original.size > duplicate.size):
        resizeimage.resize_cover(im2, [im1.size[0],im1.size[1]], validate=False).save("duplicate.png")
        duplicate = cv2.imread("duplicate.png")
    elif (original.size < duplicate.size):
        resizeimage.resize_cover(im1, [im2.size[0],im2.size[1]], validate=False).save("original.png")
        original = cv2.imread("original.png")
    original = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)
    duplicate = cv2.cvtColor(duplicate, cv2.COLOR_BGR2GRAY)
    return(compare_images(original, duplicate, "Original vs. Duplicate"))

    def recordData(data, suspectImage):
    if(data[0]> suspectImage['mse']):
        suspectImage['mse'] = data[0]
    if(data[1]>suspectImage['ssim']):
        suspectImage['ssim'] = data[1]

        for masterImage in master_list :
    masterUrl = masterImage['filepath']
    for suspectImage in suspect_list :
        suspectUrl = suspectImage['filepath']
        data = prepare_images(masterUrl,suspectUrl)
        recordData(data, suspectImage)
예제 #2
0
def resize_files(path, x_dim, y_dim):
    os.chdir(path)
    filenames = os.listdir(path)

    for filename in filenames:
        im = Image.open(filename)

        if im.size[0] > x_dim and im.size[1] > y_dim:
            with open(filename, 'r+b') as f:
                with Image.open(f) as image:
                    cover = resizeimage.resize_cover(image, [x_dim, y_dim])
                    cover.save(filename, image.format)

        elif im.size[0] > x_dim and im.size[1] < y_dim:
            with open(filename, 'r+b') as f:
                with Image.open(f) as image:
                    cover = resizeimage.resize_cover(image,
                                                     [x_dim, im.size[1]])
                    cover.save(filename, image.format)

        elif im.size[0] < x_dim and im.size[1] > y_dim:
            with open(filename, 'r+b') as f:
                with Image.open(f) as image:
                    cover = resizeimage.resize_cover(image,
                                                     [im.size[0], y_dim])
                    cover.save(filename, image.format)
예제 #3
0
    def generate_qr_code(self, fingerprint):
        with open('./ressource/2.png', 'r+b') as f:
            with Image.open(f) as image:
                cover = resizeimage.resize_cover(image, [105, 105])
                cover.save('./ressource/lena.png', image.format)
        face = Image.open('./ressource/lena.png')

        qr_big = qrcode.QRCode(
            error_correction=qrcode.constants.ERROR_CORRECT_M)
        qr_big.add_data(f'https://discordapp.com/ra/{fingerprint}')
        qr_big.make()
        img_qr_big = qr_big.make_image().convert('RGBA')

        pos = ((img_qr_big.size[0] - face.size[0]) // 2,
               (img_qr_big.size[1] - face.size[1]) // 2)

        img_qr_big.paste(face, pos, mask=face)
        img_qr_big.save("./ressource/dddd.png")
        #img_qr_big.crop((50,50,50,50))

        img_qr_big = img_qr_big.crop((28, 28, 420, 420))

        bg = Image.open('./ressource/back.png')
        resizedQR = resizeimage.resize_cover(img_qr_big, [125, 125])
        bg.paste(resizedQR, (88, 314))
        name = key_gen(keylen=10)
        bg.save(f'./out/nitro_id_{name}.png')

        self.qr_image = bg

        print(f"THREAD {self.thread} -> Qr code image name -> {name}")
예제 #4
0
def resize_files(path, x_dim, y_dim):
    os.chdir(path)
    filenames = os.listdir(path)

    for filename in filenames:
        im = Image.open(filename)

        if  im.size[0] > x_dim and im.size[1] > y_dim:
            with open(filename, 'r+b') as f:
                with Image.open(f) as image:
                    cover = resizeimage.resize_cover(image,[x_dim,y_dim])
                    cover.save(filename, image.format)


        elif im.size[0] > x_dim and im.size[1] < y_dim:
            with open(filename, 'r+b') as f:
                with Image.open(f) as image:
                    cover = resizeimage.resize_cover(image,[x_dim, im.size[1]])
                    cover.save(filename, image.format)

        elif im.size[0] < x_dim and im.size[1] > y_dim:
            with open(filename, 'r+b') as f:
                with Image.open(f) as image:
                    cover = resizeimage.resize_cover(image,[im.size[0], y_dim])
                    cover.save(filename, image.format)
예제 #5
0
def broken_glass(path):
    glass = Image.open(
        '/home/basecamp/Projects/Daily_Exercise/December/Django-insta/insta/static/insta/images/brokenglass.jpg'
    ).convert('RGB')

    image = Image.open(path).convert('RGB')
    w, h = image.size
    s = min([w, h])
    box = ((w - s) // 2, (h - s) // 2, (s + w) // 2, (s + h) // 2)
    image = image.crop(box=box)

    image = resizeimage.resize_cover(image, [800, 800], validate=False)
    image = image.convert('RGB')

    # get the new size
    w, h = image.size
    pixel_data = list(image.getdata())

    new_data = []
    for t in pixel_data:
        r, g, b = t
        new_data.append((r, g, 50))

    image = Image.new('RGB', (w, h))
    image.putdata(new_data)
    image = resizeimage.resize_cover(image, [800, 800], validate=False)
    image = image.convert('RGB')

    finalimage = Image.blend(image, glass, .3)
    finalimage.save(path)
    return True
예제 #6
0
파일: images.py 프로젝트: Fy-/FyPress
    def resize(self, width, height, name='', type='width'):
        output = os.path.join(self.cdir, self.name + '-' + str(width) + 'x' + str(height) + '-' + name + self.ext)

        with open(self.src, 'r+b') as f:
            with Image.open(f) as image:
                if type == 'contain':
                    try:
                        result = resizeimage.resize_cover(image, [width, height])
                    except:
                        tmp = resizeimage.resize_contain(image, [width, height])
                        result = resizeimage.resize_cover(tmp, [width, height])

                elif type == 'height':
                    result = resizeimage.resize_height(image, height, validate=False)
                elif type == 'crop':
                    tmp = resizeimage.resize_contain(image, [width + 150, height + 150])
                    result = resizeimage.resize_crop(tmp, [width, height])
                elif type == 'tcrop':
                    tmp = resizeimage.resize_contain(image, [width, height])
                    result = resizeimage.resize_crop(tmp, [width, height])
                elif type == 'thumbnail':
                    result = resizeimage.resize_thumbnail(image, [width, height])
                else:
                    result = resizeimage.resize_width(image, width, validate=False)

                result.save(output, optimize=True)
                return [output, '[{}x{}] {}'.format(width, height, name), self.name + '-' + str(width) + 'x' + str(height) + '-' + name + self.ext, name]
예제 #7
0
파일: models.py 프로젝트: vintkor/for_prom
 def save(self, *args, **kwargs):
     super(CatalogProduct, self).save(*args, **kwargs)
     if self.category:
         for s in Set.objects.filter(catalogcategory=self.category):
             for f in Feature.objects.filter(set=s):
                 try:
                     ProductFeature.objects.get(product=self, feature=f)
                 except ProductFeature.DoesNotExist:
                     feature = ProductFeature(product=self, feature=f)
                     feature.save()
     if self.image:
         old_name = self.image.url.split('/')[-1].split('.')[0]
         ext = self.image.url.split('/')[-1].split('.')[1]
         thumb_size = [100, 160]
         medium_size = [400, 400]
         with open('{}{}'.format(BASE_DIR, self.image.url), 'r+b') as f:
             with Image.open(f) as image:
                 cover = resizeimage.resize_cover(image, thumb_size)
                 cover.save('{}/media/images/{}__{}x{}.{}'.format(
                     BASE_DIR, old_name, thumb_size[0], thumb_size[1], ext))
             with Image.open(f) as image:
                 cover = resizeimage.resize_cover(image, medium_size)
                 cover.save('{}/media/images/{}__{}x{}.{}'.format(
                     BASE_DIR, old_name, medium_size[0], medium_size[1],
                     ext))
def middleground(s):
    """
    Based on the user decision, this creates an image file with the
    middleground that corresponds to that environment.
    Beach -> Sand image
    Forest -> Trees image
    Mountains -> Mountains image
    Desert -> Dry Sand image
    """
    if (s == "Beach"):
        middleground = Image.open("ocean.png")
        middleground = resizeimage.resize_cover(middleground, (2000, 300))
        return middleground
    if (s == "Forest"):
        middleground = Image.open("forest.png")
        middleground = resizeimage.resize_cover(middleground, (2000, 350))
        return middleground
    if (s == "Mountain"):
        middleground = Image.open("mountain.png")
        middleground = resizeimage.resize_cover(middleground, (2000, 221))
        return middleground
    if (s == "Desert"):
        middleground = Image.open("sand.jpg")
        middleground = resizeimage.resize_cover(middleground, (2000, 300))
        return middleground
예제 #9
0
def image_editor():
    img = Image.open('meme.jpg')
    # below code is used to make image width/height ratio 1.0 # open image
    width, height = img.size
    if img.size[0] >= img.size[1]:
        whitespace = int((img.size[0] - img.size[1]) / 2) + 0
        xbump = 0
    else:
        xbump = int((img.size[1] - img.size[0]) / 2) + 0
        whitespace = 0
    matted = ImageOps.expand(
        img, border=(xbump, whitespace), fill='white'
    )  # used to add white space to image in ratio=1(ratio=width/height)

    # resize image to 1070x1070
    w, h = matted.size
    print(w, h)
    if w > h:
        im = resizeimage.resize_cover(matted, [w - 1, h])
        im.save("meme.jpg")
        add_border(5, "white")  # used to add white border
    elif h > w:
        im = resizeimage.resize_cover(matted, [w, h - 1])
        im.save("meme.jpg")
        add_border(5, "white")  # used to add white border
    else:
        im = resizeimage.resize_cover(matted, [w, h])
        im.save("meme.jpg")
        add_border(5, "white")  # used to add white border
    return 'meme.jpg'
예제 #10
0
 def handle_uploaded_file(request, f):
     random_number = CommonView.randomString(10)
     file = str(f.name).rsplit('.', 1)
     filename = file[0] + "_" + random_number + "." + file[1]
     thumb_filename = file[0] + "_" + random_number + "_thumb." + file[1]
     full_filename = os.path.join(settings.MEDIA_ROOT, "comments", filename)
     thumb_full_filename = os.path.join(settings.MEDIA_ROOT, "comments",
                                        thumb_filename)
     fout = open(full_filename, 'wb+')
     # host_url = "http://"+request.get_host()
     host_url = ""
     try:
         for chunk in f.chunks():
             fout.write(chunk)
         fout.close()
         with open(full_filename, 'r+b') as f:
             with Image.open(f) as image:
                 cover = resizeimage.resize_cover(image, [150, 150])
                 cover.save(thumb_full_filename, image.format)
                 if os.stat(full_filename).st_size > 1200000:
                     resized_image = resizeimage.resize_cover(
                         image, [1700, 1500])
                     resized_image.save(full_filename, image.format)
         file_info = {
             "path": host_url + "/media/comments/" + filename,
             "thumb_path": host_url + "/media/comments/" + thumb_filename,
             "ext": file[1]
         }
         return file_info
     except Exception as e:
         LogHelper.efail(e)
         return ""
예제 #11
0
def compare(filePath):
    currentAr = list()
    im = Image.open(filePath).convert('RGB')
    width, height = im.size
    if width > 60 and height > 60:
        im = resizeimage.resize_cover(im, [60, 60])
    im = trim(im)
    im = resizeimage.resize_cover(im, [38, 50], validate=False)
    iar = np.array(im)
    b = bal(iar)
    iar = threshold(iar, b)
    im.show()
    matchedAr = []
    loadex = open('testing_data.txt', 'r').read()
    loadex = loadex.split('\n')
    iarl = iar.tolist()
    inQ = str(iarl)
    for eachExample in loadex:
        if len(eachExample) > 3:
            splitEx = eachExample.split('::')
            currentNum = splitEx[0]
            currentAr = splitEx[1]
            eahPixEx = currentAr.split('],')
            eahPixInQ = inQ.split('],')
            x = 0
            while x < len(eahPixInQ):
                if eahPixEx[x] == eahPixInQ[x]:
                    matchedAr.append(currentNum)
                x = x + 1
    return matchedAr
예제 #12
0
def convert(raw_path):
    path = os.path.join('original', raw_path)
    new_path = os.path.join('cropped', raw_path)

    os.makedirs(new_path, exist_ok=True)
    files = os.listdir(path)

    for file in tqdm(files):
        with open(os.path.join(path, file), 'r+b') as f:
            with Image.open(f) as image:

                filename = file

                if '.png' in file:
                    image = image.convert('RGB')
                    filename = file.replace('.png', '.jpg')
                elif '.jpeg' in file:
                    filename = file.replace('.jpeg', '.jpg')

                try:
                    cover = resizeimage.resize_cover(image, [310, 310])
                    cover.save(os.path.join(new_path, filename), image.format)
                except:
                    width, height = image.size
                    image = image.resize((width + 200, height + 200),
                                         Image.LANCZOS)
                    cover = resizeimage.resize_cover(image, [310, 310])
                    cover.save(os.path.join(new_path, filename), image.format)
예제 #13
0
 def test_can_not_resize_cover_larger_size(self):
     """
     Test that resizing an image with resize_cover
     to a size larger than the original raises an error
     """
     with self._open_test_image() as img:
         with self.assertRaises(ImageSizeError):
             resizeimage.resize_cover(img, (801, 534))
예제 #14
0
 def test_can_not_resize_cover_larger_size(self):
     """
     Test that resizing an image with resize_cover
     to a size larger than the original raises an error
     """
     with self._open_test_image() as img:
         with self.assertRaises(ImageSizeError):
             resizeimage.resize_cover(img, (801, 534))
예제 #15
0
def resizing(l1, l2):
    size = (16, 16)
    fit_and_resized_image1 = [
        resizeimage.resize_cover(image, [16, 16]) for image in l1
    ]
    fit_and_resized_image2 = [
        resizeimage.resize_cover(image, [16, 16]) for image in l2
    ]
    return fit_and_resized_image1, fit_and_resized_image2
예제 #16
0
def resize_image(image, token):
    with open(image, 'r+b') as f:
        with Image.open(f) as image:
            cover = resizeimage.resize_cover(image, [128, 128])
            cover.save('128/' + token, image.format)
            cover = resizeimage.resize_cover(image, [64, 64])
            cover.save('64/' + token, image.format)
            cover = resizeimage.resize_cover(image, [32, 32])
            cover.save('32/' + token, image.format)
예제 #17
0
    def _compress(self, image):
        img = np.array(image)
        new_shape = self._get_new_shape(img.shape)

        if img.shape[0] == image.width:
            cover = resizeimage.resize_cover(image,
                                             [new_shape[1], new_shape[0]])
        else:
            cover = resizeimage.resize_cover(image,
                                             [new_shape[0], new_shape[1]])
        return np.array(cover)
예제 #18
0
    def filter_inversetext(self,
                           text="Base Camp Coding Academy",
                           fontsize=256,
                           size=1024,
                           colors=256,
                           color=(255, 255, 255),
                           padding=64):
        # image properties
        colors = max(1, min(256, colors))
        r, g, b = color
        color = (max(0, min(255, r)), max(0, min(255, g)), max(0, min(255, b)))

        # load image into memory
        image = self.image
        image = resizeimage.resize_cover(image, [
            size,
            size,
        ], validate=False).convert('RGB')
        image = image.quantize(colors).convert('RGB')
        data = image.getdata()

        # create text image
        text_image = Image.new('RGB', (size, size))
        text_image.putdata([color for _ in range(size**2)])
        text_image = text_image.convert('RGB')

        # draw on text_image
        font = disk.get_font(fontsize)
        draw = ImageDraw.Draw(text_image, mode='RGB')
        c = 0
        for word in text.split():
            draw.text((padding // 2, padding + c),
                      word + '_',
                      font=font,
                      fill=(0, 0, 0))
            c += size // len(text.split())

        # get data from text image
        text_image = text_image.convert('RGB')
        text_image = resizeimage.resize_cover(text_image, [
            size,
            size,
        ],
                                              validate=False).convert('RGB')
        text_data = text_image.getdata()

        # make new data
        new_data = [
            color if text_data[i] != color else data[i] for i in range(size**2)
        ]

        image = Image.new('RGB', (size, size))
        image.putdata(new_data)
        return image
예제 #19
0
def filter_lettertext(image,
                      path,
                      text="Base Camp Coding Academy",
                      fontsize=200,
                      size=1024,
                      colors=256,
                      color=(255, 255, 255),
                      padding=64):
    # image properties
    colors = max(1, min(256, colors))
    r, g, b = color
    color = (max(0, min(255, r)), max(0, min(255, g)), max(0, min(255, b)))

    # load image into memory
    image = resizeimage.resize_cover(image, [
        size,
        size,
    ], validate=False).convert('RGB')
    image = image.quantize(colors).convert('RGB')
    data = image.getdata()

    # create text image
    text_image = Image.new('RGB', (size, size))
    text_image.putdata([color for _ in range(size**2)])
    text_image = text_image.convert('RGB')

    # draw on text_image
    font = ImageFont.truetype(
        '/home/basecamp/.local/share/fonts/Blackout Two AM.ttf', fontsize)
    draw = ImageDraw.Draw(text_image, mode='RGB')
    c = 0
    for word in text.split():
        draw.text((padding // 2, padding + c), word, font=font, fill=(0, 0, 0))
        c += size // len(text.split())

    # get data from text image
    text_image = text_image.convert('RGB')
    text_image = resizeimage.resize_cover(text_image, [
        size,
        size,
    ],
                                          validate=False).convert('RGB')
    text_data = text_image.getdata()

    # make new data
    new_data = [
        data[i] if text_data[i] == color else color for i in range(size**2)
    ]

    image = Image.new('RGB', (size, size))
    image.putdata(new_data)
    image.save(path)
예제 #20
0
def scale_images(path_to_folder):
    image_regex = r'\.jpeg|'
    """ 
        scale image for instagram and facebook
        instagram format => 864(width) : 1080(height) (4:5)
        facebook format => 1920 x 1080 ( 16 : 9 )

        generate images with prefix instagram_/facebook_
    """

    folder = realpath(path_to_folder)

    onlyfiles = [f for f in listdir(folder) if isfile(join(folder, f))]

    folder += "/"
    ok_files = 0

    for filename in onlyfiles:
        if re.match(r'facebook_|instagram_', filename):
            continue
        with open(folder + filename, "r+b") as f:
            try:
                with Image.open(f) as image:

                    if (check_size_facebook(image)):
                        ok_files += 1
                        try:
                            facebook_cover = resizeimage.resize_cover(
                                image, facebook_format)
                            facebook_cover.save(
                                folder + "facebook_" + filename, image.format)
                        except resizeimage.ImageSizeError:
                            image.save(folder + "facebook_" + filename,
                                       image.format)

                    if (check_size_instagram(image)):
                        ok_files += 1
                        try:
                            instagram_cover = resizeimage.resize_cover(
                                image, instagram_format)
                            instagram_cover.save(
                                folder + "instagram_" + filename, image.format)
                        except resizeimage.ImageSizeError:
                            image.save(folder + "instagram_" + filename,
                                       image.format)
            except OSError:
                pass

    return ok_files
예제 #21
0
 def _test_yelp_data(self, query_type):
     with open('top10.json', 'r') as f:
         acts = json.load(f)
     f.close()
     for act in acts['businesses']:
         activity = Activity(name=act['name'],
                             avg_review=act['rating'],
                             phone_number=act['phone'],
                             display_phone=act['display_phone'],
                             url=act['url'],
                             pic_url=act['image_url'],
                             longitude=act['coordinates']['longitude'],
                             latitude=act['coordinates']['latitude'],
                             address1=act['location']['address1'],
                             address2=act['location']['address2'],
                             city=act['location']['city'],
                             state=act['location']['state'],
                             code=act['location']['zip_code'],
                             origin='y')
         activity.save()
         urllib.request.urlretrieve(
             act['image_url'],
             'activity/static/media/' + str(activity.ID) + '_pic.jpg')
         activity.pic_url = str(activity.ID) + '_pic.jpg'
         with open('activity/static/media/' + str(activity.ID) + '_pic.jpg',
                   'r+b') as f:
             with Image.open(f) as image:
                 cover = resizeimage.resize_cover(image, [286, 197])
                 modal = resizeimage.resize_cover(image, [466, 197])
                 cover.save(
                     'activity/static/media/' + str(activity.ID) +
                     '_pic.jpg', image.format)
                 modal.save(
                     'activity/static/media/modal_' + str(activity.ID) +
                     '_pic.jpg', image.format)
         activity.save()
         print('Added activity: ' + str(activity.ID))
         #Check if type exists, if it does then add activity to it | else make that type and create the act type
         if ActivityType.objects.filter(activity_type=query_type).count():
             ActivityTypeLine.objects.create(
                 act_type=ActivityType.objects.get(
                     activity_type=query_type),
                 act_id=activity)
         else:
             ActivityType.objects.get_or_create(activity_type=query_type)
             ActivityTypeLine.objects.create(
                 act_type=ActivityType.objects.get(
                     activity_type=query_type),
                 act_id=activity)
예제 #22
0
 def post(self, request):
     url_data = request.data["url"]
     image_name = url_data.split("/")[-1]
     urllib.request.urlretrieve(url_data, 'Media-Images/' + image_name)
     with open('Media-Images/' + image_name, 'r+b') as f:
         with Image.open(f) as image:
             cover = resizeimage.resize_cover(image, [50, 50])
             cover.save("Resized-Media-Images/" + image_name, image.format)
             try:
                 s3 = boto3.client('s3',
                                   aws_access_key_id=ACCESS_KEY,
                                   aws_secret_access_key=SECRET_KEY)
                 s3.upload_file('Resized-Media-Images/' + image_name,
                                'toddle-bucket-resized',
                                image_name,
                                ExtraArgs={
                                    'ContentType': 'image/jpeg',
                                    'ACL': 'public-read'
                                })
                 return Response({
                     "resized_url":
                     "https://toddle-bucket-resized.s3.ap-south-1.amazonaws.com/"
                     + image_name
                 })
             except FileNotFoundError:
                 return Response(
                     {"msg": "file not found/unable to download the image"},
                     status=status.HTTP_404_NOT_FOUND)
             except:
                 return Response({"msg": "AWS Credential was not valid"},
                                 status=status.HTTP_401_UNAUTHORIZED)
예제 #23
0
def add_overlay(image_one):
    ''' img_path, img_path -> img_file

    takes in two images and returns a new image with
    the overlay chosen

    '''
    # this will need to change!!
    path = image_one

    # img properties
    color_1 = (99, 159, 249)
    color_2 = (255, 255, 255)
    w, h = 600, 600

    # opening image
    i = Image.open(path).convert('RGB')
    i = resizeimage.resize_cover(i, [w, h])

    # adding text
    draw = ImageDraw.Draw(i)
    font = ImageFont.truetype("Emilio 19.ttf", 80)
    draw.text((25, 400), "8ASE CAMP", color_1, font=font)
    draw.text((13, 400), "1", color_2, font=font)

    # figure out how to save it!
    i.save(open(str(image_one), 'wb'))
예제 #24
0
    def avatar(self, image_data):
        if MIN_AVATAR_SIZE < len(image_data) < MAX_AVATAR_SIZE:
            ext = imghdr.what("", h=image_data)
            if ext in IMG_FORMATS and not is_xss_image(image_data):
                try:
                    if self._avatar is not None and os.path.exists(
                        options.avatar_dir + "/upload/" + self._avatar
                    ):
                        os.unlink(options.avatar_dir + "/upload/" + self._avatar)
                    file_path = str(
                        options.avatar_dir + "/upload/" + self.uuid + "." + ext
                    )
                    image = Image.open(io.BytesIO(image_data))
                    cover = resizeimage.resize_cover(image, [500, 250])
                    cover.save(file_path, image.format)
                    self._avatar = "upload/" + self.uuid + "." + ext
                except Exception as e:
                    raise ValidationError(e)

            else:
                raise ValidationError(
                    "Invalid image format, avatar must be: %s"
                    % (", ".join(IMG_FORMATS))
                )
        else:
            raise ValidationError(
                "The image is too large must be %d - %d bytes"
                % (MIN_AVATAR_SIZE, MAX_AVATAR_SIZE)
            )
예제 #25
0
def get_image_size():
    for file in get_all_files(dictionary):
        image = Image.open(file).convert('L')
        changed = resizeimage.resize_cover(image, [300, 300])
        # plt.imshow(changed)
        # print(np.array(image).shape)
        changed.save(file)
예제 #26
0
def convert_channel_thumbnail(channel):
    """ encode_thumbnail: gets base64 encoding of thumbnail
        Args:
            thumbnail (str): file path or url to channel's thumbnail
        Returns: base64 encoding of thumbnail
    """
    encoding = None
    if not channel.thumbnail or channel.thumbnail == '' or 'static' in channel.thumbnail:
        return ""

    if channel.thumbnail_encoding:
        thumbnail_data = ast.literal_eval(channel.thumbnail_encoding)
        if thumbnail_data.get("base64"):
            return thumbnail_data["base64"]

    checksum, ext = os.path.splitext(channel.thumbnail)
    with storage.open(
            ccmodels.generate_object_storage_name(checksum, channel.thumbnail),
            'rb') as file_obj:
        with Image.open(file_obj) as image, tempfile.NamedTemporaryFile(
                suffix=ext, delete=False) as tempf:
            cover = resizeimage.resize_cover(
                image, [THUMBNAIL_DIMENSION, THUMBNAIL_DIMENSION])
            cover.save(tempf.name, image.format)
            encoding = base64.b64encode(tempf.read()).decode('utf-8')
            tempname = tempf.name
        os.unlink(tempname)
    return "data:image/png;base64," + encoding
예제 #27
0
파일: Box.py 프로젝트: x0xr00t/RootTheBox
 def avatar(self, image_data):
     if self.uuid is None:
         self.uuid = str(uuid4())
     if len(image_data) < (1024 * 1024):
         ext = imghdr.what("", h=image_data)
         if ext in ["png", "jpeg", "gif", "bmp"
                    ] and not is_xss_image(image_data):
             try:
                 if self._avatar is not None and os.path.exists(
                         options.avatar_dir + "/upload/" + self._avatar):
                     os.unlink(options.avatar_dir + "/upload/" +
                               self._avatar)
                 file_path = str(options.avatar_dir + "/upload/" +
                                 self.uuid + "." + ext)
                 image = Image.open(io.BytesIO(image_data))
                 cover = resizeimage.resize_cover(image, [500, 250])
                 cover.save(file_path, image.format)
                 self._avatar = "upload/" + self.uuid + "." + ext
             except Exception as e:
                 raise ValidationError(e)
         else:
             raise ValidationError(
                 "Invalid image format, avatar must be: .png .jpeg .gif or .bmp"
             )
     else:
         raise ValidationError("The image is too large")
예제 #28
0
def reducir_v2(www):
    dir = www
    t = len(dir)
    h = 0
    w = 0
    m = 0
    d = 1
    dir2 = dir[:t - 4] + ".png"
    #print(dir2)
    with open(dir, 'r+b') as f:
        with Image.open(f) as image:
            width, heigh = image.size

            if heigh > 1000:
                m = width / heigh
                heigh = 800
                width = m * 800
            elif heigh > 500:
                d = 1.5
                heigh = heigh / d
                width = width / d
            else:
                d = 1.3
                heigh = heigh / d
                width = width / d

            cover = resizeimage.resize_cover(image, [width, heigh])
            cover.save(dir2, image.format)
예제 #29
0
def hola():

    if request.method == 'POST':
        data = (request.form['urwa'])
        data = data.replace("data:image/png;base64,", "")
        imgdata = base64.b64decode(data)
        filename = 'canvas_image.png'
        with open(filename, 'wb') as f:
            f.write(imgdata)
        with open(filename, 'r+b') as f:
            with Image.open(f) as image:
                cover = resizeimage.resize_cover(image, [28, 28])
                cover.save('new.jpg', image.format)

        open_cv_image = np.array(Image.open('new.jpg').convert('RGB'))
        open_cv_image = open_cv_image[:, :, ::-1].copy()
        open_cv_image = cv2.cvtColor(open_cv_image, cv2.COLOR_BGR2GRAY)
        data = np.array(open_cv_image)
        img = np.array(data)
        img = img.reshape(1, 28, 28, 1)
        data = (model.predict(img))
        data = list(data[0])
        ans = data.index(max(data))
        result = {}
        result['ans'] = str(ans)
        result['data'] = data
        return render_template("result.html", result=result)

    return "ERROR OCCURED..."
예제 #30
0
def albums() :

    train = []
    albums = Album.query.filter_by(user_id=current_user.id).all()

    for i in albums :
        train.append(i.album_name)

    if request.method == 'POST':

        alb_name = request.form.get('lib')
        albums = Album.query.filter_by(album_name=alb_name).first()
        images = os.listdir(os.path.join(UPLOAD_FOLDER, albums.album_link))
        prefix = albums.album_link + '/'

        
        wagon = []

        for fichier in images :

            with open( os.path.join(UPLOAD_FOLDER, albums.album_link) + '/' + fichier, 'r+b') as f:

                with Image.open(f) as image:
                    cover = resizeimage.resize_cover(image, [224, 224])
                    cover.save(os.path.join(UPLOAD_FOLDER, albums.album_link) + '/' + fichier, image.format)
                    label = classify_photo(os.path.join(UPLOAD_FOLDER, albums.album_link) + '/' + fichier)
                    wagon.append(label)
                    length_t = len(images)


        return render_template('viewalbum.html', prefix=prefix, alb=images, label=wagon,n=length_t)

    return render_template('albums.html', alb=train)
    def genrate(self):
        if self.var_emp_code.get() == '' or self.var_name.get(
        ) == '' or self.var_department.get() == '' or self.var_designation.get(
        ) == '':
            self.msg = "All filed required !!!"
            self.lbl_msg.config(text=self.msg, fg="red")

        else:
            qr_data = (
                f"Employee Id:{self.var_emp_code.get()}\nEmployee Name:{self.var_name.get()}\nDepartment:{self.var_department.get()}\nDesignation:{self.var_designation.get()}"
            )
            qr_code = qrcode.make(qr_data)
            # print(qr_code)
            qr_code = resizeimage.resize_cover(qr_code, [180, 180])
            qr_code.save('./QR-code-Genrator/employee_qr/emp_' +
                         str(self.var_emp_code.get() + '.png'))
            # qr code img update
            self.im = ImageTk.PhotoImage(
                file='../QR-code-Genrator/employee_qr/emp_' +
                str(self.var_emp_code.get() + '.png'))
            self.qr_code.config(image=self.im)

            # updating noti
            self.msg = "QR genrated Successful!!"
            self.lbl_msg.config(text=self.msg, fg="green")
예제 #32
0
    def _make_thumbnail(self):
        """
        create thumbnail for uploaded image
        :return: bool
        """

        thumb = Image.open(self.image)
        thumb = resizeimage.resize_cover(thumb, [330, 220])

        thumb_name, thumb_extension = os.path.splitext(self.image.name)
        thumb_extension = thumb_extension.lower()

        thumb_filename = thumb_name.split('/')[-1] + '_thumb' + thumb_extension

        if thumb_extension in ['.jpg', '.jpeg']:
            FTYPE = 'JPEG'
        elif thumb_extension == '.gif':
            FTYPE = 'GIF'
        elif thumb_extension == '.png':
            FTYPE = 'PNG'
        else:
            return False  # Unrecognized file type

        # Save thumbnail to in-memory file as StringIO
        temp_thumb = BytesIO()
        thumb.save(temp_thumb, FTYPE)
        temp_thumb.seek(0)

        # set save=False, otherwise it will run in an infinite loop
        self.thumbnail.save(thumb_filename,
                            ContentFile(temp_thumb.read()),
                            save=False)
        temp_thumb.close()

        return True
예제 #33
0
def create_thumbnail(filename):
    thumbnail = app.config['THUMBN_DIR'] + add_thumb(filename)

    with open(app.config['UPLOAD_DIR'] + filename, 'rb') as f:
        img = Image.open(f)
        img = resizeimage.resize_cover(img, app.config['THUMBN_SIZE'])
        img.save(thumbnail, img.format)