Ejemplo n.º 1
0
def resize(im, crop, limit):
    """
    Resize image to limit if limit > 0
    if crop_square, and height and width are within 9 % crop to smaller dimension
    """
    width = im.width
    height = im.height

    if width == height:
        size = width
        if 0 < limit < width:
            size = limit
            im = resizeimage.resize_width(im, size)

    elif width > height:
        size = height
        if 0 < limit < height:
            size = limit
        if crop and (width - height) / width < 0.09:
            im = resizeimage.resize_crop(im, [size, size])
        else:
            im = resizeimage.resize_width(im, size)

    elif height > width:
        size = width
        if limit and width > limit:
            size = limit
        if crop and (height - width) / height < 0.09:
            im = resizeimage.resize_crop(im, [size, size])
        else:
            im = resizeimage.resize_height(im, size)
    return im
Ejemplo n.º 2
0
 def buttonClicked(self):
     #print "goButton clicked"
     global designingCarPark, globalMapImage
     if len(carParkShape.getVertices()
            ) < 3:  #a valid shape can't have less than three vertices
         tkMessageBox.showerror(
             "Report",
             "Error: Your car park shape must have more than 2 vertices")
     else:
         globalMapImage = resizeimage.resize_height(images[globalMapName],
                                                    imageHeight)
         designingCarPark = False
         carParkShapeForUseInProcessing = copy.deepcopy(
             carParkShape
         )  #because it would otherwise pass my shape instance by referance, I make a copy of it to be passed to the processing code.
         listOfGroupsOfCoordinatesForLines, messageToPrint = processingCode.GetCarParkPixelLinesToDrawFromPixelShape(
             carParkShapeForUseInProcessing, pixelsPerMeter,
             getAddPerimeterRoad())
         draw = ImageDraw.Draw(globalMapImage)
         listOfCoordinates = carParkShape.getVerticesCoordinates()
         for eachGroupOfCoordinatesForLines in listOfGroupsOfCoordinatesForLines:
             #print "eachGroupOfCoordinatesForLines:"
             #print eachGroupOfCoordinatesForLines
             draw.line(eachGroupOfCoordinatesForLines)
         del draw
         refreshWindow()
         tkMessageBox.showinfo("Report", messageToPrint)
Ejemplo n.º 3
0
    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]
Ejemplo n.º 4
0
def make_small_file(photo_id):
    """
    Task for making small photo
    :param photo_id:
    :return:
    """

    from app.models import Photo

    photo = Photo.objects.get(pk=photo_id)
    image = photo.original_file

    file_name = image.name.split('/')[-1]

    image_obj = Image.open(image)
    file_format = image_obj.format
    width, height = image_obj.size

    image_obj.convert('RGB')

    if width > height:
        image_obj = resizeimage.resize_width(image_obj, 150)
    else:
        image_obj = resizeimage.resize_height(image_obj, 150)

    thumb_io = BytesIO()

    image_obj.save(thumb_io, file_format, quality=90)
    file_object = File(thumb_io, name=file_name)

    photo.small_file = file_object
    photo.save()
Ejemplo n.º 5
0
def resize_image(image_path, output_dir):
    '''
    :param image_path: str, path to image
    :param output_dir: str, path to destination directory saving the resized image
    :return: boolean, indicate if image exists and is valid
    '''
    image_exist = False
    if os.path.exists(image_path):
        file_info = os.stat(image_path)
        if file_info.st_size < 15424400:
            image_exist = True
    else:
        return image_exist
    with open(image_path, 'r+b') as f:
        image = Image.open(f)
        width, height = image.size
        if width >= height:
            if width > 640:
                width = 640
            image = resizeimage.resize_width(image, width)
        else:
            if height > 640:
                height = 640
            image = resizeimage.resize_height(image, height)

            # create new resized image at output_dir
        image.save(output_dir + os.path.basename(image_path), image.format)
    return image_exist
Ejemplo n.º 6
0
 def buttonClicked(self):
     global globalMapName,globalMapImage, carParkShape
     globalMapName = self.parent.items['mapTypeComboBox'].comboBox.get()
     globalMapImage = resizeimage.resize_height(images[globalMapName], imageHeight)
     #sets the car park shape to a new blank shape
     carParkShape = processingCode.shape()
     refreshMap()
