当前位置: 首页>>代码示例>>Python>>正文


Python ImageOps.fit方法代码示例

本文整理汇总了Python中PIL.ImageOps.fit方法的典型用法代码示例。如果您正苦于以下问题:Python ImageOps.fit方法的具体用法?Python ImageOps.fit怎么用?Python ImageOps.fit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PIL.ImageOps的用法示例。


在下文中一共展示了ImageOps.fit方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: resize_gif

# 需要导入模块: from PIL import ImageOps [as 别名]
# 或者: from PIL.ImageOps import fit [as 别名]
def resize_gif(im: GifImageFile, size: int=DEFAULT_EMOJI_SIZE) -> bytes:
    frames = []
    duration_info = []
    # If 'loop' info is not set then loop for infinite number of times.
    loop = im.info.get("loop", 0)
    for frame_num in range(0, im.n_frames):
        im.seek(frame_num)
        new_frame = Image.new("RGBA", im.size)
        new_frame.paste(im, (0, 0), im.convert("RGBA"))
        new_frame = ImageOps.fit(new_frame, (size, size), Image.ANTIALIAS)
        frames.append(new_frame)
        duration_info.append(im.info['duration'])
    out = io.BytesIO()
    frames[0].save(out, save_all=True, optimize=True,
                   format="GIF", append_images=frames[1:],
                   duration=duration_info,
                   loop=loop)
    return out.getvalue() 
开发者ID:zulip,项目名称:zulip,代码行数:20,代码来源:upload.py

示例2: download_image

# 需要导入模块: from PIL import ImageOps [as 别名]
# 或者: from PIL.ImageOps import fit [as 别名]
def download_image(url, title):
    uaurl = request.Request(url, headers={'User-Agent': 'wallpaper-reddit python script by /u/MarcusTheGreat7'})
    f = request.urlopen(uaurl)
    print("downloading " + url)
    try:
        img = Image.open(f).convert('RGB')
        if config.resize:
            config.log("resizing the downloaded wallpaper")
            img = ImageOps.fit(img, (config.minwidth, config.minheight), Image.ANTIALIAS)
        if config.settitle:
            img = set_image_title(img, title)
        if config.opsys == "Windows":
            img.save(config.walldir + '\\wallpaper.bmp', "BMP")
        else:
            img.save(config.walldir + '/wallpaper.jpg', "JPEG")

    except IOError:
        print("Error saving image!")
        sys.exit(1)


# in - string, string - path of the image to set title on, title for image 
开发者ID:markubiak,项目名称:wallpaper-reddit,代码行数:24,代码来源:download.py

示例3: multi_setup_pillow

# 需要导入模块: from PIL import ImageOps [as 别名]
# 或者: from PIL.ImageOps import fit [as 别名]
def multi_setup_pillow(monitors, save_path, wp_setter_func=None):
    images = list(map(Image.open, [m.wallpaper for m in monitors]))
    resolutions = [(m.width * m.scaling, m.height * m.scaling) for m in monitors]
    offsets = [(m.offset_x, m.offset_y) for m in monitors]

    # DEBUG
    # for m in monitors:
    #     print(m)

    final_image_width = max([m.offset_x + m.width * m.scaling for m in monitors])
    final_image_height = max([m.offset_y + m.height * m.scaling for m in monitors])

    # DEBUG
    # print('Final Size: {} x {}'.format(final_image_width, final_image_height))

    n_images = []
    for i, r in zip(images, resolutions):
        n_images.append(fit(i, r, method=Image.LANCZOS))
    final_image = Image.new('RGB', (final_image_width, final_image_height))
    for i, o in zip(n_images, offsets):
        final_image.paste(i, o)
    final_image.save(save_path) 
开发者ID:GabMus,项目名称:HydraPaper,代码行数:24,代码来源:wallpaper_merger.py

示例4: get_img_batch

