亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用PIL將RGBA PNG轉換為RGB

使用PIL將RGBA PNG轉換為RGB

一只名叫tom的貓 2019-11-25 14:07:18
我正在使用PIL將使用Django上傳的透明PNG圖片轉換為JPG文件。輸出看起來壞了。源文件透明源文件碼Image.open(object.logo.path).save('/tmp/output.jpg', 'JPEG')要么Image.open(object.logo.path).convert('RGB').save('/tmp/output.png')結果兩種方式的結果圖像如下所示:結果文件有沒有辦法解決這個問題?我想要白色背景曾經是透明背景。解感謝出色的答案,我提出了以下函數集合:import Imageimport numpy as npdef alpha_to_color(image, color=(255, 255, 255)):    """Set all fully transparent pixels of an RGBA image to the specified color.    This is a very simple solution that might leave over some ugly edges, due    to semi-transparent areas. You should use alpha_composite_with color instead.    Source: http://stackoverflow.com/a/9166671/284318    Keyword Arguments:    image -- PIL RGBA Image object    color -- Tuple r, g, b (default 255, 255, 255)    """     x = np.array(image)    r, g, b, a = np.rollaxis(x, axis=-1)    r[a == 0] = color[0]    g[a == 0] = color[1]    b[a == 0] = color[2]     x = np.dstack([r, g, b, a])    return Image.fromarray(x, 'RGBA')性能簡單的非合成alpha_to_color功能是最快的解決方案,但是由于它不能處理半透明區域,因此留下了丑陋的邊框。純粹的PIL和numpy合成解決方案都可以提供出色的結果,但alpha_composite_with_color其速度(8.93毫秒)比pure_pil_alpha_to_color(79.6毫秒)快得多。如果您的系統上有numpy可用,那就是這種方式。 (更新:新的純PIL版本是所有提到的解決方案中最快的。)$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_to_color(i)"10 loops, best of 3: 4.67 msec per loop$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_composite_with_color(i)"10 loops, best of 3: 8.93 msec per loop$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color(i)"10 loops, best of 3: 79.6 msec per loop$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color_v2(i)"10 loops, best of 3: 1.1 msec per loop
查看完整描述

3 回答

  • 3 回答
  • 0 關注
  • 1832 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號