【问题标题】:Python PIL: How to save cropped image?Python PIL:如何保存裁剪的图像?
【发布时间】:2011-09-21 08:07:31
【问题描述】:

我有一个脚本可以创建图像并对其进行裁剪。问题是我调用crop()方法后它没有保存在磁盘上

crop = image.crop(x_offset, Y_offset, width, height).load()
return crop.save(image_path, format)

【问题讨论】:

  • 会发生什么?你有例外吗? image_pathformat 是什么?

标签: python python-imaging-library crop


【解决方案1】:

您需要在元组中将参数传递给.crop()。并且不要使用.load()

box = (x_offset, Y_offset, width, height)
crop = image.crop(box)
return crop.save(image_path, format)

这就是你所需要的。虽然,我不确定您为什么要返回保存操作的结果;它返回None

【讨论】:

    【解决方案2】:

    主要的麻烦是试图使用load()返回的对象作为图像对象。来自 PIL 文档:

    在 [PIL] 1.1.6 及更高版本中,load 返回可用于读取和修改像素的像素访问对象。访问对象的行为类似于二维数组 [...]

    试试这个:

    crop = image.crop((x_offset, Y_offset, width, height))   # note the tuple
    crop.load()    # OK but not needed!
    return crop.save(image_path, format)
    

    【讨论】:

      【解决方案3】:

      这是一个完整的 PIL 1.1.7 新版本。裁剪坐标现在是左上角右下角(不是 x、y、宽度、高度)。

      python的版本号为:2.7.15

      对于 PIL:1.1.7

      # -*- coding: utf-8 -*-
      
      from PIL import Image
      import PIL, sys
      
      print sys.version, PIL.VERSION
      
      
      for fn in ['im000001.png']:
      
          center_x    = 200
          center_y    = 500
      
          half_width       = 500
          half_height      = 100
      
          imageObject = Image.open(fn)
      
          #cropped = imageObject.crop((200, 100, 400, 300))
      
      
          cropped = imageObject.crop((center_x - half_width,
                                      center_y - half_height, 
                                      center_x + half_width,
                                      center_y + half_height,
                                      ))
      
          cropped.save('crop_' + fn, 'PNG')
      

      【讨论】:

      • 实际代码执行环境中“for fn in ['im000001.png']:”的具体用法是什么。
      • 我将它用于多个文件并仅用一个进行了测试。 for 行中的列表替换为 glob.glob(''*.PNG")
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-16
      • 2010-10-24
      • 1970-01-01
      • 2012-12-22
      • 1970-01-01
      • 1970-01-01
      • 2018-12-11
      相关资源
      最近更新 更多