# 需要导入模块: from PIL import ImageOps [as 别名]
# 或者: from PIL.ImageOps import fit [as 别名]
def get_img_batch(files_list,
                  secret_size,
                  batch_size=4,
                  size=(400,400)):

    batch_cover = []
    batch_secret = []

    for i in range(batch_size):
        img_cover_path = random.choice(files_list)
        try:
            img_cover = Image.open(img_cover_path).convert("RGB")
            img_cover = ImageOps.fit(img_cover, size)
            img_cover = np.array(img_cover, dtype=np.float32) / 255.
        except:
            img_cover = np.zeros((size[0],size[1],3), dtype=np.float32)
        batch_cover.append(img_cover)

        secret = np.random.binomial(1, .5, secret_size)
        batch_secret.append(secret)

    batch_cover, batch_secret = np.array(batch_cover), np.array(batch_secret)
    return batch_cover, batch_secret 
开发者ID:tancik,项目名称:StegaStamp,代码行数:25,代码来源:train.py

示例5: forward

# 需要导入模块: from PIL import ImageOps [as 别名]
# 或者: from PIL.ImageOps import fit [as 别名]
def forward(self, input_image):
        (width, height) = (self.width, self.height)

        # Resize image to work with neural network.
        if height < input_image.height < input_image.width:
            new_height = height
            new_width = new_height * input_image.width // input_image.height
        else:
            new_width = width
            new_height = new_width * input_image.height // input_image.width

        image = input_image.resize((new_width, new_height), Image.ANTIALIAS)
        image = ImageOps.fit(image, (width, height), Image.ANTIALIAS)

        # Generate predictions.
        image_tensor = torch.Tensor(np.array(image) / 255.0)
        input_image = image_tensor.permute(2, 0, 1)
        image_normalized = self.preprocess(input_image)
        out = self.net(image_normalized[None, :, :, :].to(self.device))
        return out 
开发者ID:airalcorn2,项目名称:strike-with-a-pose,代码行数:22,代码来源:strike_utils.py

示例6: generate_ascii

# 需要导入模块: from PIL import ImageOps [as 别名]
# 或者: from PIL.ImageOps import fit [as 别名]
def generate_ascii(self, image):
        font = ImageFont.truetype(str(cog_data_path(self)) + "/FreeMonoBold.ttf", 15)
        image_width, image_height = image.size
        aalib_screen_width = int(image_width / 24.9) * 10
        aalib_screen_height = int(image_height / 41.39) * 10
        screen = aalib.AsciiScreen(width=aalib_screen_width, height=aalib_screen_height)

        im = image.convert("L").resize(screen.virtual_size)
        screen.put_image((0, 0), im)
        y = 0
        how_many_rows = len(screen.render().splitlines())
        new_img_width, font_size = font.getsize(screen.render().splitlines()[0])
        img = Image.new("RGBA", (new_img_width, how_many_rows * 15), (255, 255, 255))
        draw = ImageDraw.Draw(img)
        for lines in screen.render().splitlines():
            draw.text((0, y), lines, (0, 0, 0), font=font)
            y += 15
        imagefit = ImageOps.fit(img, (image_width, image_height), Image.ANTIALIAS)
        return imagefit 
开发者ID:TrustyJAID,项目名称:Trusty-cogs,代码行数:21,代码来源:notsobot.py

示例7: save

# 需要导入模块: from PIL import ImageOps [as 别名]
# 或者: from PIL.ImageOps import fit [as 别名]
def save(self, data, file_id=None, metadata={}, THUMB_SIZE=()):
        if file_id is None:
            file_id = unicode(uuid.uuid4())
        with open(self._get_filename(file_id), "w") as f:
            f.write(data)
        # Store metadata
        with open(self._get_metadata_filename(file_id), "w") as f:
            f.write(json.dumps(metadata))

        img = None
        try:
            img = Image.open(self._get_filename(file_id))
        except IOError:
            log.info('Not an image file, skipping medium & thumbnail generation')
        else:
            # Store thumbnail & medium
            kw = {}
            if 'transparency' in img.info:
                kw['transparency'] = img.info["transparency"]

            orig_width, orig_height = img.size

            medium_size = self.MEDIUM_WIDTH, int(float(self.MEDIUM_WIDTH) * orig_height / orig_width)
            medium = img.copy()

            medium.thumbnail(medium_size, Image.ANTIALIAS)
            medium.save(self._get_filename(file_id, 'medium'), img.format, quality=75, **kw)  # 'JPEG')

            thumb = ImageOps.fit(img, THUMB_SIZE if THUMB_SIZE else self.THUMB_SIZE, Image.ANTIALIAS)
            thumb.save(self._get_filename(file_id, 'thumb'), img.format, quality=75, **kw)  # 'JPEG')
        return file_id 
