Python實現圖片自定義裁剪小工具

前言

本文提供將圖片按照自定義尺寸進行裁剪的工具方法,一如既往的實用主義。

環境依賴

ffmpeg環境安裝,可以參考:在Windows上安裝FFmpeg程序的圖文方法

本文主要使用到的不是ffmpeg,而是ffprobe也在上面這篇文章中的zip包中。

ffmpy安裝:

pip install ffmpy -i https://pypi.douban.com/simple

代碼

不廢話瞭,上代碼。

#!/user/bin/env python
# coding=utf-8
"""
@project : csdn
@author  : 劍客阿良_ALiang
@file   : cut_out_pic_tool.py
@ide    : PyCharm
@time   : 2022-01-20 10:38:53
"""
import os
import uuid
from ffmpy import FFmpeg


# 圖片裁剪
def cut_out_pic(image_path: str, output_dir: str, start_pix: tuple, size: tuple):
    ext = os.path.basename(image_path).strip().split('.')[-1]
    if ext not in ['png', 'jpg']:
        raise Exception('format error')
    result = os.path.join(output_dir, '{}.{}'.format(uuid.uuid1().hex, ext))
    ff = FFmpeg(inputs={image_path: None},
                outputs={result: '-vf crop={}:{}:{}:{} -y'.format(size[0], size[1], start_pix[0], start_pix[1])})
    print(ff.cmd)
    ff.run()
    return result


if __name__ == '__main__':
    cut_out_pic(r'C:\Users\huyi\Desktop\231.jpg', r'C:\Users\huyi\Desktop', (1000, 1000), (1000, 1000))

代碼說明

1、cut_out_pic方法參數分別為,圖片地址、輸出目錄地址、起始像素點位置、需要裁剪的寬高。

2、做瞭簡單的圖片格式校驗,如需添加,可以自己看著來。

3、最終圖片名使用uuid避免重復。

4、截取的圖片寬高不能超過圖片大小。

驗證一下

準備的圖片

執行結果

C:\Users\huyi.conda\envs\python36\python.exe "C:\Program Files\JetBrains\PyCharm 2020.1.3\plugins\python\helpers\pydev\pydevconsole.py" --mode=client --port=3635
import sys; print('Python %s on %s' % (sys.version, sys.platform))
sys.path.extend(['D:\spyder\csdn', 'D:/spyder/csdn'])
PyDev console: starting.
Python 3.6.13 |Anaconda, Inc.| (default, Mar 16 2021, 11:37:27) [MSC v.1916 64 bit (AMD64)] on win32
runfile('D:/spyder/csdn/cut_out_pic_tool.py', wdir='D:/spyder/csdn')
ffmpeg -i C:\Users\huyi\Desktop\231.jpg -vf crop=1000:1000:1000:1000 -y C:\Users\huyi\Desktop\6e81cb7a79cb11ec96d7e454e8bf1461.jpg
ffmpeg version n4.3.1-20-g8a2acdc6da Copyright (c) 2000-2020 the FFmpeg developers
  built with gcc 9.3-win32 (GCC) 20200320
  configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-iconv --enable-zlib --enable-libxml2 --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvmaf --disable-vulkan --enable-libvorbis --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-ffnvcodec --enable-cuda-llvm --disable-libglslang --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libtwolame --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-libs=-lgomp
  libavutil      56. 51.100 / 56. 51.100
  libavcodec     58. 91.100 / 58. 91.100
  libavformat    58. 45.100 / 58. 45.100
  libavdevice    58. 10.100 / 58. 10.100
  libavfilter     7. 85.100 /  7. 85.100
  libswscale      5.  7.100 /  5.  7.100
  libswresample   3.  7.100 /  3.  7.100
  libpostproc    55.  7.100 / 55.  7.100
Input #0, image2, from 'C:\Users\huyi\Desktop\231.jpg':
  Duration: 00:00:00.04, start: 0.000000, bitrate: 181614 kb/s
    Stream #0:0: Video: mjpeg (Progressive), yuvj444p(pc, bt470bg/unknown/unknown), 2560x1440, 25 tbr, 25 tbn, 25 tbc
Stream mapping:
  Stream #0:0 -> #0:0 (mjpeg (native) -> mjpeg (native))
Press [q] to stop, [?] for help
Output #0, image2, to 'C:\Users\huyi\Desktop\6e81cb7a79cb11ec96d7e454e8bf1461.jpg':
  Metadata:
    encoder         : Lavf58.45.100
    Stream #0:0: Video: mjpeg, yuvj444p(pc), 1000x1000, q=2-31, 200 kb/s, 25 fps, 25 tbn, 25 tbc
    Metadata:
      encoder         : Lavc58.91.100 mjpeg
    Side data:
      cpb: bitrate max/min/avg: 0/0/200000 buffer size: 0 vbv_delay: N/A
frame=    1 fps=0.0 q=6.7 Lsize=N/A time=00:00:00.04 bitrate=N/A speed=0.262x    
video:65kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown

結果圖片

以上就是Python實現圖片自定義裁剪小工具的詳細內容,更多關於Python圖片裁剪的資料請關註WalkonNet其它相關文章!

推薦閱讀: