fangwenxue
V2EX  ›  问与答

Python pil 压缩图片内存过高

  •  
  •   fangwenxue · Jun 15, 2020 · 1074 views
    This topic created in 2175 days ago, the information mentioned may be changed or developed.
        def resize_image(self, src_path: Path, width=800):
            self.echo_sub('开始压缩图片.')
            chunk_size = self.config.get('chunk_size') or 5
            with futures.ThreadPoolExecutor(10) as executor:
                args = ((p, width) for p in src_path.glob('*'))
                for result, image_size in executor.map(lambda a: resize_width(*a), args, chunksize=chunk_size):
                    width, height = image_size
                    if width > height or result.name == 'cover.jpg':
                        self.thumbnail.append(result)
                    self.echo_sub(f'{result} {width}x{height}.', fg='red')
            self.echo_sub_done('图片压缩完成.')
            
        def resize_width(src_file: Path, width, new_name=None, quality=95, sample=Image.ANTIALIAS):
            dest_file = get_dest_file(src_file, new_name)
            with src_file.open('r+b') as f:
                with Image.open(f) as image:
                    img = image.copy()
                    img_size = img.size
                    if img_size[0] > width:
                        new_height = int(math.ceil((width / img_size[0]) * img_size[1]))
                        img.thumbnail((width, new_height), sample)
                        img.save(str(dest_file), quality=quality)
                    return dest_file, img.size
            
    

    run log

    • 17:52:12 - 开始压缩图片.
    • Killed

    查看 syslog

    Out of memory: Killed process 16194 (python3) total-vm:1612348kB, anon-rss:621232kB, file-rss:1664kB, shmem-rss:0kB, UID:0 pgtables:1634304kB oom_score_adj:0

    单张图片 5M 内

    几个线程怎么跑了这么内存?

    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1014 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 18:43 · PVG 02:43 · LAX 11:43 · JFK 14:43
    ♥ Do have faith in what you're doing.