【问题标题】:Crop transparent PNG image with my own coords with python and PIL使用 python 和 PIL 用我自己的坐标裁剪透明的 PNG 图像
【发布时间】:2013-11-23 15:48:38
【问题描述】:

现在我的代码写入 PNG,但我无法打开它 - 文件错误。 无需裁剪所有作品,但我需要裁剪 png 文件。用我的坐标(没有 PIL 框)和透明图像。

Image.open(imagefile)
#image = image.crop(crop_coords) #only work without cropping

image.thumbnail([x, y], Image.ANTIALIAS)

imagefile = StringIO()
imagefile = open(file_destination, 'w')
try:
    image.save(imagefile, "PNG", quality=90)
except:
    print "Cannot save user image"

感谢您的帮助。


我注意到这个问题只针对带有索引 PNG alpha 图像的 png 文件。

【问题讨论】:

    标签: python image-processing png python-imaging-library alpha-transparency


    【解决方案1】:

    这里是一个使用 numpy 和 Pillow 的简单解决方案,只需用你自己的坐标更改问号!

    from PIL import Image
    import numpy as np
    
    def crop(png_image_name):
        pil_image = Image.open(png_image_name)
        np_array = np.array(pil_image)
        # z is the alpha depth, leave 0
        x0, y0, z0 = (?, ?, 0) 
        x1, y1, z1 = (?, ?, 0) 
        cropped_box = np_array[x0:x1, y0:y1, z0:z1]
        pil_image = Image.fromarray(cropped_box, 'RGBA')
        pil_image.save(png_image_name)
    

    【讨论】:

      【解决方案2】:
      from PIL import Image
      #from StringIO import StringIO
      
      img = Image.open("foobar.png")
      
      png_info = {}
      if img.mode not in ['RGB','RGBA']:
              img = img.convert('RGBA')
              png_info = img.info
      
      img = img.crop( (0,0,400,400) )
      
      img.thumbnail([200, 200], Image.ANTIALIAS)
      
      file_destination='quux.png'
      
      # imagefile = StringIO()
      imagefile = open(file_destination, 'wb')
      try:
          img.save(imagefile, "png", quality=90, **png_info)
          imagefile.close()
      except:
          print "Cannot save user image"
      

      感谢: PIL does not save transparency

      【讨论】:

        【解决方案3】:

        您必须以二进制模式打开文件,否则它会写一些东西但文件可​​能已损坏。根据你做的测试,文件是否损坏,可能不是作物本身的原因。

        这是我制作的工作版本:

        from PIL import Image
        #from StringIO import StringIO
        
        img = Image.open("foobar.png")
        img = img.crop( (0,0,400,400) )
        
        img.thumbnail([200, 200], Image.ANTIALIAS)
        
        file_destination='quux.png'
        
        # imagefile = StringIO()
        imagefile = open(file_destination, 'wb')
        try:
            img.save(imagefile, "png", quality=90)
            imagefile.close()
        except:
            print "Cannot save user image"
        

        【讨论】:

        • 谢谢,但是使用 pngs 我遇到了更多问题。下面是我自己的解决方案。
        猜你喜欢
        • 2012-12-22
        • 2017-01-18
        • 2015-03-02
        • 1970-01-01
        • 2012-10-01
        • 2016-12-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多