开发者ID:Net-ng,项目名称:kansha,代码行数:33,代码来源:simpleassetsmanager.py

示例8: resize_avatar

# 需要导入模块: from PIL import ImageOps [as 别名]
# 或者: from PIL.ImageOps import fit [as 别名]
def resize_avatar(image_data: bytes, size: int=DEFAULT_AVATAR_SIZE) -> bytes:
    try:
        im = Image.open(io.BytesIO(image_data))
        im = exif_rotate(im)
        im = ImageOps.fit(im, (size, size), Image.ANTIALIAS)
    except OSError:
        raise BadImageError(_("Could not decode image; did you upload an image file?"))
    except DecompressionBombError:
        raise BadImageError(_("Image size exceeds limit."))
    out = io.BytesIO()
    if im.mode == 'CMYK':
        im = im.convert('RGB')
    im.save(out, format='png')
    return out.getvalue() 
开发者ID:zulip,项目名称:zulip,代码行数:16,代码来源:upload.py

示例9: resize_emoji

# 需要导入模块: from PIL import ImageOps [as 别名]
# 或者: from PIL.ImageOps import fit [as 别名]
def resize_emoji(image_data: bytes, size: int=DEFAULT_EMOJI_SIZE) -> bytes:
    try:
        im = Image.open(io.BytesIO(image_data))
        image_format = im.format
        if image_format == "GIF":
            # There are a number of bugs in Pillow.GifImagePlugin which cause
            # results in resized gifs being broken. To work around this we
            # only resize under certain conditions to minimize the chance of
            # creating ugly gifs.
            should_resize = any((
                im.size[0] != im.size[1],                            # not square
                im.size[0] > MAX_EMOJI_GIF_SIZE,                     # dimensions too large
                len(image_data) > MAX_EMOJI_GIF_FILE_SIZE_BYTES,     # filesize too large
            ))
            return resize_gif(im, size) if should_resize else image_data
        else:
            im = exif_rotate(im)
            im = ImageOps.fit(im, (size, size), Image.ANTIALIAS)
            out = io.BytesIO()
            im.save(out, format=image_format)
            return out.getvalue()
    except OSError:
        raise BadImageError(_("Could not decode image; did you upload an image file?"))
    except DecompressionBombError:
        raise BadImageError(_("Image size exceeds limit."))


### Common 
开发者ID:zulip,项目名称:zulip,代码行数:30,代码来源:upload.py

示例10: test_1pxfit

# 需要导入模块: from PIL import ImageOps [as 别名]
# 或者: from PIL.ImageOps import fit [as 别名]
def test_1pxfit(self):
        # Division by zero in equalize if image is 1 pixel high
        newimg = ImageOps.fit(hopper("RGB").resize((1, 1)), (35, 35))
        self.assertEqual(newimg.size, (35, 35))

        newimg = ImageOps.fit(hopper("RGB").resize((1, 100)), (35, 35))
        self.assertEqual(newimg.size, (35, 35))

        newimg = ImageOps.fit(hopper("RGB").resize((100, 1)), (35, 35))
        self.assertEqual(newimg.size, (35, 35)) 
开发者ID:holzschu,项目名称:python3_ios,代码行数:12,代码来源:test_imageops.py

示例11: update_preview

