溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python怎么調(diào)整圖片的文件大小

發(fā)布時間:2023-03-25 11:28:45 來源:億速云 閱讀:82 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“Python怎么調(diào)整圖片的文件大小”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“Python怎么調(diào)整圖片的文件大小”吧!

    問題描述

    Python調(diào)整圖片文件的占用空間大小,而不是分辨率

    1.jpg

    Python怎么調(diào)整圖片的文件大小

    圖片大小為 8KB

    減小文件大小

    使用 PIL 模塊

    pip install Pillow

    1. 減小圖片質(zhì)量

    代碼

    import os
    from PIL import Image
    
    
    def compress_under_size(imagefile, targetfile, targetsize):
        """壓縮圖片尺寸直到某一尺寸
    
        :param imagefile: 原圖路徑
        :param targetfile: 保存圖片路徑
        :param targetsize: 目標(biāo)大小,單位byte
        """
        currentsize = os.path.getsize(imagefile)
        for quality in range(99, 0, -1):  # 壓縮質(zhì)量遞減
            if currentsize > targetsize:
                image = Image.open(imagefile)
                image.save(targetfile, optimize=True, quality=quality)
                currentsize = os.path.getsize(targetfile)
    
    
    if __name__ == '__main__':
        imagefile = '1.jpg'  # 圖片路徑
        targetfile = 'result.jpg'  # 目標(biāo)圖片路徑
        targetsize = 2 * 1024  # 目標(biāo)圖片大小
        compress_under_size(imagefile, targetfile, targetsize)  # 將圖片壓縮到2KB

    效果

    Python怎么調(diào)整圖片的文件大小

    注意!無法實現(xiàn)圖片無限壓縮,若文件太小,辨識度也會大大降低

    2. 減小圖片尺寸

    import os
    from PIL import Image
    
    
    def image_compress(filename, savename, targetsize):
        """圖像壓縮
    
        :param filename: 原圖路徑
        :param savename: 保存圖片路徑
        :param targetsize: 目標(biāo)大小,單位為byte
        """
        image = Image.open(filename)
        size = os.path.getsize(filename)
        if size <= targetsize:
            return
        width, height = image.size
        num = (targetsize / size) ** 0.5
        width, height = round(width * num), round(height * num)
        image.resize((width, height)).save(savename)
    
    
    if __name__ == '__main__':
        filename = '1.jpg'
        savename = 'result.jpg'
        targetsize = 2 * 1024
        image_compress(filename, savename, targetsize)

    效果

    Python怎么調(diào)整圖片的文件大小

    增加文件大小

    Windows

    通過 subprocess 模塊調(diào)用系統(tǒng)命令 fsutil file createnew filename filesize 創(chuàng)建指定大小的文件

    再用 copy/b 命令合并數(shù)據(jù)到圖片上

    import os
    import time
    import subprocess
    
    imagefile = '1.jpg'  # 圖片路徑
    targetfile = 'result.jpg'  # 目標(biāo)圖片路徑
    targetsize = 10 * 1024 * 1024  # 目標(biāo)圖片大小
    
    tempfile = str(int(time.time()))  # 臨時文件路徑
    tempsize = str(targetsize - os.path.getsize(imagefile))  # 臨時文件大小
    subprocess.run(['fsutil', 'file', 'createnew', tempfile, tempsize])  # 創(chuàng)建臨時文件
    subprocess.run(['copy/b', '{}/b+{}/b'.format(imagefile, tempfile), targetfile], shell=True)  # 合并生成新圖片
    os.remove(tempfile)

    Linux

    通過 subprocess 模塊調(diào)用系統(tǒng)命令 fallocate -l filesize filename 創(chuàng)建指定大小的文件

    再用 cat > 命令合并數(shù)據(jù)到圖片上

    import os
    import time
    import subprocess
    
    imagefile = '1.jpg'  # 圖片路徑
    targetfile = 'result.jpg'  # 目標(biāo)圖片路徑
    targetsize = 10 * 1024 * 1024  # 目標(biāo)圖片大小
    
    tempfile = str(int(time.time()))  # 臨時文件路徑
    tempsize = str(targetsize - os.path.getsize(imagefile))  # 臨時文件大小
    subprocess.run(['fallocate', '-l', tempsize, tempfile])  # 創(chuàng)建臨時文件
    subprocess.run('cat {} {} > {}'.format(imagefile, tempfile, targetfile), shell=True)  # 合并生成新圖片
    os.remove(tempfile)

    效果

    Python怎么調(diào)整圖片的文件大小

    圖片的分辨率沒變

    封裝

    import os
    import time
    import platform
    import subprocess
    from PIL import Image
    
    
    def resize_picture_filesize(imagefile, targetfile, targetsize):
        """調(diào)整圖片文件大小
    
        :param imagefile: 原圖路徑
        :param targetfile: 保存圖片路徑
        :param targetsize: 目標(biāo)文件大小,單位byte
        """
        currentsize = os.path.getsize(imagefile)  # 原圖文件大小
    
        if currentsize > targetsize:  # 需要縮小
            for quality in range(99, 0, -1):  # 壓縮質(zhì)量遞減
                if currentsize > targetsize:
                    image = Image.open(imagefile)
                    image.save(targetfile, optimize=True, quality=quality)
                    currentsize = os.path.getsize(targetfile)
        else:  # 需要放大
            system = platform.system()
            tempfile = str(int(time.time()))  # 臨時文件路徑
            tempsize = str(targetsize - os.path.getsize(imagefile))  # 臨時文件大小
    
            if system == 'Windows':
                subprocess.run(['fsutil', 'file', 'createnew', tempfile, tempsize])  # 創(chuàng)建臨時文件
                subprocess.run(['copy/b', '{}/b+{}/b'.format(imagefile, tempfile), targetfile], shell=True)  # 合并生成新圖片
            elif system == 'Linux':
                subprocess.run(['fallocate', '-l', tempsize, tempfile])  # 創(chuàng)建臨時文件
                subprocess.run('cat {} {} > {}'.format(imagefile, tempfile, targetfile), shell=True)  # 合并生成新圖片
            os.remove(tempfile)
    
    
    if __name__ == '__main__':
        imagefile = '1.jpg'  # 8KB的圖片
        resize_picture_filesize(imagefile, 'reduce.jpg', 2 * 1024)  # 縮小到2KB
        resize_picture_filesize(imagefile, 'increase.jpg', 800 * 1024)  # 放大到800KB

    到此,相信大家對“Python怎么調(diào)整圖片的文件大小”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

    向AI問一下細節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI