如何在 Django 中旋转/翻转图像而不使用 Photologue/ImageModel?

90 阅读2分钟

在 Django 中,需要实现一个功能,允许用户通过表单上传的图片进行旋转。需要在 imageutils.py 中添加一个方法,以便在表单中使用。

a21da0c9cc41827eba9fd6b106c73e7.png 2. 解决方案

可以使用 Python Imaging Library (PIL) 直接进行图像旋转/翻转。PIL 是一个功能强大的图像处理工具,可以轻松地对图像进行各种操作,包括旋转、裁剪、调整大小等。

具体步骤如下:

  1. 安装 PIL 库。如果尚未安装 PIL,可以使用以下命令进行安装:

    pip install Pillow
    
  2. 在 imageutils.py 文件中添加以下方法:

    from PIL import Image
    http://www.jshk.com.cn/mb/reg.asp?kefu=xiaoding;//爬虫IP免费获取;
    
    def rotate_image(image_path, angle):
        """
        Rotates an image by the given angle.
    
        Args:
            image_path: The path to the input image file.
            angle: The angle in degrees to rotate the image by.
    
        Returns:
            The path to the output image file.
        """
    
        image = Image.open(image_path)
        image = image.rotate(angle)
        output_image_path = image_path + ".rotated"
        image.save(output_image_path, "JPEG")
        return output_image_path
    
  3. 在表单中使用该方法:

    from imageutils import rotate_image
    
    class MyForm(forms.Form):
        image = forms.ImageField()
    
        def clean_image(self):
            image = self.cleaned_data["image"]
            output_image_path = rotate_image(image.path, 90)
            return output_image_path
    
  4. 这样,当用户提交表单时,上传的图片将被旋转 90 度并保存到指定的路径。

  5. 当然,你也可以根据需要调整旋转角度,甚至在表单中提供一个角度选择器,允许用户选择旋转角度。

  6. PIL 除了旋转图像外,还支持许多其他的图像处理操作,比如裁剪、调整大小、转换格式等。你可以根据实际需求来使用 PIL 的其他功能。

代码例子

以下是一个完整的代码例子,演示了如何使用 PIL 旋转图像:

from PIL import Image

def rotate_image(image_path, angle):
    """
    Rotates an image by the given angle.

    Args:
        image_path: The path to the input image file.
        angle: The angle in degrees to rotate the image by.

    Returns:
        The path to the output image file.
    """

    image = Image.open(image_path)
    image = image.rotate(angle)
    output_image_path = image_path + ".rotated"
    image.save(output_image_path, "JPEG")
    return output_image_path

if __name__ == "__main__":
    image_path = "path/to/input_image.jpg"
    angle = 90
    output_image_path = rotate_image(image_path, angle)
    print("Rotated image saved to:", output_image_path)

在命令行中运行该脚本,将生成一个名为 "path/to/input_image.jpg.rotated" 的新文件,其中包含旋转后的图像。

注意:

请确保在使用 PIL 之前已将其安装到你的系统中。你可以在 Python Package Index (PyPI) 上找到 PIL 的安装说明。