Ejemplo n.º 7
0
def resize_image(file: pathlib.Path,
                 indir: pathlib.Path,
                 outdir: pathlib.Path,
                 width=None,
                 height=None,
                 verbose=False):
    assert width or height, "At least height or width must be specified"

    if verbose:
        print("Opening file {}".format(file))

    with Image.open(file.resolve()) as img:
        if width and height:
            resized = resizeimage.resize_thumbnail(img, [width, height])
        elif width:
            resized = resizeimage.resize_width(img, width)
        else:
            resized = resizeimage.resize_height(img, height)

        if verbose:
            print("File {} resized. Will save it.".format(file))

        final_path = file.relative_to(indir)
        final_path = outdir.joinpath(final_path)
        if not final_path.parent.exists():
            final_path.parent.mkdir(parents=True)
        resized.save(final_path, resized.format)

        if verbose:
            print("Saved resized version of {} to {}".format(file, final_path))
Ejemplo n.º 8
0
 def buttonClicked(self):
     global globalMapName, globalMapImage
     globalMapName = self.parent.items['mapTypeComboBox'].comboBox.get()
     globalMapImage = resizeimage.resize_height(images[globalMapName],
                                                imageHeight)
     print "shapeResetButton clicked"
     #print self.parent.items['mapTypeComboBox'].comboBox.get()
     refreshMap()
def resize_img(path):
    with open(f'{path}', 'r+b') as f:
        new_name = f'rs{datetime.datetime.today()}.png'
        with Image.open(f) as image:
            cover = resizeimage.resize_height(image, 300)
            # cover.show()
            # cover.save(f'resource/{new_name}', image.format)
        return cover
Ejemplo n.º 10
0
def crop_profile_picture(input_file, output_file):
    with open(input_file, "rb") as fd_img:
        img = Image.open(fd_img)
        img = resizeimage.resize_height(img, 200)
        img = resizeimage.resize_crop(img, [112, 200])
        img.save(output_file, img.format)
        fd_img.close()

    return True
Ejemplo n.º 11
0
def drawMapImage():
    global globalMapImage
    globalMapImage = resizeimage.resize_height(images[globalMapName], imageHeight)
    draw = ImageDraw.Draw(globalMapImage)
    listOfCoordinates = carParkShape.getVerticesCoordinates()
    for count in range(len(listOfCoordinates)):#  each in carParkShape.getVerticesCoordinates():
        draw.ellipse((listOfCoordinates[count][0]-radiusOfCarParkVertices,listOfCoordinates[count][1]-radiusOfCarParkVertices,listOfCoordinates[count][0]+radiusOfCarParkVertices,listOfCoordinates[count][1]+radiusOfCarParkVertices))#,fill = colour)
        draw.line((listOfCoordinates[count][0],listOfCoordinates[count][1],listOfCoordinates[(count+1)%len(listOfCoordinates)][0],listOfCoordinates[(count+1)%len(listOfCoordinates)][1]))        
    del draw
Ejemplo n.º 12
0
def crop_image(
    image_base64: str, png_image_quality: int = IMAGE_QUALITY_PNG
) -> str:
    """
    Crop an image, encoded in Base64.

    Args:
        image_base64: Image encoded in Base64

    Kwargs:
        png_image_quality: PNG image quality (defaults to 6)

    Returns:
        PNG image (possibly cropped) encoded in Base64
    """
    img: Image.Image = Image.open(BytesIO(base64.b64decode(image_base64)))
    img_width: int
    img_height: int
    img_width, img_height = img.size
    cropped_image_base64: str

    # Image is too small
    if img_width < IMAGE_WIDTH_DESKTOP or img_height < IMAGE_HEIGHT_DESKTOP:
        raise ValidationError(
            "Image is too small (min {} x {} pixels): {} x {} pixels".format(
                IMAGE_WIDTH_DESKTOP,
                IMAGE_HEIGHT_DESKTOP,
                img_width,
                img_height,
            )
        )
    # Image is too big
    elif img_width > IMAGE_WIDTH_DESKTOP or img_height > IMAGE_HEIGHT_DESKTOP:
        # Image is too wide
        if (img_width / img_height) > (
            IMAGE_WIDTH_DESKTOP / IMAGE_HEIGHT_DESKTOP
        ):
            img = resizeimage.resize_height(img, IMAGE_HEIGHT_DESKTOP)
        # Image is too high (and wide)
        else:
            img = resizeimage.resize_width(img, IMAGE_WIDTH_DESKTOP)

        img = img.crop((0, 0, IMAGE_WIDTH_DESKTOP, IMAGE_HEIGHT_DESKTOP))
        buffered = BytesIO()
        img.save(
            buffered, format="PNG", compress_level=png_image_quality
        )  # [0, 9], where 0 = no compression and 9 = best compression, defaults to 6
        cropped_image_base64 = base64.b64encode(buffered.getvalue()).decode(
            "utf-8"
        )
    # Image dimensions are correct (use the original image)
    else:
        cropped_image_base64 = image_base64

    return cropped_image_base64
