如何用Python实现两种将图片转换为正方形的代码示例?

2026-05-26 20:270阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计876个文字,预计阅读时间需要4分钟。

如何用Python实现两种将图片转换为正方形的代码示例?

将原图粘贴到一张正方形背景上:

pythonimport PILfrom PIL import Image

def trans_square(image): 使用PIL打开图像,并将其粘贴到正方形背景上 image=image.convert('RGB') w, h=image.size background=Image.new('RGB', (max(w, h), max(w, h)), color=(127, 127, 127)) background.paste(image, (0, 0)) return background

一、将原图粘贴到一张正方形的背景上

def trans_square(image): r"""Open the image using PIL.""" image = image.convert('RGB') w, h = image.size background = Image.new('RGB', size=(max(w, h), max(w, h)), color=(127, 127, 127)) # 创建背景图,颜色值为127 length = int(abs(w - h) // 2) # 一侧需要填充的长度 box = (length, 0) if w < h else (0, length) # 粘贴的位置 background.paste(image, box) return background

二、切片填充的方式使用numpy创建背景,使用切片将原图的值填充到背景中。

阅读全文
标签:两种方法

本文共计876个文字,预计阅读时间需要4分钟。

如何用Python实现两种将图片转换为正方形的代码示例?

将原图粘贴到一张正方形背景上:

pythonimport PILfrom PIL import Image

def trans_square(image): 使用PIL打开图像,并将其粘贴到正方形背景上 image=image.convert('RGB') w, h=image.size background=Image.new('RGB', (max(w, h), max(w, h)), color=(127, 127, 127)) background.paste(image, (0, 0)) return background

一、将原图粘贴到一张正方形的背景上

def trans_square(image): r"""Open the image using PIL.""" image = image.convert('RGB') w, h = image.size background = Image.new('RGB', size=(max(w, h), max(w, h)), color=(127, 127, 127)) # 创建背景图,颜色值为127 length = int(abs(w - h) // 2) # 一侧需要填充的长度 box = (length, 0) if w < h else (0, length) # 粘贴的位置 background.paste(image, box) return background

二、切片填充的方式使用numpy创建背景,使用切片将原图的值填充到背景中。

阅读全文
标签:两种方法