# 需要导入模块: from PIL import ImageOps [as 别名]
# 或者: from PIL.ImageOps import fit [as 别名]
def update_preview(self, widget):
		if self.item:
			#get a crop for the preview
			#box = tuple((int(round(v)) for v in widget.coords(self.item)))
			box = self.getRealBox()
			pbox = self.getPreviewBox()
			if fast_preview:
				preview = self.image.crop(pbox) # region of interest
			else:
				preview = self.imageOrig.crop(box) # region of interest

			#add black borders for correct aspect ratio
			#if preview.size[0] > 512:
			preview.thumbnail(self.image.size, Image.ANTIALIAS) #downscale to preview rez
			paspect = preview.size[0]/float(preview.size[1])
			aspect = self.image.size[0]/float(self.image.size[1])
			if paspect < aspect:
				bbox = (0, 0, int(preview.size[1] * aspect), preview.size[1])
			else:
				bbox = (0, 0, preview.size[0], int(preview.size[0] / aspect))
			preview = ImageOps.expand(preview, border=((bbox[2]-preview.size[0])//2, (bbox[3]-preview.size[1])//2))
			#preview = ImageOps.fit(preview, size=self.image.size, method=Image.ANTIALIAS, bleed=-10.0)

			#resize to preview rez (if too small)
			self.preview = preview.resize(self.image.size, Image.ANTIALIAS)
			self.previewPhoto = ImageTk.PhotoImage(self.preview)
			self.previewLabel.configure(image=self.previewPhoto)

			print str(box[2]-box[0])+"x"+str(box[3]-box[1])+"+"+str(box[0])+"+"+str(box[1]) 
开发者ID:pknowles,项目名称:cropall,代码行数:31,代码来源:cropall.py

示例12: process_image

# 需要导入模块: from PIL import ImageOps [as 别名]
# 或者: from PIL.ImageOps import fit [as 别名]
def process_image(self, image, image_format, save_kwargs,
                      width, height):
        """
        Return a BytesIO instance of `image` cropped to `width` and `height`.

        Cropping will first reduce an image down to its longest side
        and then crop inwards centered on the Primary Point of Interest
        (as specified by `self.ppoi`)
        """
        imagefile = BytesIO()
        palette = image.getpalette()
        cropped_image = self.crop_on_centerpoint(
            image,
            width,
            height,
            self.ppoi
        )

        # Using ImageOps.fit on GIFs can introduce issues with their palette
        # Solution derived from: http://stackoverflow.com/a/4905209/1149774
        if image_format == 'GIF':
            cropped_image.putpalette(palette)

        cropped_image.save(
            imagefile,
            **save_kwargs
        )

        return imagefile 
开发者ID:respondcreate,项目名称:django-versatileimagefield,代码行数:31,代码来源:versatileimagefield.py

示例13: download_and_resize_image

# 需要导入模块: from PIL import ImageOps [as 别名]
# 或者: from PIL.ImageOps import fit [as 别名]
def download_and_resize_image(url, new_width=256, new_height=256,
                              display=False):
  _, filename = tempfile.mkstemp(suffix=".jpg")
  response = urlopen(url)
  image_data = response.read()
  image_data = BytesIO(image_data)
  pil_image = Image.open(image_data)
  pil_image = ImageOps.fit(pil_image, (new_width, new_height), Image.ANTIALIAS)
  pil_image_rgb = pil_image.convert("RGB")
  pil_image_rgb.save(filename, format="JPEG", quality=90)
  print("Image downloaded to %s." % filename)
  if display:
    display_image(pil_image)
  return filename 
开发者ID:mogoweb,项目名称:aiexamples,代码行数:16,代码来源:object_detection.py

示例14: resize_imgs

# 需要导入模块: from PIL import ImageOps [as 别名]
# 或者: from PIL.ImageOps import fit [as 别名]
def resize_imgs(self, path):
        for i, img_path in enumerate(glob.glob(path)):
            print(i, img_path)
            img = Image.open(img_path)
            img = ImageOps.fit(img, (self.img_size[0], self.img_size[1]), Image.ANTIALIAS)
            name = img_path.split("\\")[-1].split('.')[0]
            if not os.path.exists(f"resized_{self.img_size[0]}_{self.img_size[1]}"):
                os.makedirs(f"resized_{self.img_size[0]}_{self.img_size[1]}")
            img.save(f"resized_{self.img_size[0]}_{self.img_size[1]}/{name}.png") 
开发者ID:mitchelljy,项目名称:DCGAN-Keras,代码行数:11,代码来源:resize_imgs.py

示例15: image_to_tensor

# 需要导入模块: from PIL import ImageOps [as 别名]
# 或者: from PIL.ImageOps import fit [as 别名]
def image_to_tensor(pil_image):
    #resize image
    resized=ImageOps.fit(pil_image, imgsize, Image.ANTIALIAS)
    # transform it into a torch tensor
    loader = transforms.Compose([
        transforms.ToTensor()])
    return loader(resized).unsqueeze(0) #need to add one dimension, need to be 4D to pass into the network

#load model 
开发者ID:jaroslaw-weber,项目名称:hotdog-not-hotdog,代码行数:11,代码来源:not_hotdog_model.py


注:本文中的PIL.ImageOps.fit方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。