Ejemplo n.º 13
0
def upload():
    if request.method == "POST":
        target = os.path.join(
            APP_ROOT,
            '/var/www/homeDelicious/home_delicious_frontend/dist/img/uploadImgs'
        )
        # target = os.path.join(APP_ROOT, '/Users/Taylo/InnoTech/Assignments/Project/Home delicious/home_delicious_frontend')
        if not os.path.isdir(target):
            os.mkdir(target)
        files = request.files.getlist("file")
        for file in files:
            # print(file)
            filename = file.filename
            destination = "/".join([target, filename])
            print(destination)
            file.save(destination)
            image = Image.open(destination)
            if image.width > 1280 and image.height < 1280:
                with open(destination, 'r+b') as f:
                    with Image.open(f) as image:
                        cover = resizeimage.resize_width(image, 1280)
                        cover.save(destination, image.format)
            elif image.width < 1280 and image.height > 1280:
                with open(destination, 'r+b') as f:
                    with Image.open(f) as image:
                        cover = resizeimage.resize_height(image, 1280)
                        cover.save(destination, image.format)
            elif image.width > 1280 and image.height > 1280:
                with open(destination, 'r+b') as f:
                    with Image.open(f) as image:
                        cover = resizeimage.resize_cover(image, [1280, 1280])
                        cover.save(destination, image.format)
        return Response(json.dumps(destination, default=str),
                        mimetype="application/json",
                        status=204)
    if __name__ == "__main__":
        app.run(port=4555, debug=True)
    if request.method == "DELETE":
        image = request.json.get("image")
        print(image)
        path = "/var/www/homeDelicious/home_delicious_frontend/dist/img/uploadImgs/"
        image_path = path + image
        print(image_path)
        if os.path.exists(image_path):
            os.remove(image_path)
            if os.path.exists(image_path):
                return Response("Delete went wrong!",
                                mimetype="text/html",
                                status=500)
            else:
                return Response("Delete sucess",
                                mimetype="application/json",
                                status=200)
        else:
            print("The file does not exist")
Ejemplo n.º 14
0
def main():
    # Measures total program runtime by collecting start time
    start_time = time()

    max_width = 960
    max_height = 960
    folder = 'uploaded_images'

    for filename in listdir(folder):

        filepath = "%s/%s" % (folder, filename)

        if not filename.endswith('.jpg'):
            continue

        size_slug = "contain%dx%d" % (max_width, max_height)
        new_filename = "%s.%s.%s" % (filename.split('.')[0], size_slug,
                                     filename.split('.')[-1])
        new_filepath = "%s/%s" % (folder, new_filename)
        replace_file = False

        if filename == new_filename or path.isfile(new_filepath):
            print("File %s already exists, skipping file" % (new_filename))
            continue

        with open(filepath, 'r+b') as file:
            with Image.open(file) as image:

                if image.width <= max_width and image.height <= max_height:
                    print("File %s already resized, skipping file" %
                          (filename))
                else:
                    print('Resizing image %s => %s' % (filename, new_filename))

                    if image.width > image.height:
                        resized = resizeimage.resize_width(image, max_width)
                    else:
                        resized = resizeimage.resize_height(image, max_height)

                    resized.convert('RGB').save(new_filepath, image.format)
                    replace_file = True

        if replace_file:
            remove(filepath)
            rename(new_filepath, filepath)

    # Measure total program runtime by collecting end time
    end_time = time()

    # Computes overall runtime in seconds & prints it in hh:mm:ss format
    tot_time = end_time - start_time  # calculate difference between end time and start time
    print(
        "\n** Total Elapsed Runtime:",
        str(int((tot_time / 3600))) + ":" + str(int(
            (tot_time % 3600) / 60)) + ":" + str(int((tot_time % 3600) % 60)))
