在 Python 中裁切影像

影像裁切是影像編輯和圖形設計應用程式中的重要功能。它可以讓您調整圖像大小並修剪其邊緣。在 Python 應用程式中處理映像或處理影像編輯時,開發人員通常需要一種輕鬆的影像裁剪機制。因此,在這篇文章中,我們將學習如何在 Python 應用程式中無縫裁剪圖像。

用於裁切影像的 Python 函式庫

對於圖像裁剪,我們將使用 Aspose.Imaging for Python。它是一個多功能庫,提供了一系列用於處理影像的功能。特別是,它可以讓您輕鬆執行基本和進階影像編輯任務。

您可以下載該程式庫或從 PyPI 將其安裝到您的 Python 應用程式中。

> pip install aspose-imaging-python-net 

在 Python 中裁切影像

使用 Aspose.Imaging for Python 裁切影像有兩種方法:使用移位值和使用矩形。在移位值方法中,我們指定影像移位的左、右、上、下值。另一方面,我們在第二種方法中使用矩形來定義裁切區域。

因此,讓我們藉助 Python 程式碼片段來了解上述每種影像裁切方法。

在 Python 中使用平移值來裁剪映像

以下步驟示範如何在 Python 中使用移位值裁切影像。

以下程式碼片段展示如何在 Python 中裁切影像。

import aspose.pycore as aspycore
from aspose.imaging import RasterImage, Image, Rectangle
import os


if 'TEMPLATE_DIR' in os.environ:
	templates_folder = os.environ['TEMPLATE_DIR']
else:
	templates_folder = r"C:\Users\USER\Downloads\templates"

delete_output = 'SAVE_OUTPUT' not in os.environ
data_dir = templates_folder

# 將現有映像載入到 RasterImage 類別的實例中
with aspycore.as_of(Image.load(os.path.join(data_dir, "template.jpg")), RasterImage) as raster_image:
	# 在裁剪之前,應該要快取圖像以獲得更好的性能
	if not raster_image.is_cached:
		raster_image.cache_data()

	# 定義所有四個邊的位移值
	left_shift = 10
	right_shift = 10
	top_shift = 10
	bottom_shift = 10
  
	# 根據移位值,對影像進行裁剪
	raster_image.crop(left_shift, right_shift, top_shift, bottom_shift)
  
  	# 儲存裁剪後的影像
	raster_image.save(os.path.join(data_dir, "result.jpg"))

if delete_output:
	os.remove(os.path.join(data_dir, "result.jpg"))

以下是輸入影像(第一張)及其裁切版本(第二張)的螢幕截圖。

在Python中裁剪影像
Python 中的圖像裁剪

用矩形裁切影像

在此方法中,我們定義一個矩形來裁切載入影像中的特定區域。生成的圖像包含該矩形內的圖像部分。以下是使用矩形裁切影像的步驟。

以下程式碼片段顯示了在 Python 中使用矩形裁剪圖像。

import aspose.pycore as aspycore
from aspose.imaging import RasterImage, Image, Rectangle
import os

if 'TEMPLATE_DIR' in os.environ:
	templates_folder = os.environ['TEMPLATE_DIR']
else:
	templates_folder = r"C:\Users\USER\Downloads\templates"

delete_output = 'SAVE_OUTPUT' not in os.environ
data_dir = templates_folder

# 將現有映像載入到 RasterImage 類別的實例中
with aspycore.as_of(Image.load(os.path.join(data_dir, "template.jpg")), RasterImage) as raster_image:
	if not raster_image.is_cached:
		raster_image.cache_data()

	# 建立具有所需大小的 Rectangle 類別的實例
	rectangle = Rectangle(20, 20, 20, 20)
  
  	# 裁切影像
	raster_image.crop(rectangle)
  
  	# 保存圖片
	raster_image.save(os.path.join(data_dir, "result.jpg"))

if delete_output:
	os.remove(os.path.join(data_dir, "result.jpg"))

取得免費的 Python 圖像裁剪庫

您可以獲得免費的臨時許可證並裁剪圖像,而不受評估限制。

結論

Aspose.Imaging for Python 為映像裁切和操作提供了強大的解決方案。這篇部落格文章為您提供了幾種圖像裁剪方法,您可以輕鬆地將它們整合到 Python 應用程式中。使用這個強大的 Python 影像編輯 API 來增強您的影像處理能力。訪問文件探索其驚人的功能,並透過我們的論壇與我們分享您的問題。

也可以看看