scrapy 转换图像

问题描述 投票:0回答:1

我使用Scrapy爬取一些图像,图像需要剪切一部分或添加水印。我覆盖了

convert_image
中的函数
pipelines.py
但它不起作用。代码如下所示:

class MyImagesPipeline(ImagesPipeline):

    def get_media_requests(self, item, info):
        for image_url in item['image_urls']:
            yield 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:
            image = image.copy()
            image.thumbnail(size, Image.ANTIALIAS)
        else:
            #  cut water image  TODO use defined image replace Not cut 
            x,y = image.size
            if(y>120):
                image = image.crop((0,0,x,y-25))
        
        buf = StringIO()
        try:
            image.save(buf, 'JPEG')
        except Exception, ex:
            raise ImageException("Cannot process image. Error: %s" % ex)

        return image, buf

有什么想法吗?

更新:

@warwaruk

您如何确定它不起作用?有什么例外或什么吗? < no exception .I use this code for rewrite function item_completed.and it works good, here is the code:

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")
    
    if item['refer'] == 'someurl.com' :
        for a in image_paths:
            o_img = os.path.join(self.store.basedir,a)

            if os.path.isfile(o_img):
                image = Image.open(o_img)
                x,y = image.size
                if(y>120):
                    image = image.crop((0,0,x,y-35))
                    image.save(o_img,'JPEG');
    
    return item
scrapy
1个回答
4
投票

ImagePipleline 自动将图像转换为 JPEG(RGB 模式),并且不存在“切换器”。尽管您可以修改其实现,但它可能会扰乱其其他逻辑。因此,使用 MediaPipeline 更好——只需下载文件即可。

您可以编写另一个应用程序来对图像文件进行后处理。它让你的逻辑清晰,让 Scrapy 更快。

© www.soinside.com 2019 - 2024. All rights reserved.