Ejemplo n.º 15
0
 def test_resize_height(self):
     """
     Test that the image resized with resize_height
     has the expected size
     """
     with self._open_test_image() as img:
         img = resizeimage.resize_height(img, 200)
         filename = self._tmp_filename('resize-height.jpeg')
         img.save(filename, img.format)
         with Image.open(filename) as image:
             self.assertEqual(image.size[1], 200)
Ejemplo n.º 16
0
 def test_resize_height(self):
     """
     Test that the image resized with resize_height
     has the expected size
     """
     with self._open_test_image() as img:
         img = resizeimage.resize_height(img, 200)
         filename = self._tmp_filename('resize-height.jpeg')
         img.save(filename, img.format)
         with Image.open(filename) as image:
             self.assertEqual(image.size[1], 200)
Ejemplo n.º 17
0
def img_resize(path, width: int = None, height: int = None):
    with open(path, 'r+b') as f:
        with Image.open(f) as img:
            if height and width:
                cover = resizeimage.resize_cover(img, (height, width))
            elif height:
                cover = resizeimage.resize_height(img, height)
            else:
                cover = resizeimage.resize_width(img, width)
            img.save(path + '.tmp', img.format)
    os.rename(path + '.tmp', path)
def _resize(inpath, outpath, width=None, height=None):
    with open(inpath, 'r+b') as infile:
        with Image.open(infile) as inimage:
            if width and height:
                thumb = resizeimage.resize_cover(inimage, [width, height])
            elif width:
                thumb = resizeimage.resize_width(inimage, width, validate=True)
            elif height:
                thumb = resizeimage.resize_height(inimage, height, validate=True)
            else:
                raise RuntimeError('at least width or height must be provided')
            thumb.save(outpath, inimage.format)
Ejemplo n.º 19
0
def upload_image(image, cover=False):

    image = b64decode(image.encode())
    extension = imghdr.what(None, h=image)
    filename = str(uuid4()) + "." + extension

    pic = io.BytesIO(image)
    with Image.open(pic) as image_pil:
        cover = resizeimage.resize_height(image_pil, 600, validate=False)
        cover.save("static/images/{}".format(filename), image_pil.format)

    return filename
Ejemplo n.º 20
0
def create_thumbnail(input_file: str, output_file: str, width: Optional[int],
                     height: Optional[int]) -> None:
    with open(input_file, 'rb') as fh:
        img = Image.open(fh)
        if width and height:
            img = resizeimage.resize_thumbnail(img, [width, height])
        elif width:
            img = resizeimage.resize_width(img, width)
        elif height:
            img = resizeimage.resize_height(img, height)
        else:
            raise ValueError('Width or height must be specified.')
        img.save(output_file)
Ejemplo n.º 21
0
def convert_image(image, width, height):
    """
    resize the image to the correct size needed by the template.
    """
    name = image.name
    pio = Image.open(image)
    if width is None:
        img = resizeimage.resize_height(pio, height, validate=False)
    else:
        img = resizeimage.resize_cover(pio, [width, height], validate=False)
    new_image_io = BytesIO()
    img.save(new_image_io, format=pio.format)
    image.delete(save=False)
    image.save(name, content=ContentFile(new_image_io.getvalue()), save=False)
Ejemplo n.º 22
0
def _load_data(filename):
    # Load an image
    load_image = Image.open(data_path + filename)

    #rescale the image so the smallest side (height) is 299
    re_image = resizeimage.resize_height(load_image, 299)

    # convert image to a numpy array
    image = np.asarray(re_image)

    # preprocess the image to the range that the model expects. [-1, 1]
    image = 2 * (image / 255.0) - 1.0

    return image
Ejemplo n.º 23
0
def _resize_image(final_image, width, height):
    orig_data = io.BytesIO(final_image)
    with Image.open(orig_data) as image:
        resized = None
        if width and height:
            resized = resizeimage.resize_cover(image, [width, height])
        elif width:
            resized = resizeimage.resize_width(image, width)
        elif height:
            resized = resizeimage.resize_height(image, height)
        resized_data = io.BytesIO()
        resized.save(resized_data, image.format)
        final_image = resized_data.getvalue()
    return final_image
