Python PIL图片如何按比例裁剪

目录
  • PIL图片如何按比例裁剪
    • 问题描述
    • 解决方案
  • PIL调整图片大小
    • 介绍
    • 看代码吧

PIL图片如何按比例裁剪

问题描述

如图片比例为 1:1 裁剪为 4:3

1.jpg

解决方案

from PIL import Image
def image_clip(filename, savename, width_scale, height_scale):
    """图像裁剪
    :param filename: 原图路径
    :param savename: 保存图片路径
    :param width_scale: 宽的比例
    :param height_scale: 高的比例
    """
    image = Image.open(filename)
    (width, height), (_width, _height) = image.size, image.size
    _height = width / width_scale * height_scale
    if _height > height:
        _height = height
        _width = width_scale * height / height_scale
    image.crop((0, 0, _width, _height)).save(savename)  # 左上角
    # image.crop((0, height - _height, _width, height)).save(savename)  # 左下角
    # image.crop((width - _width, 0, width, _height)).save(savename)  # 右上角
    # image.crop((width - _width, height - _height, width, height)).save(savename)  # 右下角
if __name__ == '__main__':
    filename = '1.jpg'
    savename = 'result.jpg'
    image_clip(filename, savename, width_scale=4, height_scale=3)
    # image_clip(filename, savename, width_scale=3, height_scale=4)

效果

PIL调整图片大小

使用 PIL 在图片比例不变的情况下修改图片大小。

介绍

Image.resize

def resize(self, size, resample=BICUBIC, box=None, reducing_gap=None):
    """
    Returns a resized copy of this image.
    返回此图像的大小调整后的副本。
    :param size: The requested size in pixels, as a 2-tuple:
       (width, height).
     param size: 请求的大小(以像素为单位),是一个二元数组:(width, height)
    :param resample: An optional resampling filter.  This can be
       one of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BOX`,
       :py:attr:`PIL.Image.BILINEAR`, :py:attr:`PIL.Image.HAMMING`,
       :py:attr:`PIL.Image.BICUBIC` or :py:attr:`PIL.Image.LANCZOS`.
       Default filter is :py:attr:`PIL.Image.BICUBIC`.
       If the image has mode "1" or "P", it is
       always set to :py:attr:`PIL.Image.NEAREST`.
       See: :ref:`concept-filters`.
     param resample: 一个可选的重采样过滤器。
    :param box: An optional 4-tuple of floats providing
       the source image region to be scaled.
       The values must be within (0, 0, width, height) rectangle.
       If omitted or None, the entire source is used.
     param box: 可选的4元浮点数,提供要缩放的源映像区域。
    :param reducing_gap: Apply optimization by resizing the image
       in two steps. First, reducing the image by integer times
       using :py:meth:`~PIL.Image.Image.reduce`.
       Second, resizing using regular resampling. The last step
       changes size no less than by ``reducing_gap`` times.
       ``reducing_gap`` may be None (no first step is performed)
       or should be greater than 1.0. The bigger ``reducing_gap``,
       the closer the result to the fair resampling.
       The smaller ``reducing_gap``, the faster resizing.
       With ``reducing_gap`` greater or equal to 3.0, the result is
       indistinguishable from fair resampling in most cases.
       The default value is None (no optimization).
     param reducing_gap: 通过两个步骤调整图像大小来应用优化。
    :returns: An :py:class:`~PIL.Image.Image` object.
     returns: 返回一个 PIL.Image.Image 对象
    """

看代码吧

from PIL import Image

image = Image.open('图片路径')

# 调整图片大小,并保持比例不变
# 给定一个基本宽度
base_width = 50

# 基本宽度与原图宽度的比例
w_percent = base_width / float(image.size[0])

# 计算比例不变的条件下新图的长度
h_size = int(float(image.size[1]) * float(w_percent))

