scrapy convert_image

2019-02-19 16:40发布

I use Scrapy to crawl some images, the images need to cut a part or add water mark. I overwrite the function convert_image in pipelines.py but it didn't work. The code looks like this:

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

Any ideas?

UPDATE:

@warwaruk

how have you decided it didn't work? any exception or what? < 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条回答
干净又极端
2楼-- · 2019-02-19 17:30

ImagePipleline convert images to JPEG(RGB mode) automatically, and no “toggler” exists. Although you can modify its implmentaion, it may mess its other logic. So, use MediaPipeline is better -- just download the files. You can write another application to do post-processing for your image files. It make your logic clear and make scrapy faster.

查看更多
登录 后发表回答