Ejemplo n.º 24
0
def _resize_image(final_image, width, height):
    orig_data = io.BytesIO(final_image)
    with Image.open(orig_data) as image:
        resized = None
        if width and height:
            resized = resizeimage.resize_cover(image, [width, height])
        elif width:
            resized = resizeimage.resize_width(image, width)
        elif height:
            resized = resizeimage.resize_height(image, height)
        resized_data = io.BytesIO()
        resized.save(resized_data, image.format)
        final_image = resized_data.getvalue()
    return final_image
Ejemplo n.º 25
0
def imagegrabber(url):
    proxy = getProxy()
    data = requests.get(url, headers=hdr, proxies=proxy)
    image = Image.open(StringIO(data.content))

    if image.size[1] > 400:
        img = resizeimage.resize_height(image, 400)
        result = StringIO()
        format = "JPEG"
        img.save(result, format)
        image = result.getvalue()
    else:
        image = data.content
    return image
Ejemplo n.º 26
0
 def post(self, request, *args, **kwargs):
     image_data = request.data.get('image', None)
     description = request.data.get('description', '')
     r = check_too_many_reports()
     if r is not None:
         return r
     if image_data is not None:
         orig_image = image_data
         pil_image = Image.open(orig_image)
         width, height = pil_image.size
         max_dim = 1200
         if width > max_dim:
             pil_image = resizeimage.resize_width(pil_image, max_dim)
         elif height > max_dim:
             pil_image = resizeimage.resize_height(pil_image, max_dim)
         output = BytesIO()
         pil_image.save(output, format='JPEG', quality=100)
         output.seek(0)
         inmemory = InMemoryUploadedFile(output, 'image', 'a.jpg',
                                         'image/jpeg',
                                         output.getbuffer().nbytes, None)
         image_hash_text = imagehash.phash(pil_image)
         existed_object = get_or_none(ImageReport,
                                      image_hash=image_hash_text)
         if existed_object is not None:
             print(existed_object.__dict__)
             return Response(
                 {
                     'result': 'already_existed',
                     'key': existed_object.id,
                     'report': existed_object.image_hash
                 },
                 status=status.HTTP_201_CREATED)
         else:
             image_report = ImageReport()
             image_report.image_hash = image_hash_text
             image_report.image = inmemory
             image_report.description = description
             image_report.save()
             report = Report()
             report.report_type = 'image'
             report.image_report = image_report
             report.save()
             save_created_event(report)
             return Response({'key': report.id},
                             status=status.HTTP_201_CREATED)
     else:
         return Response({'reason': 'Image is invalid.'},
                         status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 27
0
def afficher(nomprogramme, db, fenetre, canvas, ordre, datedebut):
    cur = db.cursor()
    query = 'SELECT exercice.nom, exercice.description, exercice.image, muscle.nom, programme_exercice.nombre_repetition, programme_exercice.temps, programme_exercice.pause FROM programme_exercice JOIN exercice ON programme_exercice.exercice = exercice.ID JOIN muscle ON exercice.muscle = muscle.ID WHERE programme = (SELECT ID FROM programme WHERE nom = ?) AND ordre= ?'
    try:
        cur.execute(query, (nomprogramme, ordre))
        for var in cur:
            row = var
        canvas.delete('all')
        fenetre.title('lire programme')
        image = PhotoImage(file='image/fond.gif', master=fenetre)
        canvas.pack()
        canvas.create_image(550, 300, image=image)

        canvas.create_text(550, 50, text=row[0], font=("times new roman", 18))
        canvas.create_text(550, 100, text=row[1], font=("times new roman", 14))

        cheminimage = "image/" + str(row[2]) + ".gif"
        try:
            im = Image.open(cheminimage)
        except:
            im = Image.open("image/default.gif")

        if im.size[1] >= 235:
            cover = resizeimage.resize_height(im, 235)
            cover.save(cheminimage, im.format)
        imageexercice = PhotoImage(file=cheminimage, master=fenetre)
        canvas.create_image(550, 235, image=imageexercice)

        if row[5] != 0:
            timer = canvas.create_text(550, 450, text="", font=("times new roman", 18), justify=CENTER)
            updatetime(db, row[5], timer, canvas, fenetre, row[6], ordre, nomprogramme, datedebut)
            menu.menu_footer(fenetre, canvas, db)

        elif row[4] != 0:
            repetition = "Vous devez faire \n " + str(row[4]) + " \n repetitions pour terminer l'exercice"
            canvas.create_text(550, 400, text=repetition, font=("times new roman", 18), justify=CENTER)

            button = Button(fenetre, text="Passer à l'exercice suivant",
                            command=lambda: afficherpause(row[6], db, fenetre, canvas, ordre, nomprogramme, datedebut),
                            font=("times new roman", 20), background="#59C38D", borderwidth=0,
                            activebackground="#2FB5A3")
            canvas.create_window(550, 500, window=button)
            menu.menu_footer(fenetre, canvas, db)

        else:
            afficherpause(row[6], db, fenetre, canvas, ordre, nomprogramme, datedebut)
            menu.menu_footer(fenetre, canvas, db)
    except:
        terminer(datedebut, nomprogramme, db, fenetre, canvas)
Ejemplo n.º 28
0
 def create_thumbnail(self):
     """Create thumbnail(s) for provided image"""
     try:
         image_file = Image.open(self.image_path)
         #for tile_height in THUMBNAIL_HEIGHT:
         #    for tile_format in THUMBNAIL_FORMAT:
         thumbnail = resizeimage.resize_height(image_file, app_config.THUMBNAIL_HEIGHT)
         thumbnail.save(self.thumbnail_path)
     except Exception as ex:
         exc_type = ex.__class__.__name__
         self.errors.append("IMG: Unable to create thumbnail image [" + self.file_name
                            + "] Exception Type: " + str(exc_type) + " Error: " + str(ex))
     finally:
         if image_file is not None:
             image_file.close()
Ejemplo n.º 29
0
def resize(filename, height=None):
    """
    Resize the image to a certain proportion by height
    :param filename: string path of file to the image
    :param height: int
    :return: new filename of the image
    """
    if height is None:
        return filename
    print("Resizing %s to %spx height..." % (filename, height))
    with open(filename, 'r+b') as f:
        with Image.open(f) as image:
            cover = resizeimage.resize_height(image, height)
            new_filename = filename + '.res'
            cover.save(new_filename, image.format)
    return new_filename
Ejemplo n.º 30
0
 def buttonClicked(self):  #needs finishing
     #print "goButton clicked"
     global designingCarPark, globalMapImage
     globalMapImage = resizeimage.resize_height(images[globalMapName],
                                                imageHeight)
     designingCarPark = False
     listOfGroupsOfCoordinatesForLines = processingCode.GetCarParkPixelLinesToDrawFromPixelShape(
         carParkShape, pixelsPerMeter)
     draw = ImageDraw.Draw(globalMapImage)
     listOfCoordinates = carParkShape.getVerticesCoordinates()
     for eachGroupOfCoordinatesForLines in listOfGroupsOfCoordinatesForLines:
         print "eachGroupOfCoordinatesForLines:"
         print eachGroupOfCoordinatesForLines
         draw.line(eachGroupOfCoordinatesForLines)
     del draw
     refreshWindow()
Ejemplo n.º 31
0
def resize(filename, height=None):
    """
    Resize the image to a certain proportion by height
    :param filename: string path of file to the image
    :param height: int
    :return: new filename of the image
    """
    if height is None:
        return filename
    print("Resizing %s to %spx height..." % (filename, height))
    with open(filename, 'r+b') as f:
        with Image.open(f) as image:
            cover = resizeimage.resize_height(image, height)
            new_filename = filename + '.res'
            cover.save(new_filename, image.format)
    return new_filename
Ejemplo n.º 32
0
def resize_image(images_list):
    for image_file in images_list:
        with open(image_file, 'r+b') as f:
            with Image.open(f) as image:
                try:
                    width, height = image.size
                    if height >= width:
                        cover = resizeimage.resize_height(image, 512)
                    else:
                        cover = resizeimage.resize_width(image, 512)
                    save_files(cover, image_file, image)
                except imageexceptions.ImageSizeError:
                    print(
                        colored(
                            f"Image {image_file} is too small to be resized! ({width}x{height})",
                            'red'))
                    save_files(image, image_file, image)
Ejemplo n.º 33
0
def convert_image(image, width, height):
    """
    resize the image to the correct size needed by the template.
    """
    name = image.name
    pio = Image.open(image)
    if width is None:
        img = resizeimage.resize_height(pio, height, validate=False)
    else:
        img = resizeimage.resize_cover(pio, [width, height], validate=False)
    new_image_io = BytesIO()
    img.save(new_image_io, format=pio.format)
    image.delete(save=False)
    image.save(
        name,
        content=ContentFile(new_image_io.getvalue()),
        save=False
    )
Ejemplo n.º 34
0
    def upload_image_to_s3(self, image_path, relative_dir, cdn_bucket, sizes=[(None,None),(320,None),(640,None),(1280,None)]):
        """Uploads the provided image into S3 in multiple sizes if the file doesn't already exist.
        Returns an array of (path, width) tuples"""
        image_path = image_path.replace('./', '')

        with open(os.path.normpath(os.path.join(relative_dir, image_path)), 'r+b') as f:
            with Image.open(f) as image:
                image_s3_path = os.path.join('static/', 'images/', image_path)
                images = [(self.add_suffix_to_filename(image_s3_path, size[0]), size) for size in sizes]

                # If the hash of the image locally matches what is in s3, there
                # is no need to upload again so return immediately
                local_hash = self.md5_checksum(self.img_to_bytes(image))
                s3_hash = self.get_s3_etag(cdn_bucket, image_s3_path)
                if local_hash == s3_hash:
                    # Finally check that the files for all of the sizes we are going
                    # to make exist as well
                    tags = [self.get_s3_etag(cdn_bucket, path) for path, size in images]
                    if None not in tags:
                        return images

                for (path, size) in images:
                    # If size is None then we are keeping the original resolution
                    image_sized = image
                    if size != (None, None):
                        x, y = size
                        if x is not None and y is not None:
                            image_sized = resizeimage.resize_cover(image, [x, y], validate=False)
                        elif y is not None:
                            image_sized = resizeimage.resize_height(image, y, validate=False)
                        else:
                            image_sized = resizeimage.resize_width(image, x, validate=False)

                    # Save the image to a byte array and upload to S3
                    print("> Uploading", path)
                    cdn_bucket.upload_fileobj(
                        self.img_to_bytes(image_sized),
                        path,
                        ExtraArgs={'ACL':'public-read', 'ContentType': Image.MIME[image_sized.format]}
                    )

        return images
Ejemplo n.º 35
0
    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
                ]
