0

我正在尝试从继承的 ImagesPipeline 类覆盖我的 pipeline.py 中的 convert_image 方法,但它没有按预期工作。

实际上,我只是想将下载的图像放大到我的要求:700px,但下载的图像仍然是原始大小,而且我在scrapy之外测试了调整大小的功能,效果很好

对于我没有在我的设置 IMAGES_THUMBS 中使用的信息,所以大小应该是 None 和 IMAGES_EXPIRES = 0

如果有人有一个很好的解决方案,可以在不满足此要求时将下载的图像直接转换为 700x700 最小转换。

这是我的代码:

class MyImagesPipeline(ImagesPipeline):

    def get_media_requests(self, item, info):
        for image_url in item['image_urls']:
            yield scrapy.Request(image_url)

    def convert_image(self, image, size=None):
        if image.format == 'PNG' and image.mode == 'RGBA':
            background = Image.new('RGBA', image.size, (255, 255, 255))
            background.paste(image, image)
            image = background.convert('RGB')
        elif image.mode != 'RGB':
            image = image.convert('RGB')
        if size is None:
            image = image.copy()
            basewidth = 700
            wpercent = (basewidth/float(image.size[0]))
            hsize = int((float(image.size[1])*float(wpercent)))
            image.resize((basewidth,hsize), Image.ANTIALIAS)
            #image = image.copy()
            #image.thumbnail(size, Image.ANTIALIAS)

       buf = BytesIO()
       try:
            image.save(buf, 'JPEG')
       except Exception, ex:
            raise ImageException("Cannot process image. Error: %s" % ex)

       return image, buf

    def item_completed(self, results, item, info):
        image_paths = [x['path'] for ok, x in results if ok]
        if not image_paths:
            raise DropItem("Item contains no images")
        item['image_paths'] = image_paths
        return item

这是我试图覆盖的原始管道图像类: github

4

1 回答 1

0

看起来您正在使用PILor Pillowresize不会就地更改图像,它会返回一个新图像。所以你需要这个:

image = image.resize((basewidth,hsize), Image.ANTIALIAS)
^^^^^^^^
于 2016-03-07T16:22:23.203 回答