scrapy convert_image

徘徊边缘 提交于 2019-12-19 10:22:59

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/9630397/scrapy-convert-image

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!