Ejemplo n.º 36
0
    def save(self, *args, **kwargs):
        pil_image_obj = Image.open(self.logo_image)
        new_image = resizeimage.resize_height(
            pil_image_obj,
            35,
            validate=False
        )

        new_image_io = BytesIO()
        new_image.save(new_image_io, format='PNG')

        temp_name = self.logo_image.name
        self.logo_image.delete(save=False)

        self.logo_image.save(
            temp_name,
            content=ContentFile(new_image_io.getvalue()),
            save=False
        )

        super(LogoImage, self).save(*args, **kwargs)
Ejemplo n.º 37
0
def edit_original(big_image, generator):
    """
    Takes in a full-sized image and runs the generator on a smaller version.
    Returns an edited version of the full-sized image.
    """
    logging.info("Resizing")
    resized = resize(big_image, (hp.img_size, hp.img_size)).astype(np.float32)
    logging.info("Running generator")
    prob, _ = generator(resized[None])
    logging.info("Scaling action space")
    act_scaled, _ = generator.convert_prob_act(prob.numpy(),
                                               det=True,
                                               det_avg=hp.det_avg)
    logging.info(big_image.shape)
    if big_image.shape[0] > 400:
        resized = resizeimage.resize_height(Image.fromarray(big_image), 400)
    elif big_image.shape[1] > 400:
        resized = resizeimage.resize_width(Image.fromarray(big_image), 400)
    resized = np.array(resized)
    orig_edit = PhotoEditor.edit((resized / 255)[None], act_scaled)
    return orig_edit[0]
Ejemplo n.º 38
0
 def test_can_not_resize_larger_height(self):
     with self._open_test_image() as img:
         with self.assertRaises(ImageSizeError):
             resizeimage.resize_height(img, 534)
Ejemplo n.º 39
0
import sys
from PIL import Image
from io import BytesIO

import yaml
import requests
from resizeimage import resizeimage
from slugify import slugify

shows = yaml.load(sys.stdin)

for show in shows:
    slug = slugify(show['title'])
    filename = '../img/shows/' + slug + '.jpg'

    response = requests.get(show['thumbnail'])
    with Image.open(BytesIO(response.content)) as img:
        img_resized = resizeimage.resize_height(img, 425)
        img_resized.save(filename, img_resized.format)