# 重新设置大小
# 默认情况下,PIL使用Image.NEAREST过滤器进行大小调整,从而获得良好的性能,但质量很差。
image = image.resize((base_width, h_size), Image.ANTIALIAS)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • python PIL和CV对 图片的读取,显示,裁剪,保存实现方法

    PIL 图片操作 读取图片 img = Image.open("a.jpg") 显示图片 im.show() # im是Image对象,im是numpy类型,通过Image.fromarray(nparr, mode='RGB')函数转换为Image对象 图片的size (width, height) = img.size 图片的模式 mode = img.mode 截区域 img_c = img.crop(x1,y1,x2,y2) 裁剪图片 img = img.resize((siz

  • python使用pil进行图像处理(等比例压缩、裁剪)实例代码

    PIL中设计的几个基本概念 1.通道(bands):即使图像的波段数,RGB图像,灰度图像 以RGB图像为例: >>>from PIL import Image >>>im = Image.open('*.jpg') # 打开一张RGB图像 >>>im_bands = im.g etbands() # 获取RGB三个波段 >>>len(im_bands) >>>print im_bands[0,1,2] # 输出RG

  • python使用PIL剪切和拼接图片

    本文实例为大家分享了python使用PIL剪切图片和拼接图片的具体代码,供大家参考,具体内容如下 因工作需要,接触到了PIL这个包,看其他人的博客踩了一些坑,有些博客并没有注明各个位置参数的含义,今天我就将他补全 切图 1.首先先下载一张图片,我使用的是1200*1200像素的图片,将它放置在G盘的img目录下 2.  我将这张图片切成四等分,我新建了两个文件,分别是img1.img2,用来存放图片 3. 代码 from PIL import Image img = Image.open('G:

  • Python实现图片裁剪的两种方式(Pillow和OpenCV)

    在这篇文章里我们聊一下Python实现图片裁剪的两种方式,一种利用了Pillow,还有一种利用了OpenCV.两种方式都需要简单的几行代码,这可能也就是现在Python那么流行的原因吧. 首先,我们有一张原始图片,如下图所示: 原始图片 然后,我们利用OpenCV对其进行裁剪,代码如下所示: import cv2 img = cv2.imread("./data/cut/thor.jpg") print(img.shape) cropped = img[0:128, 0:512] #

  • Python PIL图片如何按比例裁剪

    目录 PIL图片如何按比例裁剪 问题描述 解决方案 PIL调整图片大小 介绍 看代码吧 PIL图片如何按比例裁剪 问题描述 如图片比例为 1:1 裁剪为 4:3 1.jpg 解决方案 from PIL import Image def image_clip(filename, savename, width_scale, height_scale): """图像裁剪 :param filename: 原图路径 :param savename: 保存图片路径 :param wi

  • Python PIL图片添加字体的例子

    效果 左边原图,右面添加字体后保存的图. 代码 # -*- coding: utf-8 -*- import PIL.Image as Image import PIL.ImageColor as ImageColor import PIL.ImageDraw as ImageDraw import PIL.ImageFont as ImageFont """ author@:xuna python2.7 """ #设置字体(Liberation

  • python 实现图片裁剪小工具

    完整项目地址下载:https://github.com/rainbow-tan/rainbow/tree/master/%E8%A3%81%E5%89%AA%E5%9B%BE%E7%89%87 实现:tkinter 画布上显示图片,按下鼠标左键并且移动,实现截图 # -*- encoding=utf-8 -*- import os import tkinter as tk from PIL import Image from PIL import ImageTk left_mouse_down_

  • Android 以任意比例裁剪图片代码分享

    公司的一个小伙伴写的,可以按照任意比例裁剪图片.我觉得挺好用的.简单在这里记录一下,以后肯定还会用到. public class SeniorCropImageView extends ImageView implements ScaleGestureDetector.OnScaleGestureListener, View.OnLayoutChangeListener { /* For drawing color field start */ private static final int

  • 基于RxPaparazzo实现图片裁剪、图片旋转、比例放大缩小功能

    前言:基于RxPaparazzo的图片裁剪,图片旋转.比例放大|缩小. 效果: 开发环境:AndroidStudio2.2.1+gradle-2.14.1 涉及知识: 1.Material Design (CardView+CoordinatorLayout+AppBarLayout+NestedScrollView+CollapsingToolbarLayout+Toolbar+FloatingActionButton)使用 2.butterknife注解式开发 3.基于RxJava+RxAn

  • PHP实现图片不变型裁剪及图片按比例裁剪的方法

    本文实例讲述了PHP实现图片不变型裁剪及图片按比例裁剪的方法.分享给大家供大家参考,具体如下: 图片不变型裁剪 <?php /** * imageCropper * @param string $source_path * @param string $target_width * @param string $target_height */ function imageCropper($source_path, $target_width, $target_height){ $source_

  • Python PIL库图片灰化处理

    2020年4月4日,是个特殊的日子,我们看到朋友圈很多灰化的图片.今天我们就聊聊图片灰度处理这事儿. PIL的基本概念: PIL中所涉及的基本概念有如下几个:通道(bands).模式(mode).尺寸(size).坐标系统(coordinate system).调色板(palette).信息(info)和滤波器(filters). PIL(Python Image Library)是python的第三方图像处理库,但是由于其强大的功能与众多的使用人数,几乎已经被认为是python官方图像处理库了

随机推荐