Ausgabe der neuen DB Einträge
9
.idea/HubobelsPython.iml
generated
|
|
@ -1,11 +1,10 @@
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<module type="PYTHON_MODULE" version="4">
|
<module type="PYTHON_MODULE" version="4">
|
||||||
<component name="NewModuleRootManager">
|
<component name="NewModuleRootManager">
|
||||||
<content url="file://$MODULE_DIR$" />
|
<content url="file://$MODULE_DIR$">
|
||||||
<orderEntry type="jdk" jdkName="Python 3.6.1 (/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6)" jdkType="Python SDK" />
|
<excludeFolder url="file://$MODULE_DIR$/venv" />
|
||||||
|
</content>
|
||||||
|
<orderEntry type="jdk" jdkName="Python 3.10" jdkType="Python SDK" />
|
||||||
<orderEntry type="sourceFolder" forTests="false" />
|
<orderEntry type="sourceFolder" forTests="false" />
|
||||||
</component>
|
</component>
|
||||||
<component name="TestRunnerService">
|
|
||||||
<option name="PROJECT_TEST_RUNNER" value="Unittests" />
|
|
||||||
</component>
|
|
||||||
</module>
|
</module>
|
||||||
2
.idea/misc.xml
generated
|
|
@ -1,6 +1,6 @@
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project version="4">
|
<project version="4">
|
||||||
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.6.1 (/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6)" project-jdk-type="Python SDK" />
|
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10" project-jdk-type="Python SDK" />
|
||||||
<component name="PyCharmProfessionalAdvertiser">
|
<component name="PyCharmProfessionalAdvertiser">
|
||||||
<option name="shown" value="true" />
|
<option name="shown" value="true" />
|
||||||
</component>
|
</component>
|
||||||
|
|
|
||||||
31
Checkmail.py
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
import poplib
|
||||||
|
|
||||||
|
mymail = []
|
||||||
|
|
||||||
|
host = "pop3.web.de"
|
||||||
|
mail = poplib.POP3_SSL(host)
|
||||||
|
print (mail.getwelcome())
|
||||||
|
print (mail.user("schneeschieben@web.de"))
|
||||||
|
print (mail.pass_("Winter19&"))
|
||||||
|
print (mail.stat())
|
||||||
|
print (mail.list())
|
||||||
|
print ("")
|
||||||
|
|
||||||
|
if mail.stat()[1] > 0:
|
||||||
|
print ("You have new mail.")
|
||||||
|
else:
|
||||||
|
print ("No new mail.")
|
||||||
|
|
||||||
|
print ("")
|
||||||
|
|
||||||
|
numMessages = len(mail.list()[1])
|
||||||
|
numb=0
|
||||||
|
for i in range(numMessages):
|
||||||
|
for j in mail.retr(i+1)[1]:
|
||||||
|
numb+=1
|
||||||
|
#print(j)
|
||||||
|
if numb == 4 or numb == 5:
|
||||||
|
print(j)
|
||||||
|
|
||||||
|
mail.quit()
|
||||||
|
input("Press any key to continue.")
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
# -*- coding: UTF8 -*-
|
# -*- coding: UTF8 -*-
|
||||||
import requests
|
import requests
|
||||||
import datetime
|
|
||||||
import pymysql
|
import pymysql
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -13,24 +13,31 @@ day = now.strftime("%d")
|
||||||
month = now.strftime("%m")
|
month = now.strftime("%m")
|
||||||
year = now.strftime("%Y")
|
year = now.strftime("%Y")
|
||||||
|
|
||||||
pfadflur="/media/cameras/flur/"+year+"/"+month+"/"+day
|
pfadflur="/mnt/usb/cameras/flur/"+year+"/"+month+"/"+day
|
||||||
pfadgarten="/media/cameras/garten/"+year+"/"+month+"/"+day
|
pfadgarten="/mnt/usb/cameras/garten/"+year+"/"+month+"/"+day
|
||||||
pfadwz="/media/cameras/wz/"+year+"/"+month+"/"+day
|
pfadwz="/mnt/usb/cameras/wz/"+year+"/"+month+"/"+day
|
||||||
|
pfadhaustuer="/mnt/usb/cameras/haustuer/"+year+"/"+month+"/"+day
|
||||||
|
|
||||||
try:
|
try:
|
||||||
shutil.rmtree(pfadflur)
|
shutil.rmtree(pfadflur)
|
||||||
print('Lösche '+ pfadflur)
|
print('L sche '+ pfadflur)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print('Beim Löschen kam es zu folgendem Fehler: ' + str(e))
|
print('Beim Löschen kam es zu folgendem Fehler: ' + str(e))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
shutil.rmtree(pfadgarten)
|
shutil.rmtree(pfadgarten)
|
||||||
print('Lösche '+ pfadgarten)
|
print('L sche '+ pfadgarten)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print('Beim Löschen kam es zu folgendem Fehler: ' + str(e))
|
print('Beim Löschen kam es zu folgendem Fehler: ' + str(e))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
shutil.rmtree(pfadwz)
|
shutil.rmtree(pfadwz)
|
||||||
print('Lösche '+ pfadwz)
|
print('L sche '+ pfadwz)
|
||||||
|
except Exception as e:
|
||||||
|
print('Beim Löschen kam es zu folgendem Fehler: ' + str(e))
|
||||||
|
|
||||||
|
try:
|
||||||
|
shutil.rmtree(pfadhaustuer)
|
||||||
|
print('L sche '+ pfadhaustuer)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print('Beim Löschen kam es zu folgendem Fehler: ' + str(e))
|
print('Beim Löschen kam es zu folgendem Fehler: ' + str(e))
|
||||||
|
|
|
||||||
26
Dropboxsync.py
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
import dropbox
|
||||||
|
import os
|
||||||
|
|
||||||
|
access_token = 'wolWNcuUBx8AAAAAAAAAAewgSIDDcM7gBELKKuQyTup-iaMigFASlRULaav4e_N7'
|
||||||
|
|
||||||
|
dbx = dropbox.Dropbox(access_token)
|
||||||
|
|
||||||
|
a = os.getcwd() + "/Stick/"
|
||||||
|
b = os.getcwd() + "/testa/"
|
||||||
|
inhalta = (os.listdir(a))
|
||||||
|
|
||||||
|
for i in inhalta:
|
||||||
|
with open(a + str(i), 'rb') as f:
|
||||||
|
dbx.files_upload(f.read(), '/' + str(i))
|
||||||
|
|
||||||
|
inhalt = dbx.files_list_folder('')
|
||||||
|
|
||||||
|
|
||||||
|
for entry in dbx.files_list_folder('').entries:
|
||||||
|
print(entry.name)
|
||||||
|
download_Path = b + entry.name
|
||||||
|
|
||||||
|
dropbox_Path = '/' + entry.name
|
||||||
|
|
||||||
|
dbx.files_download_to_file(download_Path, dropbox_Path)
|
||||||
|
|
||||||
21
Influx.py
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
from influxdb import InfluxDBClient
|
||||||
|
|
||||||
|
client = InfluxDBClient(host='10.0.1.59', port=8086, username='admin', password='polier2003')
|
||||||
|
|
||||||
|
#databases = client.get_list_database()
|
||||||
|
|
||||||
|
client.switch_database('iobroker')
|
||||||
|
|
||||||
|
# measurements = client.get_list_measurements()
|
||||||
|
# antwort = client.query('SELECT * FROM "javascript.0.Variablen.Tagesverbrauch" WHERE time > now() -24h')
|
||||||
|
# antwort = client.query('SELECT * FROM "javascript.0.Variablen.Tagesverbrauch" WHERE time > '+"'2020-07-16T19:16:30.665000Z' and time < '2020-07-16T19:20:30.572000Z'")
|
||||||
|
# antwort = client.query('SELECT * FROM "javascript.0.Variablen.Tagesverbrauch" WHERE time = '+"'2020-07-16T19:16:30.665000Z'")
|
||||||
|
|
||||||
|
antwort = client.query('SELECT * FROM "javascript.0.Variablen.Tagesverbrauch" WHERE time > now() -1440m and time < now() -1439m')
|
||||||
|
cpu_points = list(antwort.get_points())
|
||||||
|
print(antwort)
|
||||||
|
print(cpu_points)
|
||||||
|
print(cpu_points[0]['time'])
|
||||||
|
print(cpu_points[0]['value'])
|
||||||
|
client.close()
|
||||||
|
|
||||||
12
Lotto2SQL.py
|
|
@ -6,14 +6,14 @@ import time
|
||||||
connection = pymysql.connect(db="hubobel",
|
connection = pymysql.connect(db="hubobel",
|
||||||
user="hubobel",
|
user="hubobel",
|
||||||
passwd="polier2003",
|
passwd="polier2003",
|
||||||
host='10.0.1.59',charset='utf8')
|
host='10.0.1.123',charset='utf8')
|
||||||
cursor = connection.cursor()
|
cursor = connection.cursor()
|
||||||
|
|
||||||
|
|
||||||
requests.packages.urllib3.disable_warnings()
|
requests.packages.urllib3.disable_warnings()
|
||||||
sauce = requests.get('https://www.lotto24.de/webshop/product/eurojackpot/result', verify=False)
|
sauce = requests.get('https://lotto.web.de/webshop/product/eurojackpot/result', verify=False)
|
||||||
soup = bs.BeautifulSoup(sauce.text, 'lxml')
|
soup = bs.BeautifulSoup(sauce.text, 'lxml')
|
||||||
|
#print(soup)
|
||||||
ZahlenEuro = {'Datum': '', 'Z1': '', 'Z2': '', 'Z3': '', 'Z4': '', 'Z5': '', 'Eurozahl1': '', 'Eurozahl2': ''}
|
ZahlenEuro = {'Datum': '', 'Z1': '', 'Z2': '', 'Z3': '', 'Z4': '', 'Z5': '', 'Eurozahl1': '', 'Eurozahl2': ''}
|
||||||
a = 1
|
a = 1
|
||||||
daten = soup.find_all('div', class_="winning-numbers__number")
|
daten = soup.find_all('div', class_="winning-numbers__number")
|
||||||
|
|
@ -26,8 +26,9 @@ for i in daten:
|
||||||
elif a == 7:
|
elif a == 7:
|
||||||
ZahlenEuro['Eurozahl2'] = int(i.text)
|
ZahlenEuro['Eurozahl2'] = int(i.text)
|
||||||
a = a + 1
|
a = a + 1
|
||||||
|
#print(ZahlenEuro)
|
||||||
daten = soup.find_all('h2', class_="strong hidden-xs")
|
daten = soup.find_all('h2', class_="strong hidden-xs")
|
||||||
|
#print(daten)
|
||||||
for i in daten:
|
for i in daten:
|
||||||
date = i.text
|
date = i.text
|
||||||
date = date.replace(' ', '')
|
date = date.replace(' ', '')
|
||||||
|
|
@ -36,9 +37,10 @@ for i in daten:
|
||||||
start = (date.find('dem')) + 4
|
start = (date.find('dem')) + 4
|
||||||
ende = (date.find('(Alle'))
|
ende = (date.find('(Alle'))
|
||||||
ZahlenEuro['Datum'] = date[start:ende]
|
ZahlenEuro['Datum'] = date[start:ende]
|
||||||
|
#print(ZahlenEuro)
|
||||||
|
|
||||||
requests.packages.urllib3.disable_warnings()
|
requests.packages.urllib3.disable_warnings()
|
||||||
sauce = requests.get('https://www.lotto24.de/webshop/product/lottonormal/result', verify=False)
|
sauce = requests.get('https://lotto.web.de/webshop/product/lottonormal/result', verify=False)
|
||||||
soup = bs.BeautifulSoup(sauce.text, 'lxml')
|
soup = bs.BeautifulSoup(sauce.text, 'lxml')
|
||||||
|
|
||||||
Lottozahlen = {'Datum': '', 'Z1': '', 'Z2': '', 'Z3': '', 'Z4': '', 'Z5': '', 'Z6': '', 'Superzahl': '',
|
Lottozahlen = {'Datum': '', 'Z1': '', 'Z2': '', 'Z3': '', 'Z4': '', 'Z5': '', 'Z6': '', 'Superzahl': '',
|
||||||
|
|
|
||||||
116
Lotto2SQL_V2.py
Normal file
|
|
@ -0,0 +1,116 @@
|
||||||
|
import pymysql
|
||||||
|
import bs4 as bs
|
||||||
|
import requests
|
||||||
|
import time
|
||||||
|
|
||||||
|
requests.packages.urllib3.disable_warnings()
|
||||||
|
sauce = requests.get('https://www.lotto-hessen.de/lotto6aus49/gewinnzahlen-quoten/gewinnzahlen', verify=False)
|
||||||
|
soup = bs.BeautifulSoup(sauce.text, 'lxml')
|
||||||
|
print(soup)
|
||||||
|
Lottozahlen = {'Datum': '', 'Z1': '', 'Z2': '', 'Z3': '', 'Z4': '', 'Z5': '', 'Z6': '', 'Superzahl': '',
|
||||||
|
'Spiel77': '', 'Super6': ''}
|
||||||
|
a = 0
|
||||||
|
daten = soup.find_all('span')
|
||||||
|
zahlen = []
|
||||||
|
for i in daten:
|
||||||
|
if a >= 1 and a < 7:
|
||||||
|
Lottozahlen['Z' + str(a)] = i.text
|
||||||
|
if a == 7:
|
||||||
|
Lottozahlen['Superzahl'] = i.text
|
||||||
|
a = a + 1
|
||||||
|
if i.text == 'Tag':
|
||||||
|
a = 1
|
||||||
|
for i in daten:
|
||||||
|
if a > 0 and a < 8:
|
||||||
|
Lottozahlen['Spiel77'] = Lottozahlen['Spiel77']+i.text
|
||||||
|
if a > 7 and a < 14:
|
||||||
|
Lottozahlen['Super6'] = Lottozahlen['Super6']+i.text
|
||||||
|
a = a +1
|
||||||
|
if i.text == 'Superzahl':
|
||||||
|
a = 1
|
||||||
|
daten = soup.find_all('h2', class_="h4")
|
||||||
|
for i in daten:
|
||||||
|
Lottozahlen['Datum']=i.text
|
||||||
|
a=1
|
||||||
|
while a < 7:
|
||||||
|
Lottozahlen['Z' + str(a)] = int(Lottozahlen['Z'+str(a)])
|
||||||
|
a = a + 1
|
||||||
|
Lottozahlen['Superzahl'] = int(Lottozahlen['Superzahl'])
|
||||||
|
Lottozahlen['Spiel77'] = int(Lottozahlen['Spiel77'])
|
||||||
|
Lottozahlen['Super6'] = int(Lottozahlen['Super6'])
|
||||||
|
datum = Lottozahlen['Datum']
|
||||||
|
start = datum.find(', ')
|
||||||
|
Lottozahlen['Datum'] = datum[start+2:]
|
||||||
|
print(Lottozahlen)
|
||||||
|
requests.packages.urllib3.disable_warnings()
|
||||||
|
sauce = requests.get('https://www.lotto-hessen.de/eurojackpot/gewinnzahlen-quoten/gewinnzahlen?gbn=5', verify=False)
|
||||||
|
soup = bs.BeautifulSoup(sauce.text, 'lxml')
|
||||||
|
ZahlenEuro = {'Datum': '', 'Z1': '', 'Z2': '', 'Z3': '', 'Z4': '', 'Z5': '', 'Eurozahl1': '', 'Eurozahl2': ''}
|
||||||
|
daten = soup.find_all('span')
|
||||||
|
for i in daten:
|
||||||
|
if i.text =='Tag':
|
||||||
|
a = -1
|
||||||
|
a = a + 1
|
||||||
|
if a >= 1 and a < 6:
|
||||||
|
ZahlenEuro['Z'+str(a)] = int(i.text)
|
||||||
|
if a == 6:
|
||||||
|
ZahlenEuro['Eurozahl1'] = int(i.text)
|
||||||
|
if a == 7:
|
||||||
|
ZahlenEuro['Eurozahl2'] = int(i.text)
|
||||||
|
daten = soup.find_all('h2', class_="h4")
|
||||||
|
for i in daten:
|
||||||
|
ZahlenEuro['Datum'] = i.text
|
||||||
|
datums = ZahlenEuro['Datum']
|
||||||
|
start = datums.find(', ')
|
||||||
|
ZahlenEuro['Datum'] = datums[start+2:]
|
||||||
|
print(ZahlenEuro)
|
||||||
|
|
||||||
|
connection = pymysql.connect(db="hubobel",
|
||||||
|
user="hubobel",
|
||||||
|
passwd="polier2003",
|
||||||
|
host='10.0.1.123',charset='utf8')
|
||||||
|
cursor = connection.cursor()
|
||||||
|
|
||||||
|
data = ZahlenEuro
|
||||||
|
sql = "INSERT INTO `euro`(`datum`, `z1`, `z2`, `z3`, `z4`, `z5`, `sz1`, `sz2`) VALUES" \
|
||||||
|
" ('" + str(data['Datum']) + "','" + str(data['Z1']) + "','" + str(data['Z2']) + "','" + str(data['Z3']) + \
|
||||||
|
"','" + str(data['Z4']) + "','" + str(data['Z5']) + "','" + str(data['Eurozahl1']) + "','" + str(
|
||||||
|
data['Eurozahl2']) + "')"
|
||||||
|
sql_q = "SELECT * FROM euro WHERE datum like '%" + data['Datum'] + "%'"
|
||||||
|
resp = cursor.execute(sql_q)
|
||||||
|
if resp == 0:
|
||||||
|
cursor.execute(sql)
|
||||||
|
|
||||||
|
data = Lottozahlen
|
||||||
|
if 'Samstag,' in datum:
|
||||||
|
sql = "INSERT INTO `samstag`(`datum`, `z1`, `z2`, `z3`, `z4`, `z5`, `z6`, `sz`, `super6`, `spiel77`) VALUES" \
|
||||||
|
" ('" + str(data['Datum']) + "','" + str(data['Z1']) + "','" + str(data['Z2']) + "','" + str(data['Z3']) + \
|
||||||
|
"','" + str(data['Z4']) + "','" + str(data['Z5']) + "','" + str(data['Z6']) + "','" + str(data['Superzahl']) + \
|
||||||
|
"','" + str(data['Super6']) + "','" + str(data['Spiel77']) + "')"
|
||||||
|
sql_q = "SELECT * FROM samstag WHERE datum like '%" + data['Datum'] + "%'"
|
||||||
|
resp = cursor.execute(sql_q)
|
||||||
|
if resp == 0:
|
||||||
|
cursor.execute(sql)
|
||||||
|
|
||||||
|
if 'Mittwoch,' in datum:
|
||||||
|
sql = "INSERT INTO `mittwoch`(`datum`, `z1`, `z2`, `z3`, `z4`, `z5`, `z6`, `sz`, `super6`, `spiel77`) VALUES" \
|
||||||
|
" ('" + str(data['Datum']) + "','" + str(data['Z1']) + "','" + str(data['Z2']) + "','" + str(data['Z3']) + \
|
||||||
|
"','" + str(data['Z4']) + "','" + str(data['Z5']) + "','" + str(data['Z6']) + "','" + str(data['Superzahl']) + \
|
||||||
|
"','" + str(data['Super6']) + "','" + str(data['Spiel77']) + "')"
|
||||||
|
sql_q = "SELECT * FROM mittwoch WHERE datum like '%" + data['Datum'] + "%'"
|
||||||
|
resp = cursor.execute(sql_q)
|
||||||
|
if resp == 0:
|
||||||
|
cursor.execute(sql)
|
||||||
|
|
||||||
|
sql = "INSERT INTO `6aus49`(`datum`, `z1`, `z2`, `z3`, `z4`, `z5`, `z6`, `sz`, `super6`, `spiel77`) VALUES" \
|
||||||
|
" ('" + str(data['Datum']) + "','" + str(data['Z1']) + "','" + str(data['Z2']) + "','" + str(data['Z3']) + \
|
||||||
|
"','" + str(data['Z4']) + "','" + str(data['Z5']) + "','" + str(data['Z6']) + "','" + str(data['Superzahl']) + \
|
||||||
|
"','" + str(data['Super6']) + "','" + str(data['Spiel77']) + "')"
|
||||||
|
sql_q = "SELECT * FROM 6aus49 WHERE datum like '%" + data['Datum'] + "%'"
|
||||||
|
resp = cursor.execute(sql_q)
|
||||||
|
if resp == 0:
|
||||||
|
cursor.execute(sql)
|
||||||
|
|
||||||
|
connection.commit()
|
||||||
|
cursor.close()
|
||||||
|
connection.close()
|
||||||
23
OrdnerCLEAN.py
Normal file
|
|
@ -0,0 +1,23 @@
|
||||||
|
import os
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
pfad = os.getcwd() + "/Ziel/"
|
||||||
|
content = (os.listdir(pfad))
|
||||||
|
jetzt = datetime.now()
|
||||||
|
diff_seconds = (jetzt-datetime.fromtimestamp(0)).total_seconds()
|
||||||
|
jetzt = datetime.fromtimestamp(0)
|
||||||
|
|
||||||
|
|
||||||
|
for i in content:
|
||||||
|
datum = (os.path.getmtime(pfad + i))
|
||||||
|
alter = (diff_seconds-datum)/60/60/24
|
||||||
|
if i[:1] == "(":
|
||||||
|
b = i.find(')')
|
||||||
|
dauer = int((i[1:b]))-int(alter)
|
||||||
|
print(i + ' wird in ' + str(dauer) + ' Tagen gelöscht')
|
||||||
|
if dauer < 1:
|
||||||
|
os.remove(pfad+i)
|
||||||
|
print(i + ' wurde gelöscht!')
|
||||||
|
elif alter > 14:
|
||||||
|
os.remove(pfad + i)
|
||||||
|
print(i + ' wurde gelöscht!')
|
||||||
10
Reolink.py
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
import requests
|
||||||
|
|
||||||
|
url_WZ = 'http://10.0.1.241/cgi-bin/api.cgi?cmd=Login'
|
||||||
|
payload = '[{"cmd": "Login", "action": 0, "param": {"User": {"userName": "admin", "password": "polier2003"}}}]'
|
||||||
|
r = requests.post(url=url_WZ, data=payload)
|
||||||
|
data = r.json()
|
||||||
|
token = str((data[0]['value']['Token']['name']))
|
||||||
|
url = 'http://10.0.1.241/cgi-bin/api.cgi?cmd=SetIsp&token=' + token
|
||||||
|
payload = '[{"cmd":"SetIsp","action":0,"param":{"Isp":{"channel":0,"antiFlicker":"50HZ","exposure":"Auto","gain":{"min":1,"max":62},"shutter":{"min":0,"max":125},"blueGain":128,"redGain":128,"whiteBalance":"Auto","dayNight":"Color","backLight":"DynamicRangeControl","blc":128,"drc":128,"rotation":0,"mirroring":0,"nr3d":1}}}]'
|
||||||
|
r = requests.post(url=url, data=payload)
|
||||||
37
SQL.py
|
|
@ -3,15 +3,40 @@ import pymysql
|
||||||
connection = pymysql.connect(db="hubobel",
|
connection = pymysql.connect(db="hubobel",
|
||||||
user="hubobel",
|
user="hubobel",
|
||||||
passwd="polier2003",
|
passwd="polier2003",
|
||||||
host='10.0.1.59',charset='utf8')
|
host='10.0.1.123',charset='utf8')
|
||||||
cursor = connection.cursor()
|
cursor = connection.cursor()
|
||||||
try:
|
try:
|
||||||
cursor.execute("""CREATE TABLE facts (
|
cursor.execute("""CREATE TABLE speed (
|
||||||
nr INTEGER, fact TEXT)""")
|
nr INT, timestamp TEXT,server TEXT,ip TEXT, ping FLOAT, download FLOAT, upload FLOAT)""")
|
||||||
except:
|
except:
|
||||||
print ('weiter')
|
print ('weiter')
|
||||||
|
|
||||||
sql = "SELECT * FROM facts ORDER BY nr DESC"
|
sql = "SELECT * FROM speed ORDER BY Nr DESC"
|
||||||
resp = cursor.execute(sql)
|
|
||||||
|
|
||||||
print(resp)
|
Anzahl = cursor.execute(sql)
|
||||||
|
|
||||||
|
Anzahl = int(Anzahl+1)
|
||||||
|
print(Anzahl)
|
||||||
|
results_dict = {'client': {'rating': '0', 'loggedin': '0', 'isprating': '3.7', 'ispdlavg': '0', 'ip': '84.63.254.177', 'isp': 'Vodafone Germany DSL', 'lon': '8.1189', 'ispulavg': '0', 'country': 'DE', 'lat': '49.7403'}, 'bytes_sent': 22970368, 'download': 28727296.703763857, 'timestamp': '2022-01-02T15:26:51.753501Z', 'share': u'http://www.speedtest.net/result/12547122848.png', 'bytes_received': 36013552, 'ping': 15.811, 'upload': 17662540.706131537, 'server': {'latency': 15.811, 'name': 'Frankfurt', 'url': 'http://speedtest.ropa.de:8080/speedtest/upload.php', 'country': 'Germany', 'lon': '8.6821', 'cc': 'DE', 'host': 'speedtest.ropa.de:8080', 'sponsor': 'ropa GmbH & Co. KG', 'lat': '50.1109', 'id': '37748', 'd': 57.65047622507195}}
|
||||||
|
|
||||||
|
up = float(results_dict['upload'])/1000000
|
||||||
|
ping = float(results_dict['ping'])
|
||||||
|
down = float(results_dict['download'])/1000000
|
||||||
|
time = str(results_dict['timestamp'])
|
||||||
|
ip = str(results_dict['client']['ip'])
|
||||||
|
server = str(results_dict['server']['url'])
|
||||||
|
down = round(down, 2)
|
||||||
|
up = round(up, 2)
|
||||||
|
ping = round(ping, 1)
|
||||||
|
|
||||||
|
|
||||||
|
val = f'"{Anzahl}", "{time}", "{server}", "{ip}", "{ping}", "{down}", "{up}"'
|
||||||
|
sql = f'INSERT INTO speed VALUE ({val})'
|
||||||
|
|
||||||
|
print(sql)
|
||||||
|
resp = cursor.execute(sql)
|
||||||
|
connection.commit()
|
||||||
|
|
||||||
|
|
||||||
|
cursor.close()
|
||||||
|
connection.close()
|
||||||
63
Speedtest.py
Normal file
|
|
@ -0,0 +1,63 @@
|
||||||
|
import speedtest
|
||||||
|
import pymysql
|
||||||
|
import time
|
||||||
|
###################
|
||||||
|
|
||||||
|
version = "1.1"
|
||||||
|
|
||||||
|
##################
|
||||||
|
|
||||||
|
connection = pymysql.connect(db="hubobel",
|
||||||
|
user="hubobel",
|
||||||
|
passwd="polier2003",
|
||||||
|
host='10.0.1.123',charset='utf8')
|
||||||
|
cursor = connection.cursor()
|
||||||
|
try:
|
||||||
|
cursor.execute("""CREATE TABLE speed (
|
||||||
|
nr INT, timestamp TEXT,server TEXT,ip TEXT, ping FLOAT, download FLOAT, upload FLOAT, Version TEXT)""")
|
||||||
|
except:
|
||||||
|
print ('weiter')
|
||||||
|
|
||||||
|
sql = "SELECT * FROM speed ORDER BY Nr DESC"
|
||||||
|
|
||||||
|
Anzahl = cursor.execute(sql)
|
||||||
|
|
||||||
|
Anzahl = int(Anzahl+1)
|
||||||
|
|
||||||
|
servers = []
|
||||||
|
|
||||||
|
threads = None
|
||||||
|
|
||||||
|
|
||||||
|
s = speedtest.Speedtest()
|
||||||
|
s.get_servers(servers)
|
||||||
|
s.get_best_server()
|
||||||
|
s.download(threads=threads)
|
||||||
|
s.upload(threads=threads)
|
||||||
|
s.results.share()
|
||||||
|
results_dict = {'client': {'rating': '0', 'loggedin': '0', 'isprating': '3.7', 'ispdlavg': '0', 'ip': '84.63.254.177', 'isp': 'Vodafone Germany DSL', 'lon': '8.1189', 'ispulavg': '0', 'country': 'DE', 'lat': '49.7403'}, 'bytes_sent': 22970368, 'download': 28727296.703763857, 'timestamp': '2022-01-02T15:26:51.753501Z', 'share': u'http://www.speedtest.net/result/12547122848.png', 'bytes_received': 36013552, 'ping': 15.811, 'upload': 17662540.706131537, 'server': {'latency': 15.811, 'name': 'Frankfurt', 'url': 'http://speedtest.ropa.de:8080/speedtest/upload.php', 'country': 'Germany', 'lon': '8.6821', 'cc': 'DE', 'host': 'speedtest.ropa.de:8080', 'sponsor': 'ropa GmbH & Co. KG', 'lat': '50.1109', 'id': '37748', 'd': 57.65047622507195}}
|
||||||
|
|
||||||
|
results_dict = s.results.dict()
|
||||||
|
up = float(results_dict['upload'])/1000000
|
||||||
|
ping = float(results_dict['ping'])
|
||||||
|
down = float(results_dict['download'])/1000000
|
||||||
|
#time = str(results_dict['timestamp'])
|
||||||
|
ip = str(results_dict['client']['ip'])
|
||||||
|
server = str(results_dict['server']['url'])
|
||||||
|
down = round(down, 2)
|
||||||
|
up = round(up, 2)
|
||||||
|
ping = round(ping, 1)
|
||||||
|
time = (time.strftime("%Y-%m-%d-%H.%M.%S"))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
val = f'"{Anzahl}", "{time}", "{server}", "{ip}", "{ping}", "{down}", "{up}", "{version}"'
|
||||||
|
sql = f'INSERT INTO speed VALUE ({val})'
|
||||||
|
|
||||||
|
print(sql)
|
||||||
|
resp = cursor.execute(sql)
|
||||||
|
connection.commit()
|
||||||
|
|
||||||
|
|
||||||
|
cursor.close()
|
||||||
|
connection.close()
|
||||||
BIN
Stick/Bildschirmfoto 2020-08-07 um 18.24.28.png
Normal file
|
After Width: | Height: | Size: 95 KiB |
BIN
Stick/DSC_0010.jpeg
Normal file
|
After Width: | Height: | Size: 1.3 MiB |
BIN
Stick/IMG_2410.jpeg
Normal file
|
After Width: | Height: | Size: 295 KiB |
BIN
Stick/profi.pxm
Normal file
0
Stick/sicherheitgehtvor.txt
Normal file
24
USB.py
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
import os
|
||||||
|
from shutil import copyfile
|
||||||
|
import time
|
||||||
|
|
||||||
|
while True:
|
||||||
|
mount = os.getcwd() + "/media"
|
||||||
|
b = os.getcwd() + "/Ziel"
|
||||||
|
inhaltmount = (os.listdir(mount))
|
||||||
|
for all in inhaltmount:
|
||||||
|
try:
|
||||||
|
a = os.getcwd() + "/media/" + all
|
||||||
|
inhalta = (os.listdir(a))
|
||||||
|
inhaltb = (os.listdir(b))
|
||||||
|
print(inhalta)
|
||||||
|
if "sicherheitgehtvor.txt" in inhalta:
|
||||||
|
#print('Stick steckt und wurde autentifiziert')
|
||||||
|
inhalta.remove('sicherheitgehtvor.txt')
|
||||||
|
for i in inhalta:
|
||||||
|
if i not in inhaltb:
|
||||||
|
print('copy')
|
||||||
|
copyfile(a+'/'+ i, b + '/' + i)
|
||||||
|
except:
|
||||||
|
None
|
||||||
|
time.sleep(2)
|
||||||
BIN
Verbrauchsdaten.png
Normal file
|
After Width: | Height: | Size: 113 KiB |
BIN
Verbrauchsdaten2.png
Normal file
|
After Width: | Height: | Size: 19 KiB |
24
WetterShot.py
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
from selenium import webdriver
|
||||||
|
from PIL import Image
|
||||||
|
from selenium.webdriver.chrome.options import Options
|
||||||
|
|
||||||
|
chrome_options = Options()
|
||||||
|
chrome_options.add_argument("--headless")
|
||||||
|
chrome_options.add_argument('--no-sandbox')
|
||||||
|
chrome_options.add_argument('--start-maximized')
|
||||||
|
|
||||||
|
br = webdriver.Chrome(options=chrome_options)
|
||||||
|
|
||||||
|
br.set_window_size(1024, 1400)
|
||||||
|
br.get('https://www.hessenschau.de/wetter/wiesbaden/index.html')
|
||||||
|
br.refresh()
|
||||||
|
br.save_screenshot('Wetterscreenshot.png')
|
||||||
|
br.quit
|
||||||
|
|
||||||
|
im = Image.open("Wetterscreenshot.png")
|
||||||
|
area = (20, 600, 1600, 2500)
|
||||||
|
cropped_img = im.crop(area)
|
||||||
|
|
||||||
|
cropped_img.save('Wetterscreenshot2.png')
|
||||||
|
|
||||||
|
|
||||||
BIN
Wetterscreenshot.png
Normal file
|
After Width: | Height: | Size: 92 KiB |
BIN
Wetterscreenshot2.png
Normal file
|
After Width: | Height: | Size: 529 KiB |
5
Zeit.py
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
import time
|
||||||
|
|
||||||
|
Zeit = (time.strftime("%Y-%m-%d-%H.%M.%S"))
|
||||||
|
|
||||||
|
print(Zeit)
|
||||||
0
geckodriver.log
Normal file
5
ghostdriver.log
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
[INFO - 2021-01-01T16:09:59.302Z] GhostDriver - Main - running on port 61529
|
||||||
|
[INFO - 2021-01-01T16:10:00.234Z] Session [cc826d50-4c4b-11eb-b822-d77cbdf40a0a] - page.settings - {"XSSAuditingEnabled":false,"javascriptCanCloseWindows":true,"javascriptCanOpenWindows":true,"javascriptEnabled":true,"loadImages":true,"localToRemoteUrlAccessEnabled":false,"userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.1.1 Safari/538.1","webSecurityEnabled":true}
|
||||||
|
[INFO - 2021-01-01T16:10:00.234Z] Session [cc826d50-4c4b-11eb-b822-d77cbdf40a0a] - page.customHeaders: - {}
|
||||||
|
[INFO - 2021-01-01T16:10:00.234Z] Session [cc826d50-4c4b-11eb-b822-d77cbdf40a0a] - Session.negotiatedCapabilities - {"browserName":"phantomjs","version":"2.1.1","driverName":"ghostdriver","driverVersion":"1.2.0","platform":"mac-unknown-64bit","javascriptEnabled":true,"takesScreenshot":true,"handlesAlerts":false,"databaseEnabled":false,"locationContextEnabled":false,"applicationCacheEnabled":false,"browserConnectionEnabled":false,"cssSelectorsEnabled":true,"webStorageEnabled":false,"rotatable":false,"acceptSslCerts":false,"nativeEvents":true,"proxy":{"proxyType":"direct"}}
|
||||||
|
[INFO - 2021-01-01T16:10:00.234Z] SessionManagerReqHand - _postNewSessionCommand - New Session Created: cc826d50-4c4b-11eb-b822-d77cbdf40a0a
|
||||||
25
leer.py
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
from selenium import webdriver
|
||||||
|
from PIL import Image
|
||||||
|
from selenium.webdriver.chrome.options import Options
|
||||||
|
|
||||||
|
chrome_options = Options()
|
||||||
|
chrome_options.add_argument("--headless")
|
||||||
|
chrome_options.add_argument('--no-sandbox')
|
||||||
|
chrome_options.add_argument('--start-maximized')
|
||||||
|
|
||||||
|
br = webdriver.Chrome(options=chrome_options)
|
||||||
|
|
||||||
|
try:
|
||||||
|
br.set_window_size(1024, 1400)
|
||||||
|
br.get('https://www.hessenschau.de/wetter/wiesbaden/index.html')
|
||||||
|
#br.refresh()
|
||||||
|
br.save_screenshot('Wetterscreenshot.png')
|
||||||
|
br.quit
|
||||||
|
|
||||||
|
im = Image.open("Wetterscreenshot.png")
|
||||||
|
area = (20, 300, 1000, 1200)
|
||||||
|
cropped_img = im.crop(area)
|
||||||
|
|
||||||
|
cropped_img.save('/home/pi/Bilder/(1)Wetterscreenshot2.png')
|
||||||
|
except:
|
||||||
|
None
|
||||||
37
newsblur.py
|
|
@ -4,21 +4,28 @@ import time
|
||||||
import datetime
|
import datetime
|
||||||
import os
|
import os
|
||||||
|
|
||||||
session = requests.session()
|
url = 'http://hubobel.de/tt-rss/api/'
|
||||||
url = 'http://www.newsblur.com/api/login'
|
pfad = os.path.dirname(__file__)
|
||||||
datas = {'username':'hubobel','password':'polier2003'}
|
|
||||||
resp = session.post(url,datas)
|
datas = '{"op":"login","user":"admin","password":"polier2003"}'
|
||||||
|
resp = requests.post(url,datas)
|
||||||
data = resp.json()
|
data = resp.json()
|
||||||
print (data)
|
print(data)
|
||||||
|
id = str(data['content']['session_id'])
|
||||||
|
datas = '{"sid":"'+id+'","op":"getFeeds","cat_id":-4}'
|
||||||
|
resp = requests.post(url,datas)
|
||||||
|
data = resp.json()
|
||||||
|
|
||||||
|
for i in data['content']:
|
||||||
|
#print(i)
|
||||||
|
if int(i['unread'])>0:
|
||||||
|
print(i)
|
||||||
|
|
||||||
|
datas = '{"sid":"'+id+'","op":"getLabels","cat_id":-4}'
|
||||||
|
resp = requests.post(url,datas)
|
||||||
|
data = resp.json()
|
||||||
|
print(data['content'])
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
url = 'http://www.newsblur.com/reader/refresh_feeds'
|
|
||||||
resp = session.get(url)
|
|
||||||
data = resp.json()
|
|
||||||
print (json.dumps(data, indent=4))
|
|
||||||
print (data['id'])
|
|
||||||
url = 'http://www.newsblur.com/reader/feed/6212608'
|
|
||||||
resp = session.get(url)
|
|
||||||
data = resp.json()
|
|
||||||
print (json.dumps(data, indent=4))
|
|
||||||
print(data)
|
|
||||||
|
|
@ -18,14 +18,16 @@ tb = telebot.TeleBot(TOKEN)
|
||||||
url = 'http://hubobel.de/tt-rss/api/'
|
url = 'http://hubobel.de/tt-rss/api/'
|
||||||
pfad = os.path.dirname(__file__)
|
pfad = os.path.dirname(__file__)
|
||||||
|
|
||||||
datas = '{"op":"login","user":"admin","password":"password"}'
|
datas = '{"op":"login","user":"admin","password":"polier2003"}'
|
||||||
resp = requests.post(url,datas)
|
resp = requests.post(url,datas)
|
||||||
data = resp.json()
|
data = resp.json()
|
||||||
|
#print(data)
|
||||||
id= str(data['content']['session_id'])
|
id= str(data['content']['session_id'])
|
||||||
datas = '{"sid":"'+id+'","op":"getFeeds","cat_id":-4}'
|
datas = '{"sid":"'+id+'","op":"getFeeds","cat_id":-4}'
|
||||||
resp = requests.post(url,datas)
|
resp = requests.post(url,datas)
|
||||||
data = resp.json()
|
data = resp.json()
|
||||||
ids=[]
|
ids=[]
|
||||||
|
print(data)
|
||||||
gefunden=[]
|
gefunden=[]
|
||||||
laenge_start=laenge()
|
laenge_start=laenge()
|
||||||
|
|
||||||
|
|
@ -39,15 +41,17 @@ fobj.close()
|
||||||
|
|
||||||
|
|
||||||
for i in data['content']:
|
for i in data['content']:
|
||||||
|
print(i)
|
||||||
if int(i['unread'])>0 and int(i['id'])>0:
|
if int(i['unread'])>0 and int(i['id'])>0:
|
||||||
datas = '{"sid":"'+id+'","op":"getHeadlines","feed_id":'+str(i['id'])+'}'
|
datas = '{"sid":"'+id+'","op":"getHeadlines","feed_id":'+str(i['id'])+'}'
|
||||||
resp = requests.post(url,datas)
|
resp = requests.post(url,datas)
|
||||||
feeds = resp.json()
|
feeds = resp.json()
|
||||||
|
print(feeds)
|
||||||
for headlines in feeds['content']:
|
for headlines in feeds['content']:
|
||||||
if headlines['unread']:
|
if headlines['unread']:
|
||||||
a=0
|
a=0
|
||||||
b=len(suchstring)
|
b=len(suchstring)
|
||||||
if headlines['feed_id'] == '4':
|
if headlines['feed_id'] == '46':
|
||||||
article_id=str(headlines['id'])
|
article_id=str(headlines['id'])
|
||||||
datas = '{"sid":"' + id + '","op":"getArticle","article_id":'+article_id+'}'
|
datas = '{"sid":"' + id + '","op":"getArticle","article_id":'+article_id+'}'
|
||||||
resp = requests.post(url, datas)
|
resp = requests.post(url, datas)
|
||||||
|
|
@ -57,12 +61,12 @@ for i in data['content']:
|
||||||
connection = pymysql.connect(db="hubobel",
|
connection = pymysql.connect(db="hubobel",
|
||||||
user="hubobel",
|
user="hubobel",
|
||||||
passwd="polier2003",
|
passwd="polier2003",
|
||||||
host='10.0.1.59', charset='utf8')
|
host='10.0.1.123', charset='utf8')
|
||||||
cursor = connection.cursor()
|
cursor = connection.cursor()
|
||||||
sql = "SELECT * FROM facts ORDER BY nr DESC"
|
sql = "SELECT * FROM facts ORDER BY nr DESC"
|
||||||
resp = cursor.execute(sql)
|
resp = cursor.execute(sql)
|
||||||
x = int(resp) + 1
|
x = int(resp) + 1
|
||||||
|
print(antwort)
|
||||||
line = antwort.replace('<p>', '')
|
line = antwort.replace('<p>', '')
|
||||||
line = line.replace('</p>', '')
|
line = line.replace('</p>', '')
|
||||||
sql = "INSERT INTO `facts`(`nr`, `fact`) VALUES ('" + str(x) + "','" + line + "')"
|
sql = "INSERT INTO `facts`(`nr`, `fact`) VALUES ('" + str(x) + "','" + line + "')"
|
||||||
|
|
|
||||||
BIN
screenshot.png
Normal file
|
After Width: | Height: | Size: 932 KiB |
|
|
@ -0,0 +1 @@
|
||||||
|
pip
|
||||||
|
|
@ -0,0 +1,21 @@
|
||||||
|
Copyright (c) 2014
|
||||||
|
Rackspace
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
a copy of this software and associated documentation files (the
|
||||||
|
"Software"), to deal in the Software without restriction, including
|
||||||
|
without limitation the rights to use, copy, modify, merge, publish,
|
||||||
|
distribute, sublicense, and/or sell copies of the Software, and to
|
||||||
|
permit persons to whom the Software is furnished to do so, subject to
|
||||||
|
the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be
|
||||||
|
included in all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||||
|
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||||
|
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||||
|
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||||
|
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||||
|
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||||
|
|
@ -0,0 +1,487 @@
|
||||||
|
Metadata-Version: 2.1
|
||||||
|
Name: Automat
|
||||||
|
Version: 20.2.0
|
||||||
|
Summary: Self-service finite-state machines for the programmer on the go.
|
||||||
|
Home-page: https://github.com/glyph/Automat
|
||||||
|
Author: Glyph
|
||||||
|
Author-email: glyph@twistedmatrix.com
|
||||||
|
License: MIT
|
||||||
|
Keywords: fsm finite state machine automata
|
||||||
|
Platform: UNKNOWN
|
||||||
|
Classifier: Intended Audience :: Developers
|
||||||
|
Classifier: License :: OSI Approved :: MIT License
|
||||||
|
Classifier: Operating System :: OS Independent
|
||||||
|
Classifier: Programming Language :: Python
|
||||||
|
Classifier: Programming Language :: Python :: 2
|
||||||
|
Classifier: Programming Language :: Python :: 2.7
|
||||||
|
Classifier: Programming Language :: Python :: 3
|
||||||
|
Classifier: Programming Language :: Python :: 3.5
|
||||||
|
Classifier: Programming Language :: Python :: 3.6
|
||||||
|
Classifier: Programming Language :: Python :: 3.7
|
||||||
|
Classifier: Programming Language :: Python :: 3.8
|
||||||
|
Requires-Dist: attrs (>=19.2.0)
|
||||||
|
Requires-Dist: six
|
||||||
|
Provides-Extra: visualize
|
||||||
|
Requires-Dist: graphviz (>0.5.1); extra == 'visualize'
|
||||||
|
Requires-Dist: Twisted (>=16.1.1); extra == 'visualize'
|
||||||
|
|
||||||
|
|
||||||
|
Automat
|
||||||
|
=======
|
||||||
|
|
||||||
|
|
||||||
|
.. image:: https://readthedocs.org/projects/automat/badge/?version=latest
|
||||||
|
:target: http://automat.readthedocs.io/en/latest/
|
||||||
|
:alt: Documentation Status
|
||||||
|
|
||||||
|
|
||||||
|
.. image:: https://travis-ci.org/glyph/automat.svg?branch=master
|
||||||
|
:target: https://travis-ci.org/glyph/automat
|
||||||
|
:alt: Build Status
|
||||||
|
|
||||||
|
|
||||||
|
.. image:: https://coveralls.io/repos/glyph/automat/badge.png
|
||||||
|
:target: https://coveralls.io/r/glyph/automat
|
||||||
|
:alt: Coverage Status
|
||||||
|
|
||||||
|
|
||||||
|
Self-service finite-state machines for the programmer on the go.
|
||||||
|
----------------------------------------------------------------
|
||||||
|
|
||||||
|
Automat is a library for concise, idiomatic Python expression of finite-state
|
||||||
|
automata (particularly deterministic finite-state transducers).
|
||||||
|
|
||||||
|
Read more here, or on `Read the Docs <https://automat.readthedocs.io/>`_\ , or watch the following videos for an overview and presentation
|
||||||
|
|
||||||
|
Overview and presentation by **Glyph Lefkowitz** at the first talk of the first Pyninsula meetup, on February 21st, 2017:
|
||||||
|
|
||||||
|
.. image:: https://img.youtube.com/vi/0wOZBpD1VVk/0.jpg
|
||||||
|
:target: https://www.youtube.com/watch?v=0wOZBpD1VVk
|
||||||
|
:alt: Glyph Lefkowitz - Automat - Pyninsula #0
|
||||||
|
|
||||||
|
|
||||||
|
Presentation by **Clinton Roy** at PyCon Australia, on August 6th 2017:
|
||||||
|
|
||||||
|
.. image:: https://img.youtube.com/vi/TedUKXhu9kE/0.jpg
|
||||||
|
:target: https://www.youtube.com/watch?v=TedUKXhu9kE
|
||||||
|
:alt: Clinton Roy - State Machines - Pycon Australia 2017
|
||||||
|
|
||||||
|
|
||||||
|
Why use state machines?
|
||||||
|
^^^^^^^^^^^^^^^^^^^^^^^
|
||||||
|
|
||||||
|
Sometimes you have to create an object whose behavior varies with its state,
|
||||||
|
but still wishes to present a consistent interface to its callers.
|
||||||
|
|
||||||
|
For example, let's say you're writing the software for a coffee machine. It
|
||||||
|
has a lid that can be opened or closed, a chamber for water, a chamber for
|
||||||
|
coffee beans, and a button for "brew".
|
||||||
|
|
||||||
|
There are a number of possible states for the coffee machine. It might or
|
||||||
|
might not have water. It might or might not have beans. The lid might be open
|
||||||
|
or closed. The "brew" button should only actually attempt to brew coffee in
|
||||||
|
one of these configurations, and the "open lid" button should only work if the
|
||||||
|
coffee is not, in fact, brewing.
|
||||||
|
|
||||||
|
With diligence and attention to detail, you can implement this correctly using
|
||||||
|
a collection of attributes on an object; ``has_water``\ , ``has_beans``\ ,
|
||||||
|
``is_lid_open`` and so on. However, you have to keep all these attributes
|
||||||
|
consistent. As the coffee maker becomes more complex - perhaps you add an
|
||||||
|
additional chamber for flavorings so you can make hazelnut coffee, for
|
||||||
|
example - you have to keep adding more and more checks and more and more
|
||||||
|
reasoning about which combinations of states are allowed.
|
||||||
|
|
||||||
|
Rather than adding tedious 'if' checks to every single method to make sure that
|
||||||
|
each of these flags are exactly what you expect, you can use a state machine to
|
||||||
|
ensure that if your code runs at all, it will be run with all the required
|
||||||
|
values initialized, because they have to be called in the order you declare
|
||||||
|
them.
|
||||||
|
|
||||||
|
You can read about state machines and their advantages for Python programmers
|
||||||
|
in considerably more detail
|
||||||
|
`in this excellent series of articles from ClusterHQ <https://clusterhq.com/blog/what-is-a-state-machine/>`_.
|
||||||
|
|
||||||
|
What makes Automat different?
|
||||||
|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||||
|
|
||||||
|
There are
|
||||||
|
`dozens of libraries on PyPI implementing state machines <https://pypi.org/search/?q=finite+state+machine>`_.
|
||||||
|
So it behooves me to say why yet another one would be a good idea.
|
||||||
|
|
||||||
|
Automat is designed around this principle: while organizing your code around
|
||||||
|
state machines is a good idea, your callers don't, and shouldn't have to, care
|
||||||
|
that you've done so. In Python, the "input" to a stateful system is a method
|
||||||
|
call; the "output" may be a method call, if you need to invoke a side effect,
|
||||||
|
or a return value, if you are just performing a computation in memory. Most
|
||||||
|
other state-machine libraries require you to explicitly create an input object,
|
||||||
|
provide that object to a generic "input" method, and then receive results,
|
||||||
|
sometimes in terms of that library's interfaces and sometimes in terms of
|
||||||
|
classes you define yourself.
|
||||||
|
|
||||||
|
For example, a snippet of the coffee-machine example above might be implemented
|
||||||
|
as follows in naive Python:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
class CoffeeMachine(object):
|
||||||
|
def brew_button(self):
|
||||||
|
if self.has_water and self.has_beans and not self.is_lid_open:
|
||||||
|
self.heat_the_heating_element()
|
||||||
|
# ...
|
||||||
|
|
||||||
|
With Automat, you'd create a class with a ``MethodicalMachine`` attribute:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
from automat import MethodicalMachine
|
||||||
|
|
||||||
|
class CoffeeBrewer(object):
|
||||||
|
_machine = MethodicalMachine()
|
||||||
|
|
||||||
|
and then you would break the above logic into two pieces - the ``brew_button``
|
||||||
|
*input*\ , declared like so:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
@_machine.input()
|
||||||
|
def brew_button(self):
|
||||||
|
"The user pressed the 'brew' button."
|
||||||
|
|
||||||
|
It wouldn't do any good to declare a method *body* on this, however, because
|
||||||
|
input methods don't actually execute their bodies when called; doing actual
|
||||||
|
work is the *output*\ 's job:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
@_machine.output()
|
||||||
|
def _heat_the_heating_element(self):
|
||||||
|
"Heat up the heating element, which should cause coffee to happen."
|
||||||
|
self._heating_element.turn_on()
|
||||||
|
|
||||||
|
As well as a couple of *states* - and for simplicity's sake let's say that the
|
||||||
|
only two states are ``have_beans`` and ``dont_have_beans``\ :
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
@_machine.state()
|
||||||
|
def have_beans(self):
|
||||||
|
"In this state, you have some beans."
|
||||||
|
@_machine.state(initial=True)
|
||||||
|
def dont_have_beans(self):
|
||||||
|
"In this state, you don't have any beans."
|
||||||
|
|
||||||
|
``dont_have_beans`` is the ``initial`` state because ``CoffeeBrewer`` starts without beans
|
||||||
|
in it.
|
||||||
|
|
||||||
|
(And another input to put some beans in:)
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
@_machine.input()
|
||||||
|
def put_in_beans(self):
|
||||||
|
"The user put in some beans."
|
||||||
|
|
||||||
|
Finally, you hook everything together with the ``upon`` method of the functions
|
||||||
|
decorated with ``_machine.state``\ :
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
|
||||||
|
# When we don't have beans, upon putting in beans, we will then have beans
|
||||||
|
# (and produce no output)
|
||||||
|
dont_have_beans.upon(put_in_beans, enter=have_beans, outputs=[])
|
||||||
|
|
||||||
|
# When we have beans, upon pressing the brew button, we will then not have
|
||||||
|
# beans any more (as they have been entered into the brewing chamber) and
|
||||||
|
# our output will be heating the heating element.
|
||||||
|
have_beans.upon(brew_button, enter=dont_have_beans,
|
||||||
|
outputs=[_heat_the_heating_element])
|
||||||
|
|
||||||
|
To *users* of this coffee machine class though, it still looks like a POPO
|
||||||
|
(Plain Old Python Object):
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
>>> coffee_machine = CoffeeMachine()
|
||||||
|
>>> coffee_machine.put_in_beans()
|
||||||
|
>>> coffee_machine.brew_button()
|
||||||
|
|
||||||
|
All of the *inputs* are provided by calling them like methods, all of the
|
||||||
|
*outputs* are automatically invoked when they are produced according to the
|
||||||
|
outputs specified to ``upon`` and all of the states are simply opaque tokens -
|
||||||
|
although the fact that they're defined as methods like inputs and outputs
|
||||||
|
allows you to put docstrings on them easily to document them.
|
||||||
|
|
||||||
|
How do I get the current state of a state machine?
|
||||||
|
--------------------------------------------------
|
||||||
|
|
||||||
|
Don't do that.
|
||||||
|
|
||||||
|
One major reason for having a state machine is that you want the callers of the
|
||||||
|
state machine to just provide the appropriate input to the machine at the
|
||||||
|
appropriate time, and *not have to check themselves* what state the machine is
|
||||||
|
in. So if you are tempted to write some code like this:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
if connection_state_machine.state == "CONNECTED":
|
||||||
|
connection_state_machine.send_message()
|
||||||
|
else:
|
||||||
|
print("not connected")
|
||||||
|
|
||||||
|
Instead, just make your calling code do this:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
connection_state_machine.send_message()
|
||||||
|
|
||||||
|
and then change your state machine to look like this:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
@_machine.state()
|
||||||
|
def connected(self):
|
||||||
|
"connected"
|
||||||
|
@_machine.state()
|
||||||
|
def not_connected(self):
|
||||||
|
"not connected"
|
||||||
|
@_machine.input()
|
||||||
|
def send_message(self):
|
||||||
|
"send a message"
|
||||||
|
@_machine.output()
|
||||||
|
def _actually_send_message(self):
|
||||||
|
self._transport.send(b"message")
|
||||||
|
@_machine.output()
|
||||||
|
def _report_sending_failure(self):
|
||||||
|
print("not connected")
|
||||||
|
connected.upon(send_message, enter=connected, [_actually_send_message])
|
||||||
|
not_connected.upon(send_message, enter=not_connected, [_report_sending_failure])
|
||||||
|
|
||||||
|
so that the responsibility for knowing which state the state machine is in
|
||||||
|
remains within the state machine itself.
|
||||||
|
|
||||||
|
Input for Inputs and Output for Outputs
|
||||||
|
---------------------------------------
|
||||||
|
|
||||||
|
Quite often you want to be able to pass parameters to your methods, as well as
|
||||||
|
inspecting their results. For example, when you brew the coffee, you might
|
||||||
|
expect a cup of coffee to result, and you would like to see what kind of coffee
|
||||||
|
it is. And if you were to put delicious hand-roasted small-batch artisanal
|
||||||
|
beans into the machine, you would expect a *better* cup of coffee than if you
|
||||||
|
were to use mass-produced beans. You would do this in plain old Python by
|
||||||
|
adding a parameter, so that's how you do it in Automat as well.
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
@_machine.input()
|
||||||
|
def put_in_beans(self, beans):
|
||||||
|
"The user put in some beans."
|
||||||
|
|
||||||
|
However, one important difference here is that *we can't add any
|
||||||
|
implementation code to the input method*. Inputs are purely a declaration of
|
||||||
|
the interface; the behavior must all come from outputs. Therefore, the change
|
||||||
|
in the state of the coffee machine must be represented as an output. We can
|
||||||
|
add an output method like this:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
@_machine.output()
|
||||||
|
def _save_beans(self, beans):
|
||||||
|
"The beans are now in the machine; save them."
|
||||||
|
self._beans = beans
|
||||||
|
|
||||||
|
and then connect it to the ``put_in_beans`` by changing the transition from
|
||||||
|
``dont_have_beans`` to ``have_beans`` like so:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
dont_have_beans.upon(put_in_beans, enter=have_beans,
|
||||||
|
outputs=[_save_beans])
|
||||||
|
|
||||||
|
Now, when you call:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
coffee_machine.put_in_beans("real good beans")
|
||||||
|
|
||||||
|
the machine will remember the beans for later.
|
||||||
|
|
||||||
|
So how do we get the beans back out again? One of our outputs needs to have a
|
||||||
|
return value. It would make sense if our ``brew_button`` method returned the cup
|
||||||
|
of coffee that it made, so we should add an output. So, in addition to heating
|
||||||
|
the heating element, let's add a return value that describes the coffee. First
|
||||||
|
a new output:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
@_machine.output()
|
||||||
|
def _describe_coffee(self):
|
||||||
|
return "A cup of coffee made with {}.".format(self._beans)
|
||||||
|
|
||||||
|
Note that we don't need to check first whether ``self._beans`` exists or not,
|
||||||
|
because we can only reach this output method if the state machine says we've
|
||||||
|
gone through a set of states that sets this attribute.
|
||||||
|
|
||||||
|
Now, we need to hook up ``_describe_coffee`` to the process of brewing, so change
|
||||||
|
the brewing transition to:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
have_beans.upon(brew_button, enter=dont_have_beans,
|
||||||
|
outputs=[_heat_the_heating_element,
|
||||||
|
_describe_coffee])
|
||||||
|
|
||||||
|
Now, we can call it:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
>>> coffee_machine.brew_button()
|
||||||
|
[None, 'A cup of coffee made with real good beans.']
|
||||||
|
|
||||||
|
Except... wait a second, what's that ``None`` doing there?
|
||||||
|
|
||||||
|
Since every input can produce multiple outputs, in automat, the default return
|
||||||
|
value from every input invocation is a ``list``. In this case, we have both
|
||||||
|
``_heat_the_heating_element`` and ``_describe_coffee`` outputs, so we're seeing
|
||||||
|
both of their return values. However, this can be customized, with the
|
||||||
|
``collector`` argument to ``upon``\ ; the ``collector`` is a callable which takes an
|
||||||
|
iterable of all the outputs' return values and "collects" a single return value
|
||||||
|
to return to the caller of the state machine.
|
||||||
|
|
||||||
|
In this case, we only care about the last output, so we can adjust the call to
|
||||||
|
``upon`` like this:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
have_beans.upon(brew_button, enter=dont_have_beans,
|
||||||
|
outputs=[_heat_the_heating_element,
|
||||||
|
_describe_coffee],
|
||||||
|
collector=lambda iterable: list(iterable)[-1]
|
||||||
|
)
|
||||||
|
|
||||||
|
And now, we'll get just the return value we want:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
>>> coffee_machine.brew_button()
|
||||||
|
'A cup of coffee made with real good beans.'
|
||||||
|
|
||||||
|
If I can't get the state of the state machine, how can I save it to (a database, an API response, a file on disk...)
|
||||||
|
--------------------------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
There are APIs for serializing the state machine.
|
||||||
|
|
||||||
|
First, you have to decide on a persistent representation of each state, via the
|
||||||
|
``serialized=`` argument to the ``MethodicalMachine.state()`` decorator.
|
||||||
|
|
||||||
|
Let's take this very simple "light switch" state machine, which can be on or
|
||||||
|
off, and flipped to reverse its state:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
class LightSwitch(object):
|
||||||
|
_machine = MethodicalMachine()
|
||||||
|
@_machine.state(serialized="on")
|
||||||
|
def on_state(self):
|
||||||
|
"the switch is on"
|
||||||
|
@_machine.state(serialized="off", initial=True)
|
||||||
|
def off_state(self):
|
||||||
|
"the switch is off"
|
||||||
|
@_machine.input()
|
||||||
|
def flip(self):
|
||||||
|
"flip the switch"
|
||||||
|
on_state.upon(flip, enter=off_state, outputs=[])
|
||||||
|
off_state.upon(flip, enter=on_state, outputs=[])
|
||||||
|
|
||||||
|
In this case, we've chosen a serialized representation for each state via the
|
||||||
|
``serialized`` argument. The on state is represented by the string ``"on"``\ , and
|
||||||
|
the off state is represented by the string ``"off"``.
|
||||||
|
|
||||||
|
Now, let's just add an input that lets us tell if the switch is on or not.
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
@_machine.input()
|
||||||
|
def query_power(self):
|
||||||
|
"return True if powered, False otherwise"
|
||||||
|
@_machine.output()
|
||||||
|
def _is_powered(self):
|
||||||
|
return True
|
||||||
|
@_machine.output()
|
||||||
|
def _not_powered(self):
|
||||||
|
return False
|
||||||
|
on_state.upon(query_power, enter=on_state, outputs=[_is_powered],
|
||||||
|
collector=next)
|
||||||
|
off_state.upon(query_power, enter=off_state, outputs=[_not_powered],
|
||||||
|
collector=next)
|
||||||
|
|
||||||
|
To save the state, we have the ``MethodicalMachine.serializer()`` method. A
|
||||||
|
method decorated with ``@serializer()`` gets an extra argument injected at the
|
||||||
|
beginning of its argument list: the serialized identifier for the state. In
|
||||||
|
this case, either ``"on"`` or ``"off"``. Since state machine output methods can
|
||||||
|
also affect other state on the object, a serializer method is expected to
|
||||||
|
return *all* relevant state for serialization.
|
||||||
|
|
||||||
|
For our simple light switch, such a method might look like this:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
@_machine.serializer()
|
||||||
|
def save(self, state):
|
||||||
|
return {"is-it-on": state}
|
||||||
|
|
||||||
|
Serializers can be public methods, and they can return whatever you like. If
|
||||||
|
necessary, you can have different serializers - just multiple methods decorated
|
||||||
|
with ``@_machine.serializer()`` - for different formats; return one data-structure
|
||||||
|
for JSON, one for XML, one for a database row, and so on.
|
||||||
|
|
||||||
|
When it comes time to unserialize, though, you generally want a private method,
|
||||||
|
because an unserializer has to take a not-fully-initialized instance and
|
||||||
|
populate it with state. It is expected to *return* the serialized machine
|
||||||
|
state token that was passed to the serializer, but it can take whatever
|
||||||
|
arguments you like. Of course, in order to return that, it probably has to
|
||||||
|
take it somewhere in its arguments, so it will generally take whatever a paired
|
||||||
|
serializer has returned as an argument.
|
||||||
|
|
||||||
|
So our unserializer would look like this:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
@_machine.unserializer()
|
||||||
|
def _restore(self, blob):
|
||||||
|
return blob["is-it-on"]
|
||||||
|
|
||||||
|
Generally you will want a classmethod deserialization constructor which you
|
||||||
|
write yourself to call this, so that you know how to create an instance of your
|
||||||
|
own object, like so:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_blob(cls, blob):
|
||||||
|
self = cls()
|
||||||
|
self._restore(blob)
|
||||||
|
return self
|
||||||
|
|
||||||
|
Saving and loading our ``LightSwitch`` along with its state-machine state can now
|
||||||
|
be accomplished as follows:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
>>> switch1 = LightSwitch()
|
||||||
|
>>> switch1.query_power()
|
||||||
|
False
|
||||||
|
>>> switch1.flip()
|
||||||
|
[]
|
||||||
|
>>> switch1.query_power()
|
||||||
|
True
|
||||||
|
>>> blob = switch1.save()
|
||||||
|
>>> switch2 = LightSwitch.from_blob(blob)
|
||||||
|
>>> switch2.query_power()
|
||||||
|
True
|
||||||
|
|
||||||
|
More comprehensive (tested, working) examples are present in ``docs/examples``.
|
||||||
|
|
||||||
|
Go forth and machine all the state!
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -0,0 +1,32 @@
|
||||||
|
../../../bin/automat-visualize,sha256=8iWWSqIUrhiegd0it0lFrwM-JuAtUvd7q5A8j70nvj8,263
|
||||||
|
Automat-20.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
||||||
|
Automat-20.2.0.dist-info/LICENSE,sha256=siATAWeNCpN9k4VDgnyhNgcS6zTiPejuPzv_-9TA43Y,1053
|
||||||
|
Automat-20.2.0.dist-info/METADATA,sha256=RlZub3EgNMk1YDCNYTDJ80ksrBRzPjgzVnYsLrS44nU,17919
|
||||||
|
Automat-20.2.0.dist-info/RECORD,,
|
||||||
|
Automat-20.2.0.dist-info/WHEEL,sha256=CihQvCnsGZQBGAHLEUMf0IdA4fRduS_NBUTMgCTtvPM,110
|
||||||
|
Automat-20.2.0.dist-info/entry_points.txt,sha256=i4tDM5qwy3v1KIN7ETS2XRVcHkThhkq7ZFTPuyP6BpA,63
|
||||||
|
Automat-20.2.0.dist-info/top_level.txt,sha256=vg4zAOyhP_3YCmpKZLNgFw1uMF3lC_b6TKsdz7jBSpI,8
|
||||||
|
automat/__init__.py,sha256=ec8PILBwt35xyzsstU9kx8p5ADi6KX9d1rBLZsocN_Y,169
|
||||||
|
automat/__pycache__/__init__.cpython-39.pyc,,
|
||||||
|
automat/__pycache__/_core.cpython-39.pyc,,
|
||||||
|
automat/__pycache__/_discover.cpython-39.pyc,,
|
||||||
|
automat/__pycache__/_introspection.cpython-39.pyc,,
|
||||||
|
automat/__pycache__/_methodical.cpython-39.pyc,,
|
||||||
|
automat/__pycache__/_visualize.cpython-39.pyc,,
|
||||||
|
automat/_core.py,sha256=IEtZHq3wsBZPX_VfMHMFy_uNjx1kfE11Qq-nmIXZe28,4819
|
||||||
|
automat/_discover.py,sha256=ye7NHLZkrwYsPmBpTIyJuJ-VRCmwkOUpA0is-A81z04,4367
|
||||||
|
automat/_introspection.py,sha256=i5UEGdj8lp2BnHnGeAyIwEyoN2gU1nXYg-ZPNX7oBbM,1274
|
||||||
|
automat/_methodical.py,sha256=tvIQLMzMM1d6h_jUCQOM9zPJoGYYQZg0J5IkRszgjB0,15930
|
||||||
|
automat/_test/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||||
|
automat/_test/__pycache__/__init__.cpython-39.pyc,,
|
||||||
|
automat/_test/__pycache__/test_core.cpython-39.pyc,,
|
||||||
|
automat/_test/__pycache__/test_discover.cpython-39.pyc,,
|
||||||
|
automat/_test/__pycache__/test_methodical.cpython-39.pyc,,
|
||||||
|
automat/_test/__pycache__/test_trace.cpython-39.pyc,,
|
||||||
|
automat/_test/__pycache__/test_visualize.cpython-39.pyc,,
|
||||||
|
automat/_test/test_core.py,sha256=CDmGBQNi9Pr7ZktfBcOhBvwI7wjLLYRtWZ0P5baXONY,2833
|
||||||
|
automat/_test/test_discover.py,sha256=O9ndAdRAC8uO0uDhioz3e45EsJCF19jQZESj0RBC7ZM,21846
|
||||||
|
automat/_test/test_methodical.py,sha256=t1CAKtT1fs-FoKMQxXl4ky6_6pgpG7lGDbyQrb_vIeo,18856
|
||||||
|
automat/_test/test_trace.py,sha256=Mx1B8QgaE7QFk6blTie2j-Vx95hTV-zySnlxLalt8ek,3279
|
||||||
|
automat/_test/test_visualize.py,sha256=8ErNYxovTiDyZkYkoP1BcyEazU_s0YQ3NHdfH9OihAg,13744
|
||||||
|
automat/_visualize.py,sha256=jY8HkzaGdMoXB7LavvaneW4GdtBN6PRShl7-4OXDvss,6335
|
||||||
|
|
@ -0,0 +1,6 @@
|
||||||
|
Wheel-Version: 1.0
|
||||||
|
Generator: bdist_wheel (0.32.2)
|
||||||
|
Root-Is-Purelib: true
|
||||||
|
Tag: py2-none-any
|
||||||
|
Tag: py3-none-any
|
||||||
|
|
||||||
|
|
@ -0,0 +1,3 @@
|
||||||
|
[console_scripts]
|
||||||
|
automat-visualize = automat._visualize:tool
|
||||||
|
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
automat
|
||||||
2521
venv/lib/python3.9/site-packages/OpenSSL/SSL.py
Normal file
20
venv/lib/python3.9/site-packages/OpenSSL/__init__.py
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
# Copyright (C) AB Strakt
|
||||||
|
# See LICENSE for details.
|
||||||
|
|
||||||
|
"""
|
||||||
|
pyOpenSSL - A simple wrapper around the OpenSSL library
|
||||||
|
"""
|
||||||
|
|
||||||
|
from OpenSSL import crypto, SSL
|
||||||
|
from OpenSSL.version import (
|
||||||
|
__author__, __copyright__, __email__, __license__, __summary__, __title__,
|
||||||
|
__uri__, __version__,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"SSL", "crypto",
|
||||||
|
|
||||||
|
"__author__", "__copyright__", "__email__", "__license__", "__summary__",
|
||||||
|
"__title__", "__uri__", "__version__",
|
||||||
|
]
|
||||||
161
venv/lib/python3.9/site-packages/OpenSSL/_util.py
Normal file
|
|
@ -0,0 +1,161 @@
|
||||||
|
import sys
|
||||||
|
import warnings
|
||||||
|
|
||||||
|
from six import PY2, binary_type, text_type
|
||||||
|
|
||||||
|
from cryptography.hazmat.bindings.openssl.binding import Binding
|
||||||
|
|
||||||
|
|
||||||
|
binding = Binding()
|
||||||
|
binding.init_static_locks()
|
||||||
|
ffi = binding.ffi
|
||||||
|
lib = binding.lib
|
||||||
|
|
||||||
|
|
||||||
|
# This is a special CFFI allocator that does not bother to zero its memory
|
||||||
|
# after allocation. This has vastly better performance on large allocations and
|
||||||
|
# so should be used whenever we don't need the memory zeroed out.
|
||||||
|
no_zero_allocator = ffi.new_allocator(should_clear_after_alloc=False)
|
||||||
|
|
||||||
|
|
||||||
|
def text(charp):
|
||||||
|
"""
|
||||||
|
Get a native string type representing of the given CFFI ``char*`` object.
|
||||||
|
|
||||||
|
:param charp: A C-style string represented using CFFI.
|
||||||
|
|
||||||
|
:return: :class:`str`
|
||||||
|
"""
|
||||||
|
if not charp:
|
||||||
|
return ""
|
||||||
|
return native(ffi.string(charp))
|
||||||
|
|
||||||
|
|
||||||
|
def exception_from_error_queue(exception_type):
|
||||||
|
"""
|
||||||
|
Convert an OpenSSL library failure into a Python exception.
|
||||||
|
|
||||||
|
When a call to the native OpenSSL library fails, this is usually signalled
|
||||||
|
by the return value, and an error code is stored in an error queue
|
||||||
|
associated with the current thread. The err library provides functions to
|
||||||
|
obtain these error codes and textual error messages.
|
||||||
|
"""
|
||||||
|
errors = []
|
||||||
|
|
||||||
|
while True:
|
||||||
|
error = lib.ERR_get_error()
|
||||||
|
if error == 0:
|
||||||
|
break
|
||||||
|
errors.append((
|
||||||
|
text(lib.ERR_lib_error_string(error)),
|
||||||
|
text(lib.ERR_func_error_string(error)),
|
||||||
|
text(lib.ERR_reason_error_string(error))))
|
||||||
|
|
||||||
|
raise exception_type(errors)
|
||||||
|
|
||||||
|
|
||||||
|
def make_assert(error):
|
||||||
|
"""
|
||||||
|
Create an assert function that uses :func:`exception_from_error_queue` to
|
||||||
|
raise an exception wrapped by *error*.
|
||||||
|
"""
|
||||||
|
def openssl_assert(ok):
|
||||||
|
"""
|
||||||
|
If *ok* is not True, retrieve the error from OpenSSL and raise it.
|
||||||
|
"""
|
||||||
|
if ok is not True:
|
||||||
|
exception_from_error_queue(error)
|
||||||
|
|
||||||
|
return openssl_assert
|
||||||
|
|
||||||
|
|
||||||
|
def native(s):
|
||||||
|
"""
|
||||||
|
Convert :py:class:`bytes` or :py:class:`unicode` to the native
|
||||||
|
:py:class:`str` type, using UTF-8 encoding if conversion is necessary.
|
||||||
|
|
||||||
|
:raise UnicodeError: The input string is not UTF-8 decodeable.
|
||||||
|
|
||||||
|
:raise TypeError: The input is neither :py:class:`bytes` nor
|
||||||
|
:py:class:`unicode`.
|
||||||
|
"""
|
||||||
|
if not isinstance(s, (binary_type, text_type)):
|
||||||
|
raise TypeError("%r is neither bytes nor unicode" % s)
|
||||||
|
if PY2:
|
||||||
|
if isinstance(s, text_type):
|
||||||
|
return s.encode("utf-8")
|
||||||
|
else:
|
||||||
|
if isinstance(s, binary_type):
|
||||||
|
return s.decode("utf-8")
|
||||||
|
return s
|
||||||
|
|
||||||
|
|
||||||
|
def path_string(s):
|
||||||
|
"""
|
||||||
|
Convert a Python string to a :py:class:`bytes` string identifying the same
|
||||||
|
path and which can be passed into an OpenSSL API accepting a filename.
|
||||||
|
|
||||||
|
:param s: An instance of :py:class:`bytes` or :py:class:`unicode`.
|
||||||
|
|
||||||
|
:return: An instance of :py:class:`bytes`.
|
||||||
|
"""
|
||||||
|
if isinstance(s, binary_type):
|
||||||
|
return s
|
||||||
|
elif isinstance(s, text_type):
|
||||||
|
return s.encode(sys.getfilesystemencoding())
|
||||||
|
else:
|
||||||
|
raise TypeError("Path must be represented as bytes or unicode string")
|
||||||
|
|
||||||
|
|
||||||
|
if PY2:
|
||||||
|
def byte_string(s):
|
||||||
|
return s
|
||||||
|
else:
|
||||||
|
def byte_string(s):
|
||||||
|
return s.encode("charmap")
|
||||||
|
|
||||||
|
|
||||||
|
# A marker object to observe whether some optional arguments are passed any
|
||||||
|
# value or not.
|
||||||
|
UNSPECIFIED = object()
|
||||||
|
|
||||||
|
_TEXT_WARNING = (
|
||||||
|
text_type.__name__ + " for {0} is no longer accepted, use bytes"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def text_to_bytes_and_warn(label, obj):
|
||||||
|
"""
|
||||||
|
If ``obj`` is text, emit a warning that it should be bytes instead and try
|
||||||
|
to convert it to bytes automatically.
|
||||||
|
|
||||||
|
:param str label: The name of the parameter from which ``obj`` was taken
|
||||||
|
(so a developer can easily find the source of the problem and correct
|
||||||
|
it).
|
||||||
|
|
||||||
|
:return: If ``obj`` is the text string type, a ``bytes`` object giving the
|
||||||
|
UTF-8 encoding of that text is returned. Otherwise, ``obj`` itself is
|
||||||
|
returned.
|
||||||
|
"""
|
||||||
|
if isinstance(obj, text_type):
|
||||||
|
warnings.warn(
|
||||||
|
_TEXT_WARNING.format(label),
|
||||||
|
category=DeprecationWarning,
|
||||||
|
stacklevel=3
|
||||||
|
)
|
||||||
|
return obj.encode('utf-8')
|
||||||
|
return obj
|
||||||
|
|
||||||
|
|
||||||
|
try:
|
||||||
|
# newer versions of cffi free the buffer deterministically
|
||||||
|
with ffi.from_buffer(b""):
|
||||||
|
pass
|
||||||
|
from_buffer = ffi.from_buffer
|
||||||
|
except AttributeError:
|
||||||
|
# cffi < 0.12 frees the buffer with refcounting gc
|
||||||
|
from contextlib import contextmanager
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def from_buffer(*args):
|
||||||
|
yield ffi.from_buffer(*args)
|
||||||
3064
venv/lib/python3.9/site-packages/OpenSSL/crypto.py
Normal file
42
venv/lib/python3.9/site-packages/OpenSSL/debug.py
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
from __future__ import print_function
|
||||||
|
|
||||||
|
import ssl
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import OpenSSL.SSL
|
||||||
|
import cffi
|
||||||
|
import cryptography
|
||||||
|
|
||||||
|
from . import version
|
||||||
|
|
||||||
|
|
||||||
|
_env_info = u"""\
|
||||||
|
pyOpenSSL: {pyopenssl}
|
||||||
|
cryptography: {cryptography}
|
||||||
|
cffi: {cffi}
|
||||||
|
cryptography's compiled against OpenSSL: {crypto_openssl_compile}
|
||||||
|
cryptography's linked OpenSSL: {crypto_openssl_link}
|
||||||
|
Pythons's OpenSSL: {python_openssl}
|
||||||
|
Python executable: {python}
|
||||||
|
Python version: {python_version}
|
||||||
|
Platform: {platform}
|
||||||
|
sys.path: {sys_path}""".format(
|
||||||
|
pyopenssl=version.__version__,
|
||||||
|
crypto_openssl_compile=OpenSSL._util.ffi.string(
|
||||||
|
OpenSSL._util.lib.OPENSSL_VERSION_TEXT,
|
||||||
|
).decode("ascii"),
|
||||||
|
crypto_openssl_link=OpenSSL.SSL.SSLeay_version(
|
||||||
|
OpenSSL.SSL.SSLEAY_VERSION
|
||||||
|
).decode("ascii"),
|
||||||
|
python_openssl=getattr(ssl, "OPENSSL_VERSION", "n/a"),
|
||||||
|
cryptography=cryptography.__version__,
|
||||||
|
cffi=cffi.__version__,
|
||||||
|
python=sys.executable,
|
||||||
|
python_version=sys.version,
|
||||||
|
platform=sys.platform,
|
||||||
|
sys_path=sys.path,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
print(_env_info)
|
||||||
40
venv/lib/python3.9/site-packages/OpenSSL/rand.py
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
"""
|
||||||
|
PRNG management routines, thin wrappers.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from OpenSSL._util import lib as _lib
|
||||||
|
|
||||||
|
|
||||||
|
def add(buffer, entropy):
|
||||||
|
"""
|
||||||
|
Mix bytes from *string* into the PRNG state.
|
||||||
|
|
||||||
|
The *entropy* argument is (the lower bound of) an estimate of how much
|
||||||
|
randomness is contained in *string*, measured in bytes.
|
||||||
|
|
||||||
|
For more information, see e.g. :rfc:`1750`.
|
||||||
|
|
||||||
|
This function is only relevant if you are forking Python processes and
|
||||||
|
need to reseed the CSPRNG after fork.
|
||||||
|
|
||||||
|
:param buffer: Buffer with random data.
|
||||||
|
:param entropy: The entropy (in bytes) measurement of the buffer.
|
||||||
|
|
||||||
|
:return: :obj:`None`
|
||||||
|
"""
|
||||||
|
if not isinstance(buffer, bytes):
|
||||||
|
raise TypeError("buffer must be a byte string")
|
||||||
|
|
||||||
|
if not isinstance(entropy, int):
|
||||||
|
raise TypeError("entropy must be an integer")
|
||||||
|
|
||||||
|
_lib.RAND_add(buffer, len(buffer), entropy)
|
||||||
|
|
||||||
|
|
||||||
|
def status():
|
||||||
|
"""
|
||||||
|
Check whether the PRNG has been seeded with enough data.
|
||||||
|
|
||||||
|
:return: 1 if the PRNG is seeded enough, 0 otherwise.
|
||||||
|
"""
|
||||||
|
return _lib.RAND_status()
|
||||||
31
venv/lib/python3.9/site-packages/OpenSSL/tsafe.py
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
import warnings
|
||||||
|
from threading import RLock as _RLock
|
||||||
|
|
||||||
|
from OpenSSL import SSL as _ssl
|
||||||
|
|
||||||
|
|
||||||
|
warnings.warn(
|
||||||
|
"OpenSSL.tsafe is deprecated and will be removed",
|
||||||
|
DeprecationWarning, stacklevel=3
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Connection:
|
||||||
|
def __init__(self, *args):
|
||||||
|
self._ssl_conn = _ssl.Connection(*args)
|
||||||
|
self._lock = _RLock()
|
||||||
|
|
||||||
|
for f in ('get_context', 'pending', 'send', 'write', 'recv', 'read',
|
||||||
|
'renegotiate', 'bind', 'listen', 'connect', 'accept',
|
||||||
|
'setblocking', 'fileno', 'shutdown', 'close', 'get_cipher_list',
|
||||||
|
'getpeername', 'getsockname', 'getsockopt', 'setsockopt',
|
||||||
|
'makefile', 'get_app_data', 'set_app_data', 'state_string',
|
||||||
|
'sock_shutdown', 'get_peer_certificate', 'get_peer_cert_chain',
|
||||||
|
'want_read', 'want_write', 'set_connect_state',
|
||||||
|
'set_accept_state', 'connect_ex', 'sendall'):
|
||||||
|
exec("""def %s(self, *args):
|
||||||
|
self._lock.acquire()
|
||||||
|
try:
|
||||||
|
return self._ssl_conn.%s(*args)
|
||||||
|
finally:
|
||||||
|
self._lock.release()\n""" % (f, f))
|
||||||
22
venv/lib/python3.9/site-packages/OpenSSL/version.py
Normal file
|
|
@ -0,0 +1,22 @@
|
||||||
|
# Copyright (C) AB Strakt
|
||||||
|
# Copyright (C) Jean-Paul Calderone
|
||||||
|
# See LICENSE for details.
|
||||||
|
|
||||||
|
"""
|
||||||
|
pyOpenSSL - A simple wrapper around the OpenSSL library
|
||||||
|
"""
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"__author__", "__copyright__", "__email__", "__license__", "__summary__",
|
||||||
|
"__title__", "__uri__", "__version__",
|
||||||
|
]
|
||||||
|
|
||||||
|
__version__ = "19.1.0"
|
||||||
|
|
||||||
|
__title__ = "pyOpenSSL"
|
||||||
|
__uri__ = "https://pyopenssl.org/"
|
||||||
|
__summary__ = "Python wrapper module around the OpenSSL library"
|
||||||
|
__author__ = "The pyOpenSSL developers"
|
||||||
|
__email__ = "cryptography-dev@python.org"
|
||||||
|
__license__ = "Apache License, Version 2.0"
|
||||||
|
__copyright__ = "Copyright 2001-2017 {0}".format(__author__)
|
||||||
BIN
venv/lib/python3.9/site-packages/PIL/.dylibs/libXau.6.dylib
Executable file
BIN
venv/lib/python3.9/site-packages/PIL/.dylibs/libfreetype.6.dylib
Executable file
BIN
venv/lib/python3.9/site-packages/PIL/.dylibs/libjpeg.9.dylib
Executable file
BIN
venv/lib/python3.9/site-packages/PIL/.dylibs/liblcms2.2.dylib
Executable file
BIN
venv/lib/python3.9/site-packages/PIL/.dylibs/liblzma.5.dylib
Executable file
BIN
venv/lib/python3.9/site-packages/PIL/.dylibs/libopenjp2.2.3.1.dylib
Executable file
BIN
venv/lib/python3.9/site-packages/PIL/.dylibs/libpng16.16.dylib
Executable file
BIN
venv/lib/python3.9/site-packages/PIL/.dylibs/libtiff.5.dylib
Executable file
BIN
venv/lib/python3.9/site-packages/PIL/.dylibs/libwebp.7.dylib
Executable file
BIN
venv/lib/python3.9/site-packages/PIL/.dylibs/libwebpdemux.2.dylib
Executable file
BIN
venv/lib/python3.9/site-packages/PIL/.dylibs/libwebpmux.3.dylib
Executable file
BIN
venv/lib/python3.9/site-packages/PIL/.dylibs/libxcb.1.1.0.dylib
Executable file
BIN
venv/lib/python3.9/site-packages/PIL/.dylibs/libz.1.2.11.dylib
Executable file
110
venv/lib/python3.9/site-packages/PIL/BdfFontFile.py
Normal file
|
|
@ -0,0 +1,110 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# bitmap distribution font (bdf) file parser
|
||||||
|
#
|
||||||
|
# history:
|
||||||
|
# 1996-05-16 fl created (as bdf2pil)
|
||||||
|
# 1997-08-25 fl converted to FontFile driver
|
||||||
|
# 2001-05-25 fl removed bogus __init__ call
|
||||||
|
# 2002-11-20 fl robustification (from Kevin Cazabon, Dmitry Vasiliev)
|
||||||
|
# 2003-04-22 fl more robustification (from Graham Dumpleton)
|
||||||
|
#
|
||||||
|
# Copyright (c) 1997-2003 by Secret Labs AB.
|
||||||
|
# Copyright (c) 1997-2003 by Fredrik Lundh.
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
"""
|
||||||
|
Parse X Bitmap Distribution Format (BDF)
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
from . import FontFile, Image
|
||||||
|
|
||||||
|
bdf_slant = {
|
||||||
|
"R": "Roman",
|
||||||
|
"I": "Italic",
|
||||||
|
"O": "Oblique",
|
||||||
|
"RI": "Reverse Italic",
|
||||||
|
"RO": "Reverse Oblique",
|
||||||
|
"OT": "Other",
|
||||||
|
}
|
||||||
|
|
||||||
|
bdf_spacing = {"P": "Proportional", "M": "Monospaced", "C": "Cell"}
|
||||||
|
|
||||||
|
|
||||||
|
def bdf_char(f):
|
||||||
|
# skip to STARTCHAR
|
||||||
|
while True:
|
||||||
|
s = f.readline()
|
||||||
|
if not s:
|
||||||
|
return None
|
||||||
|
if s[:9] == b"STARTCHAR":
|
||||||
|
break
|
||||||
|
id = s[9:].strip().decode("ascii")
|
||||||
|
|
||||||
|
# load symbol properties
|
||||||
|
props = {}
|
||||||
|
while True:
|
||||||
|
s = f.readline()
|
||||||
|
if not s or s[:6] == b"BITMAP":
|
||||||
|
break
|
||||||
|
i = s.find(b" ")
|
||||||
|
props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
|
||||||
|
|
||||||
|
# load bitmap
|
||||||
|
bitmap = []
|
||||||
|
while True:
|
||||||
|
s = f.readline()
|
||||||
|
if not s or s[:7] == b"ENDCHAR":
|
||||||
|
break
|
||||||
|
bitmap.append(s[:-1])
|
||||||
|
bitmap = b"".join(bitmap)
|
||||||
|
|
||||||
|
[x, y, l, d] = [int(p) for p in props["BBX"].split()]
|
||||||
|
[dx, dy] = [int(p) for p in props["DWIDTH"].split()]
|
||||||
|
|
||||||
|
bbox = (dx, dy), (l, -d - y, x + l, -d), (0, 0, x, y)
|
||||||
|
|
||||||
|
try:
|
||||||
|
im = Image.frombytes("1", (x, y), bitmap, "hex", "1")
|
||||||
|
except ValueError:
|
||||||
|
# deal with zero-width characters
|
||||||
|
im = Image.new("1", (x, y))
|
||||||
|
|
||||||
|
return id, int(props["ENCODING"]), bbox, im
|
||||||
|
|
||||||
|
|
||||||
|
class BdfFontFile(FontFile.FontFile):
|
||||||
|
"""Font file plugin for the X11 BDF format."""
|
||||||
|
|
||||||
|
def __init__(self, fp):
|
||||||
|
super().__init__()
|
||||||
|
|
||||||
|
s = fp.readline()
|
||||||
|
if s[:13] != b"STARTFONT 2.1":
|
||||||
|
raise SyntaxError("not a valid BDF file")
|
||||||
|
|
||||||
|
props = {}
|
||||||
|
comments = []
|
||||||
|
|
||||||
|
while True:
|
||||||
|
s = fp.readline()
|
||||||
|
if not s or s[:13] == b"ENDPROPERTIES":
|
||||||
|
break
|
||||||
|
i = s.find(b" ")
|
||||||
|
props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
|
||||||
|
if s[:i] in [b"COMMENT", b"COPYRIGHT"]:
|
||||||
|
if s.find(b"LogicalFontDescription") < 0:
|
||||||
|
comments.append(s[i + 1 : -1].decode("ascii"))
|
||||||
|
|
||||||
|
while True:
|
||||||
|
c = bdf_char(fp)
|
||||||
|
if not c:
|
||||||
|
break
|
||||||
|
id, ch, (xy, dst, src), im = c
|
||||||
|
if 0 <= ch < len(self.glyph):
|
||||||
|
self.glyph[ch] = xy, dst, src, im
|
||||||
422
venv/lib/python3.9/site-packages/PIL/BlpImagePlugin.py
Normal file
|
|
@ -0,0 +1,422 @@
|
||||||
|
"""
|
||||||
|
Blizzard Mipmap Format (.blp)
|
||||||
|
Jerome Leclanche <jerome@leclan.ch>
|
||||||
|
|
||||||
|
The contents of this file are hereby released in the public domain (CC0)
|
||||||
|
Full text of the CC0 license:
|
||||||
|
https://creativecommons.org/publicdomain/zero/1.0/
|
||||||
|
|
||||||
|
BLP1 files, used mostly in Warcraft III, are not fully supported.
|
||||||
|
All types of BLP2 files used in World of Warcraft are supported.
|
||||||
|
|
||||||
|
The BLP file structure consists of a header, up to 16 mipmaps of the
|
||||||
|
texture
|
||||||
|
|
||||||
|
Texture sizes must be powers of two, though the two dimensions do
|
||||||
|
not have to be equal; 512x256 is valid, but 512x200 is not.
|
||||||
|
The first mipmap (mipmap #0) is the full size image; each subsequent
|
||||||
|
mipmap halves both dimensions. The final mipmap should be 1x1.
|
||||||
|
|
||||||
|
BLP files come in many different flavours:
|
||||||
|
* JPEG-compressed (type == 0) - only supported for BLP1.
|
||||||
|
* RAW images (type == 1, encoding == 1). Each mipmap is stored as an
|
||||||
|
array of 8-bit values, one per pixel, left to right, top to bottom.
|
||||||
|
Each value is an index to the palette.
|
||||||
|
* DXT-compressed (type == 1, encoding == 2):
|
||||||
|
- DXT1 compression is used if alpha_encoding == 0.
|
||||||
|
- An additional alpha bit is used if alpha_depth == 1.
|
||||||
|
- DXT3 compression is used if alpha_encoding == 1.
|
||||||
|
- DXT5 compression is used if alpha_encoding == 7.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import struct
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
from . import Image, ImageFile
|
||||||
|
|
||||||
|
BLP_FORMAT_JPEG = 0
|
||||||
|
|
||||||
|
BLP_ENCODING_UNCOMPRESSED = 1
|
||||||
|
BLP_ENCODING_DXT = 2
|
||||||
|
BLP_ENCODING_UNCOMPRESSED_RAW_BGRA = 3
|
||||||
|
|
||||||
|
BLP_ALPHA_ENCODING_DXT1 = 0
|
||||||
|
BLP_ALPHA_ENCODING_DXT3 = 1
|
||||||
|
BLP_ALPHA_ENCODING_DXT5 = 7
|
||||||
|
|
||||||
|
|
||||||
|
def unpack_565(i):
|
||||||
|
return (((i >> 11) & 0x1F) << 3, ((i >> 5) & 0x3F) << 2, (i & 0x1F) << 3)
|
||||||
|
|
||||||
|
|
||||||
|
def decode_dxt1(data, alpha=False):
|
||||||
|
"""
|
||||||
|
input: one "row" of data (i.e. will produce 4*width pixels)
|
||||||
|
"""
|
||||||
|
|
||||||
|
blocks = len(data) // 8 # number of blocks in row
|
||||||
|
ret = (bytearray(), bytearray(), bytearray(), bytearray())
|
||||||
|
|
||||||
|
for block in range(blocks):
|
||||||
|
# Decode next 8-byte block.
|
||||||
|
idx = block * 8
|
||||||
|
color0, color1, bits = struct.unpack_from("<HHI", data, idx)
|
||||||
|
|
||||||
|
r0, g0, b0 = unpack_565(color0)
|
||||||
|
r1, g1, b1 = unpack_565(color1)
|
||||||
|
|
||||||
|
# Decode this block into 4x4 pixels
|
||||||
|
# Accumulate the results onto our 4 row accumulators
|
||||||
|
for j in range(4):
|
||||||
|
for i in range(4):
|
||||||
|
# get next control op and generate a pixel
|
||||||
|
|
||||||
|
control = bits & 3
|
||||||
|
bits = bits >> 2
|
||||||
|
|
||||||
|
a = 0xFF
|
||||||
|
if control == 0:
|
||||||
|
r, g, b = r0, g0, b0
|
||||||
|
elif control == 1:
|
||||||
|
r, g, b = r1, g1, b1
|
||||||
|
elif control == 2:
|
||||||
|
if color0 > color1:
|
||||||
|
r = (2 * r0 + r1) // 3
|
||||||
|
g = (2 * g0 + g1) // 3
|
||||||
|
b = (2 * b0 + b1) // 3
|
||||||
|
else:
|
||||||
|
r = (r0 + r1) // 2
|
||||||
|
g = (g0 + g1) // 2
|
||||||
|
b = (b0 + b1) // 2
|
||||||
|
elif control == 3:
|
||||||
|
if color0 > color1:
|
||||||
|
r = (2 * r1 + r0) // 3
|
||||||
|
g = (2 * g1 + g0) // 3
|
||||||
|
b = (2 * b1 + b0) // 3
|
||||||
|
else:
|
||||||
|
r, g, b, a = 0, 0, 0, 0
|
||||||
|
|
||||||
|
if alpha:
|
||||||
|
ret[j].extend([r, g, b, a])
|
||||||
|
else:
|
||||||
|
ret[j].extend([r, g, b])
|
||||||
|
|
||||||
|
return ret
|
||||||
|
|
||||||
|
|
||||||
|
def decode_dxt3(data):
|
||||||
|
"""
|
||||||
|
input: one "row" of data (i.e. will produce 4*width pixels)
|
||||||
|
"""
|
||||||
|
|
||||||
|
blocks = len(data) // 16 # number of blocks in row
|
||||||
|
ret = (bytearray(), bytearray(), bytearray(), bytearray())
|
||||||
|
|
||||||
|
for block in range(blocks):
|
||||||
|
idx = block * 16
|
||||||
|
block = data[idx : idx + 16]
|
||||||
|
# Decode next 16-byte block.
|
||||||
|
bits = struct.unpack_from("<8B", block)
|
||||||
|
color0, color1 = struct.unpack_from("<HH", block, 8)
|
||||||
|
|
||||||
|
(code,) = struct.unpack_from("<I", block, 12)
|
||||||
|
|
||||||
|
r0, g0, b0 = unpack_565(color0)
|
||||||
|
r1, g1, b1 = unpack_565(color1)
|
||||||
|
|
||||||
|
for j in range(4):
|
||||||
|
high = False # Do we want the higher bits?
|
||||||
|
for i in range(4):
|
||||||
|
alphacode_index = (4 * j + i) // 2
|
||||||
|
a = bits[alphacode_index]
|
||||||
|
if high:
|
||||||
|
high = False
|
||||||
|
a >>= 4
|
||||||
|
else:
|
||||||
|
high = True
|
||||||
|
a &= 0xF
|
||||||
|
a *= 17 # We get a value between 0 and 15
|
||||||
|
|
||||||
|
color_code = (code >> 2 * (4 * j + i)) & 0x03
|
||||||
|
|
||||||
|
if color_code == 0:
|
||||||
|
r, g, b = r0, g0, b0
|
||||||
|
elif color_code == 1:
|
||||||
|
r, g, b = r1, g1, b1
|
||||||
|
elif color_code == 2:
|
||||||
|
r = (2 * r0 + r1) // 3
|
||||||
|
g = (2 * g0 + g1) // 3
|
||||||
|
b = (2 * b0 + b1) // 3
|
||||||
|
elif color_code == 3:
|
||||||
|
r = (2 * r1 + r0) // 3
|
||||||
|
g = (2 * g1 + g0) // 3
|
||||||
|
b = (2 * b1 + b0) // 3
|
||||||
|
|
||||||
|
ret[j].extend([r, g, b, a])
|
||||||
|
|
||||||
|
return ret
|
||||||
|
|
||||||
|
|
||||||
|
def decode_dxt5(data):
|
||||||
|
"""
|
||||||
|
input: one "row" of data (i.e. will produce 4 * width pixels)
|
||||||
|
"""
|
||||||
|
|
||||||
|
blocks = len(data) // 16 # number of blocks in row
|
||||||
|
ret = (bytearray(), bytearray(), bytearray(), bytearray())
|
||||||
|
|
||||||
|
for block in range(blocks):
|
||||||
|
idx = block * 16
|
||||||
|
block = data[idx : idx + 16]
|
||||||
|
# Decode next 16-byte block.
|
||||||
|
a0, a1 = struct.unpack_from("<BB", block)
|
||||||
|
|
||||||
|
bits = struct.unpack_from("<6B", block, 2)
|
||||||
|
alphacode1 = bits[2] | (bits[3] << 8) | (bits[4] << 16) | (bits[5] << 24)
|
||||||
|
alphacode2 = bits[0] | (bits[1] << 8)
|
||||||
|
|
||||||
|
color0, color1 = struct.unpack_from("<HH", block, 8)
|
||||||
|
|
||||||
|
(code,) = struct.unpack_from("<I", block, 12)
|
||||||
|
|
||||||
|
r0, g0, b0 = unpack_565(color0)
|
||||||
|
r1, g1, b1 = unpack_565(color1)
|
||||||
|
|
||||||
|
for j in range(4):
|
||||||
|
for i in range(4):
|
||||||
|
# get next control op and generate a pixel
|
||||||
|
alphacode_index = 3 * (4 * j + i)
|
||||||
|
|
||||||
|
if alphacode_index <= 12:
|
||||||
|
alphacode = (alphacode2 >> alphacode_index) & 0x07
|
||||||
|
elif alphacode_index == 15:
|
||||||
|
alphacode = (alphacode2 >> 15) | ((alphacode1 << 1) & 0x06)
|
||||||
|
else: # alphacode_index >= 18 and alphacode_index <= 45
|
||||||
|
alphacode = (alphacode1 >> (alphacode_index - 16)) & 0x07
|
||||||
|
|
||||||
|
if alphacode == 0:
|
||||||
|
a = a0
|
||||||
|
elif alphacode == 1:
|
||||||
|
a = a1
|
||||||
|
elif a0 > a1:
|
||||||
|
a = ((8 - alphacode) * a0 + (alphacode - 1) * a1) // 7
|
||||||
|
elif alphacode == 6:
|
||||||
|
a = 0
|
||||||
|
elif alphacode == 7:
|
||||||
|
a = 255
|
||||||
|
else:
|
||||||
|
a = ((6 - alphacode) * a0 + (alphacode - 1) * a1) // 5
|
||||||
|
|
||||||
|
color_code = (code >> 2 * (4 * j + i)) & 0x03
|
||||||
|
|
||||||
|
if color_code == 0:
|
||||||
|
r, g, b = r0, g0, b0
|
||||||
|
elif color_code == 1:
|
||||||
|
r, g, b = r1, g1, b1
|
||||||
|
elif color_code == 2:
|
||||||
|
r = (2 * r0 + r1) // 3
|
||||||
|
g = (2 * g0 + g1) // 3
|
||||||
|
b = (2 * b0 + b1) // 3
|
||||||
|
elif color_code == 3:
|
||||||
|
r = (2 * r1 + r0) // 3
|
||||||
|
g = (2 * g1 + g0) // 3
|
||||||
|
b = (2 * b1 + b0) // 3
|
||||||
|
|
||||||
|
ret[j].extend([r, g, b, a])
|
||||||
|
|
||||||
|
return ret
|
||||||
|
|
||||||
|
|
||||||
|
class BLPFormatError(NotImplementedError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class BlpImageFile(ImageFile.ImageFile):
|
||||||
|
"""
|
||||||
|
Blizzard Mipmap Format
|
||||||
|
"""
|
||||||
|
|
||||||
|
format = "BLP"
|
||||||
|
format_description = "Blizzard Mipmap Format"
|
||||||
|
|
||||||
|
def _open(self):
|
||||||
|
self.magic = self.fp.read(4)
|
||||||
|
self._read_blp_header()
|
||||||
|
|
||||||
|
if self.magic == b"BLP1":
|
||||||
|
decoder = "BLP1"
|
||||||
|
self.mode = "RGB"
|
||||||
|
elif self.magic == b"BLP2":
|
||||||
|
decoder = "BLP2"
|
||||||
|
self.mode = "RGBA" if self._blp_alpha_depth else "RGB"
|
||||||
|
else:
|
||||||
|
raise BLPFormatError(f"Bad BLP magic {repr(self.magic)}")
|
||||||
|
|
||||||
|
self.tile = [(decoder, (0, 0) + self.size, 0, (self.mode, 0, 1))]
|
||||||
|
|
||||||
|
def _read_blp_header(self):
|
||||||
|
(self._blp_compression,) = struct.unpack("<i", self.fp.read(4))
|
||||||
|
|
||||||
|
(self._blp_encoding,) = struct.unpack("<b", self.fp.read(1))
|
||||||
|
(self._blp_alpha_depth,) = struct.unpack("<b", self.fp.read(1))
|
||||||
|
(self._blp_alpha_encoding,) = struct.unpack("<b", self.fp.read(1))
|
||||||
|
(self._blp_mips,) = struct.unpack("<b", self.fp.read(1))
|
||||||
|
|
||||||
|
self._size = struct.unpack("<II", self.fp.read(8))
|
||||||
|
|
||||||
|
if self.magic == b"BLP1":
|
||||||
|
# Only present for BLP1
|
||||||
|
(self._blp_encoding,) = struct.unpack("<i", self.fp.read(4))
|
||||||
|
(self._blp_subtype,) = struct.unpack("<i", self.fp.read(4))
|
||||||
|
|
||||||
|
self._blp_offsets = struct.unpack("<16I", self.fp.read(16 * 4))
|
||||||
|
self._blp_lengths = struct.unpack("<16I", self.fp.read(16 * 4))
|
||||||
|
|
||||||
|
|
||||||
|
class _BLPBaseDecoder(ImageFile.PyDecoder):
|
||||||
|
_pulls_fd = True
|
||||||
|
|
||||||
|
def decode(self, buffer):
|
||||||
|
try:
|
||||||
|
self.fd.seek(0)
|
||||||
|
self.magic = self.fd.read(4)
|
||||||
|
self._read_blp_header()
|
||||||
|
self._load()
|
||||||
|
except struct.error as e:
|
||||||
|
raise OSError("Truncated Blp file") from e
|
||||||
|
return 0, 0
|
||||||
|
|
||||||
|
def _read_palette(self):
|
||||||
|
ret = []
|
||||||
|
for i in range(256):
|
||||||
|
try:
|
||||||
|
b, g, r, a = struct.unpack("<4B", self.fd.read(4))
|
||||||
|
except struct.error:
|
||||||
|
break
|
||||||
|
ret.append((b, g, r, a))
|
||||||
|
return ret
|
||||||
|
|
||||||
|
def _read_blp_header(self):
|
||||||
|
(self._blp_compression,) = struct.unpack("<i", self.fd.read(4))
|
||||||
|
|
||||||
|
(self._blp_encoding,) = struct.unpack("<b", self.fd.read(1))
|
||||||
|
(self._blp_alpha_depth,) = struct.unpack("<b", self.fd.read(1))
|
||||||
|
(self._blp_alpha_encoding,) = struct.unpack("<b", self.fd.read(1))
|
||||||
|
(self._blp_mips,) = struct.unpack("<b", self.fd.read(1))
|
||||||
|
|
||||||
|
self.size = struct.unpack("<II", self.fd.read(8))
|
||||||
|
|
||||||
|
if self.magic == b"BLP1":
|
||||||
|
# Only present for BLP1
|
||||||
|
(self._blp_encoding,) = struct.unpack("<i", self.fd.read(4))
|
||||||
|
(self._blp_subtype,) = struct.unpack("<i", self.fd.read(4))
|
||||||
|
|
||||||
|
self._blp_offsets = struct.unpack("<16I", self.fd.read(16 * 4))
|
||||||
|
self._blp_lengths = struct.unpack("<16I", self.fd.read(16 * 4))
|
||||||
|
|
||||||
|
|
||||||
|
class BLP1Decoder(_BLPBaseDecoder):
|
||||||
|
def _load(self):
|
||||||
|
if self._blp_compression == BLP_FORMAT_JPEG:
|
||||||
|
self._decode_jpeg_stream()
|
||||||
|
|
||||||
|
elif self._blp_compression == 1:
|
||||||
|
if self._blp_encoding in (4, 5):
|
||||||
|
data = bytearray()
|
||||||
|
palette = self._read_palette()
|
||||||
|
_data = BytesIO(self.fd.read(self._blp_lengths[0]))
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
(offset,) = struct.unpack("<B", _data.read(1))
|
||||||
|
except struct.error:
|
||||||
|
break
|
||||||
|
b, g, r, a = palette[offset]
|
||||||
|
data.extend([r, g, b])
|
||||||
|
|
||||||
|
self.set_as_raw(bytes(data))
|
||||||
|
else:
|
||||||
|
raise BLPFormatError(
|
||||||
|
f"Unsupported BLP encoding {repr(self._blp_encoding)}"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise BLPFormatError(
|
||||||
|
f"Unsupported BLP compression {repr(self._blp_encoding)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
def _decode_jpeg_stream(self):
|
||||||
|
from PIL.JpegImagePlugin import JpegImageFile
|
||||||
|
|
||||||
|
(jpeg_header_size,) = struct.unpack("<I", self.fd.read(4))
|
||||||
|
jpeg_header = self.fd.read(jpeg_header_size)
|
||||||
|
self.fd.read(self._blp_offsets[0] - self.fd.tell()) # What IS this?
|
||||||
|
data = self.fd.read(self._blp_lengths[0])
|
||||||
|
data = jpeg_header + data
|
||||||
|
data = BytesIO(data)
|
||||||
|
image = JpegImageFile(data)
|
||||||
|
self.tile = image.tile # :/
|
||||||
|
self.fd = image.fp
|
||||||
|
self.mode = image.mode
|
||||||
|
|
||||||
|
|
||||||
|
class BLP2Decoder(_BLPBaseDecoder):
|
||||||
|
def _load(self):
|
||||||
|
palette = self._read_palette()
|
||||||
|
|
||||||
|
data = bytearray()
|
||||||
|
self.fd.seek(self._blp_offsets[0])
|
||||||
|
|
||||||
|
if self._blp_compression == 1:
|
||||||
|
# Uncompressed or DirectX compression
|
||||||
|
|
||||||
|
if self._blp_encoding == BLP_ENCODING_UNCOMPRESSED:
|
||||||
|
_data = BytesIO(self.fd.read(self._blp_lengths[0]))
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
(offset,) = struct.unpack("<B", _data.read(1))
|
||||||
|
except struct.error:
|
||||||
|
break
|
||||||
|
b, g, r, a = palette[offset]
|
||||||
|
data.extend((r, g, b))
|
||||||
|
|
||||||
|
elif self._blp_encoding == BLP_ENCODING_DXT:
|
||||||
|
if self._blp_alpha_encoding == BLP_ALPHA_ENCODING_DXT1:
|
||||||
|
linesize = (self.size[0] + 3) // 4 * 8
|
||||||
|
for yb in range((self.size[1] + 3) // 4):
|
||||||
|
for d in decode_dxt1(
|
||||||
|
self.fd.read(linesize), alpha=bool(self._blp_alpha_depth)
|
||||||
|
):
|
||||||
|
data += d
|
||||||
|
|
||||||
|
elif self._blp_alpha_encoding == BLP_ALPHA_ENCODING_DXT3:
|
||||||
|
linesize = (self.size[0] + 3) // 4 * 16
|
||||||
|
for yb in range((self.size[1] + 3) // 4):
|
||||||
|
for d in decode_dxt3(self.fd.read(linesize)):
|
||||||
|
data += d
|
||||||
|
|
||||||
|
elif self._blp_alpha_encoding == BLP_ALPHA_ENCODING_DXT5:
|
||||||
|
linesize = (self.size[0] + 3) // 4 * 16
|
||||||
|
for yb in range((self.size[1] + 3) // 4):
|
||||||
|
for d in decode_dxt5(self.fd.read(linesize)):
|
||||||
|
data += d
|
||||||
|
else:
|
||||||
|
raise BLPFormatError(
|
||||||
|
f"Unsupported alpha encoding {repr(self._blp_alpha_encoding)}"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise BLPFormatError(f"Unknown BLP encoding {repr(self._blp_encoding)}")
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise BLPFormatError(
|
||||||
|
f"Unknown BLP compression {repr(self._blp_compression)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.set_as_raw(bytes(data))
|
||||||
|
|
||||||
|
|
||||||
|
Image.register_open(
|
||||||
|
BlpImageFile.format, BlpImageFile, lambda p: p[:4] in (b"BLP1", b"BLP2")
|
||||||
|
)
|
||||||
|
Image.register_extension(BlpImageFile.format, ".blp")
|
||||||
|
|
||||||
|
Image.register_decoder("BLP1", BLP1Decoder)
|
||||||
|
Image.register_decoder("BLP2", BLP2Decoder)
|
||||||
381
venv/lib/python3.9/site-packages/PIL/BmpImagePlugin.py
Normal file
|
|
@ -0,0 +1,381 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library.
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# BMP file handler
|
||||||
|
#
|
||||||
|
# Windows (and OS/2) native bitmap storage format.
|
||||||
|
#
|
||||||
|
# history:
|
||||||
|
# 1995-09-01 fl Created
|
||||||
|
# 1996-04-30 fl Added save
|
||||||
|
# 1997-08-27 fl Fixed save of 1-bit images
|
||||||
|
# 1998-03-06 fl Load P images as L where possible
|
||||||
|
# 1998-07-03 fl Load P images as 1 where possible
|
||||||
|
# 1998-12-29 fl Handle small palettes
|
||||||
|
# 2002-12-30 fl Fixed load of 1-bit palette images
|
||||||
|
# 2003-04-21 fl Fixed load of 1-bit monochrome images
|
||||||
|
# 2003-04-23 fl Added limited support for BI_BITFIELDS compression
|
||||||
|
#
|
||||||
|
# Copyright (c) 1997-2003 by Secret Labs AB
|
||||||
|
# Copyright (c) 1995-2003 by Fredrik Lundh
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
|
||||||
|
from . import Image, ImageFile, ImagePalette
|
||||||
|
from ._binary import i8
|
||||||
|
from ._binary import i16le as i16
|
||||||
|
from ._binary import i32le as i32
|
||||||
|
from ._binary import o8
|
||||||
|
from ._binary import o16le as o16
|
||||||
|
from ._binary import o32le as o32
|
||||||
|
|
||||||
|
#
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# Read BMP file
|
||||||
|
|
||||||
|
BIT2MODE = {
|
||||||
|
# bits => mode, rawmode
|
||||||
|
1: ("P", "P;1"),
|
||||||
|
4: ("P", "P;4"),
|
||||||
|
8: ("P", "P"),
|
||||||
|
16: ("RGB", "BGR;15"),
|
||||||
|
24: ("RGB", "BGR"),
|
||||||
|
32: ("RGB", "BGRX"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _accept(prefix):
|
||||||
|
return prefix[:2] == b"BM"
|
||||||
|
|
||||||
|
|
||||||
|
def _dib_accept(prefix):
|
||||||
|
return i32(prefix[:4]) in [12, 40, 64, 108, 124]
|
||||||
|
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# Image plugin for the Windows BMP format.
|
||||||
|
# =============================================================================
|
||||||
|
class BmpImageFile(ImageFile.ImageFile):
|
||||||
|
""" Image plugin for the Windows Bitmap format (BMP) """
|
||||||
|
|
||||||
|
# ------------------------------------------------------------- Description
|
||||||
|
format_description = "Windows Bitmap"
|
||||||
|
format = "BMP"
|
||||||
|
|
||||||
|
# -------------------------------------------------- BMP Compression values
|
||||||
|
COMPRESSIONS = {"RAW": 0, "RLE8": 1, "RLE4": 2, "BITFIELDS": 3, "JPEG": 4, "PNG": 5}
|
||||||
|
for k, v in COMPRESSIONS.items():
|
||||||
|
vars()[k] = v
|
||||||
|
|
||||||
|
def _bitmap(self, header=0, offset=0):
|
||||||
|
""" Read relevant info about the BMP """
|
||||||
|
read, seek = self.fp.read, self.fp.seek
|
||||||
|
if header:
|
||||||
|
seek(header)
|
||||||
|
file_info = {}
|
||||||
|
# read bmp header size @offset 14 (this is part of the header size)
|
||||||
|
file_info["header_size"] = i32(read(4))
|
||||||
|
file_info["direction"] = -1
|
||||||
|
|
||||||
|
# -------------------- If requested, read header at a specific position
|
||||||
|
# read the rest of the bmp header, without its size
|
||||||
|
header_data = ImageFile._safe_read(self.fp, file_info["header_size"] - 4)
|
||||||
|
|
||||||
|
# -------------------------------------------------- IBM OS/2 Bitmap v1
|
||||||
|
# ----- This format has different offsets because of width/height types
|
||||||
|
if file_info["header_size"] == 12:
|
||||||
|
file_info["width"] = i16(header_data[0:2])
|
||||||
|
file_info["height"] = i16(header_data[2:4])
|
||||||
|
file_info["planes"] = i16(header_data[4:6])
|
||||||
|
file_info["bits"] = i16(header_data[6:8])
|
||||||
|
file_info["compression"] = self.RAW
|
||||||
|
file_info["palette_padding"] = 3
|
||||||
|
|
||||||
|
# --------------------------------------------- Windows Bitmap v2 to v5
|
||||||
|
# v3, OS/2 v2, v4, v5
|
||||||
|
elif file_info["header_size"] in (40, 64, 108, 124):
|
||||||
|
file_info["y_flip"] = i8(header_data[7]) == 0xFF
|
||||||
|
file_info["direction"] = 1 if file_info["y_flip"] else -1
|
||||||
|
file_info["width"] = i32(header_data[0:4])
|
||||||
|
file_info["height"] = (
|
||||||
|
i32(header_data[4:8])
|
||||||
|
if not file_info["y_flip"]
|
||||||
|
else 2 ** 32 - i32(header_data[4:8])
|
||||||
|
)
|
||||||
|
file_info["planes"] = i16(header_data[8:10])
|
||||||
|
file_info["bits"] = i16(header_data[10:12])
|
||||||
|
file_info["compression"] = i32(header_data[12:16])
|
||||||
|
# byte size of pixel data
|
||||||
|
file_info["data_size"] = i32(header_data[16:20])
|
||||||
|
file_info["pixels_per_meter"] = (
|
||||||
|
i32(header_data[20:24]),
|
||||||
|
i32(header_data[24:28]),
|
||||||
|
)
|
||||||
|
file_info["colors"] = i32(header_data[28:32])
|
||||||
|
file_info["palette_padding"] = 4
|
||||||
|
self.info["dpi"] = tuple(
|
||||||
|
int(x / 39.3701 + 0.5) for x in file_info["pixels_per_meter"]
|
||||||
|
)
|
||||||
|
if file_info["compression"] == self.BITFIELDS:
|
||||||
|
if len(header_data) >= 52:
|
||||||
|
for idx, mask in enumerate(
|
||||||
|
["r_mask", "g_mask", "b_mask", "a_mask"]
|
||||||
|
):
|
||||||
|
file_info[mask] = i32(header_data[36 + idx * 4 : 40 + idx * 4])
|
||||||
|
else:
|
||||||
|
# 40 byte headers only have the three components in the
|
||||||
|
# bitfields masks, ref:
|
||||||
|
# https://msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85).aspx
|
||||||
|
# See also
|
||||||
|
# https://github.com/python-pillow/Pillow/issues/1293
|
||||||
|
# There is a 4th component in the RGBQuad, in the alpha
|
||||||
|
# location, but it is listed as a reserved component,
|
||||||
|
# and it is not generally an alpha channel
|
||||||
|
file_info["a_mask"] = 0x0
|
||||||
|
for mask in ["r_mask", "g_mask", "b_mask"]:
|
||||||
|
file_info[mask] = i32(read(4))
|
||||||
|
file_info["rgb_mask"] = (
|
||||||
|
file_info["r_mask"],
|
||||||
|
file_info["g_mask"],
|
||||||
|
file_info["b_mask"],
|
||||||
|
)
|
||||||
|
file_info["rgba_mask"] = (
|
||||||
|
file_info["r_mask"],
|
||||||
|
file_info["g_mask"],
|
||||||
|
file_info["b_mask"],
|
||||||
|
file_info["a_mask"],
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise OSError(f"Unsupported BMP header type ({file_info['header_size']})")
|
||||||
|
|
||||||
|
# ------------------ Special case : header is reported 40, which
|
||||||
|
# ---------------------- is shorter than real size for bpp >= 16
|
||||||
|
self._size = file_info["width"], file_info["height"]
|
||||||
|
|
||||||
|
# ------- If color count was not found in the header, compute from bits
|
||||||
|
file_info["colors"] = (
|
||||||
|
file_info["colors"]
|
||||||
|
if file_info.get("colors", 0)
|
||||||
|
else (1 << file_info["bits"])
|
||||||
|
)
|
||||||
|
|
||||||
|
# ---------------------- Check bit depth for unusual unsupported values
|
||||||
|
self.mode, raw_mode = BIT2MODE.get(file_info["bits"], (None, None))
|
||||||
|
if self.mode is None:
|
||||||
|
raise OSError(f"Unsupported BMP pixel depth ({file_info['bits']})")
|
||||||
|
|
||||||
|
# ---------------- Process BMP with Bitfields compression (not palette)
|
||||||
|
if file_info["compression"] == self.BITFIELDS:
|
||||||
|
SUPPORTED = {
|
||||||
|
32: [
|
||||||
|
(0xFF0000, 0xFF00, 0xFF, 0x0),
|
||||||
|
(0xFF0000, 0xFF00, 0xFF, 0xFF000000),
|
||||||
|
(0xFF, 0xFF00, 0xFF0000, 0xFF000000),
|
||||||
|
(0x0, 0x0, 0x0, 0x0),
|
||||||
|
(0xFF000000, 0xFF0000, 0xFF00, 0x0),
|
||||||
|
],
|
||||||
|
24: [(0xFF0000, 0xFF00, 0xFF)],
|
||||||
|
16: [(0xF800, 0x7E0, 0x1F), (0x7C00, 0x3E0, 0x1F)],
|
||||||
|
}
|
||||||
|
MASK_MODES = {
|
||||||
|
(32, (0xFF0000, 0xFF00, 0xFF, 0x0)): "BGRX",
|
||||||
|
(32, (0xFF000000, 0xFF0000, 0xFF00, 0x0)): "XBGR",
|
||||||
|
(32, (0xFF, 0xFF00, 0xFF0000, 0xFF000000)): "RGBA",
|
||||||
|
(32, (0xFF0000, 0xFF00, 0xFF, 0xFF000000)): "BGRA",
|
||||||
|
(32, (0x0, 0x0, 0x0, 0x0)): "BGRA",
|
||||||
|
(24, (0xFF0000, 0xFF00, 0xFF)): "BGR",
|
||||||
|
(16, (0xF800, 0x7E0, 0x1F)): "BGR;16",
|
||||||
|
(16, (0x7C00, 0x3E0, 0x1F)): "BGR;15",
|
||||||
|
}
|
||||||
|
if file_info["bits"] in SUPPORTED:
|
||||||
|
if (
|
||||||
|
file_info["bits"] == 32
|
||||||
|
and file_info["rgba_mask"] in SUPPORTED[file_info["bits"]]
|
||||||
|
):
|
||||||
|
raw_mode = MASK_MODES[(file_info["bits"], file_info["rgba_mask"])]
|
||||||
|
self.mode = "RGBA" if "A" in raw_mode else self.mode
|
||||||
|
elif (
|
||||||
|
file_info["bits"] in (24, 16)
|
||||||
|
and file_info["rgb_mask"] in SUPPORTED[file_info["bits"]]
|
||||||
|
):
|
||||||
|
raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])]
|
||||||
|
else:
|
||||||
|
raise OSError("Unsupported BMP bitfields layout")
|
||||||
|
else:
|
||||||
|
raise OSError("Unsupported BMP bitfields layout")
|
||||||
|
elif file_info["compression"] == self.RAW:
|
||||||
|
if file_info["bits"] == 32 and header == 22: # 32-bit .cur offset
|
||||||
|
raw_mode, self.mode = "BGRA", "RGBA"
|
||||||
|
else:
|
||||||
|
raise OSError(f"Unsupported BMP compression ({file_info['compression']})")
|
||||||
|
|
||||||
|
# --------------- Once the header is processed, process the palette/LUT
|
||||||
|
if self.mode == "P": # Paletted for 1, 4 and 8 bit images
|
||||||
|
|
||||||
|
# ---------------------------------------------------- 1-bit images
|
||||||
|
if not (0 < file_info["colors"] <= 65536):
|
||||||
|
raise OSError(f"Unsupported BMP Palette size ({file_info['colors']})")
|
||||||
|
else:
|
||||||
|
padding = file_info["palette_padding"]
|
||||||
|
palette = read(padding * file_info["colors"])
|
||||||
|
greyscale = True
|
||||||
|
indices = (
|
||||||
|
(0, 255)
|
||||||
|
if file_info["colors"] == 2
|
||||||
|
else list(range(file_info["colors"]))
|
||||||
|
)
|
||||||
|
|
||||||
|
# ----------------- Check if greyscale and ignore palette if so
|
||||||
|
for ind, val in enumerate(indices):
|
||||||
|
rgb = palette[ind * padding : ind * padding + 3]
|
||||||
|
if rgb != o8(val) * 3:
|
||||||
|
greyscale = False
|
||||||
|
|
||||||
|
# ------- If all colors are grey, white or black, ditch palette
|
||||||
|
if greyscale:
|
||||||
|
self.mode = "1" if file_info["colors"] == 2 else "L"
|
||||||
|
raw_mode = self.mode
|
||||||
|
else:
|
||||||
|
self.mode = "P"
|
||||||
|
self.palette = ImagePalette.raw(
|
||||||
|
"BGRX" if padding == 4 else "BGR", palette
|
||||||
|
)
|
||||||
|
|
||||||
|
# ---------------------------- Finally set the tile data for the plugin
|
||||||
|
self.info["compression"] = file_info["compression"]
|
||||||
|
self.tile = [
|
||||||
|
(
|
||||||
|
"raw",
|
||||||
|
(0, 0, file_info["width"], file_info["height"]),
|
||||||
|
offset or self.fp.tell(),
|
||||||
|
(
|
||||||
|
raw_mode,
|
||||||
|
((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3),
|
||||||
|
file_info["direction"],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
]
|
||||||
|
|
||||||
|
def _open(self):
|
||||||
|
""" Open file, check magic number and read header """
|
||||||
|
# read 14 bytes: magic number, filesize, reserved, header final offset
|
||||||
|
head_data = self.fp.read(14)
|
||||||
|
# choke if the file does not have the required magic bytes
|
||||||
|
if not _accept(head_data):
|
||||||
|
raise SyntaxError("Not a BMP file")
|
||||||
|
# read the start position of the BMP image data (u32)
|
||||||
|
offset = i32(head_data[10:14])
|
||||||
|
# load bitmap information (offset=raster info)
|
||||||
|
self._bitmap(offset=offset)
|
||||||
|
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# Image plugin for the DIB format (BMP alias)
|
||||||
|
# =============================================================================
|
||||||
|
class DibImageFile(BmpImageFile):
|
||||||
|
|
||||||
|
format = "DIB"
|
||||||
|
format_description = "Windows Bitmap"
|
||||||
|
|
||||||
|
def _open(self):
|
||||||
|
self._bitmap()
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# Write BMP file
|
||||||
|
|
||||||
|
|
||||||
|
SAVE = {
|
||||||
|
"1": ("1", 1, 2),
|
||||||
|
"L": ("L", 8, 256),
|
||||||
|
"P": ("P", 8, 256),
|
||||||
|
"RGB": ("BGR", 24, 0),
|
||||||
|
"RGBA": ("BGRA", 32, 0),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _dib_save(im, fp, filename):
|
||||||
|
_save(im, fp, filename, False)
|
||||||
|
|
||||||
|
|
||||||
|
def _save(im, fp, filename, bitmap_header=True):
|
||||||
|
try:
|
||||||
|
rawmode, bits, colors = SAVE[im.mode]
|
||||||
|
except KeyError as e:
|
||||||
|
raise OSError(f"cannot write mode {im.mode} as BMP") from e
|
||||||
|
|
||||||
|
info = im.encoderinfo
|
||||||
|
|
||||||
|
dpi = info.get("dpi", (96, 96))
|
||||||
|
|
||||||
|
# 1 meter == 39.3701 inches
|
||||||
|
ppm = tuple(map(lambda x: int(x * 39.3701 + 0.5), dpi))
|
||||||
|
|
||||||
|
stride = ((im.size[0] * bits + 7) // 8 + 3) & (~3)
|
||||||
|
header = 40 # or 64 for OS/2 version 2
|
||||||
|
image = stride * im.size[1]
|
||||||
|
|
||||||
|
# bitmap header
|
||||||
|
if bitmap_header:
|
||||||
|
offset = 14 + header + colors * 4
|
||||||
|
file_size = offset + image
|
||||||
|
if file_size > 2 ** 32 - 1:
|
||||||
|
raise ValueError("File size is too large for the BMP format")
|
||||||
|
fp.write(
|
||||||
|
b"BM" # file type (magic)
|
||||||
|
+ o32(file_size) # file size
|
||||||
|
+ o32(0) # reserved
|
||||||
|
+ o32(offset) # image data offset
|
||||||
|
)
|
||||||
|
|
||||||
|
# bitmap info header
|
||||||
|
fp.write(
|
||||||
|
o32(header) # info header size
|
||||||
|
+ o32(im.size[0]) # width
|
||||||
|
+ o32(im.size[1]) # height
|
||||||
|
+ o16(1) # planes
|
||||||
|
+ o16(bits) # depth
|
||||||
|
+ o32(0) # compression (0=uncompressed)
|
||||||
|
+ o32(image) # size of bitmap
|
||||||
|
+ o32(ppm[0]) # resolution
|
||||||
|
+ o32(ppm[1]) # resolution
|
||||||
|
+ o32(colors) # colors used
|
||||||
|
+ o32(colors) # colors important
|
||||||
|
)
|
||||||
|
|
||||||
|
fp.write(b"\0" * (header - 40)) # padding (for OS/2 format)
|
||||||
|
|
||||||
|
if im.mode == "1":
|
||||||
|
for i in (0, 255):
|
||||||
|
fp.write(o8(i) * 4)
|
||||||
|
elif im.mode == "L":
|
||||||
|
for i in range(256):
|
||||||
|
fp.write(o8(i) * 4)
|
||||||
|
elif im.mode == "P":
|
||||||
|
fp.write(im.im.getpalette("RGB", "BGRX"))
|
||||||
|
|
||||||
|
ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, stride, -1))])
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# Registry
|
||||||
|
|
||||||
|
|
||||||
|
Image.register_open(BmpImageFile.format, BmpImageFile, _accept)
|
||||||
|
Image.register_save(BmpImageFile.format, _save)
|
||||||
|
|
||||||
|
Image.register_extension(BmpImageFile.format, ".bmp")
|
||||||
|
|
||||||
|
Image.register_mime(BmpImageFile.format, "image/bmp")
|
||||||
|
|
||||||
|
Image.register_open(DibImageFile.format, DibImageFile, _dib_accept)
|
||||||
|
Image.register_save(DibImageFile.format, _dib_save)
|
||||||
|
|
||||||
|
Image.register_extension(DibImageFile.format, ".dib")
|
||||||
|
|
||||||
|
Image.register_mime(DibImageFile.format, "image/bmp")
|
||||||
73
venv/lib/python3.9/site-packages/PIL/BufrStubImagePlugin.py
Normal file
|
|
@ -0,0 +1,73 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# BUFR stub adapter
|
||||||
|
#
|
||||||
|
# Copyright (c) 1996-2003 by Fredrik Lundh
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
from . import Image, ImageFile
|
||||||
|
|
||||||
|
_handler = None
|
||||||
|
|
||||||
|
|
||||||
|
def register_handler(handler):
|
||||||
|
"""
|
||||||
|
Install application-specific BUFR image handler.
|
||||||
|
|
||||||
|
:param handler: Handler object.
|
||||||
|
"""
|
||||||
|
global _handler
|
||||||
|
_handler = handler
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# Image adapter
|
||||||
|
|
||||||
|
|
||||||
|
def _accept(prefix):
|
||||||
|
return prefix[:4] == b"BUFR" or prefix[:4] == b"ZCZC"
|
||||||
|
|
||||||
|
|
||||||
|
class BufrStubImageFile(ImageFile.StubImageFile):
|
||||||
|
|
||||||
|
format = "BUFR"
|
||||||
|
format_description = "BUFR"
|
||||||
|
|
||||||
|
def _open(self):
|
||||||
|
|
||||||
|
offset = self.fp.tell()
|
||||||
|
|
||||||
|
if not _accept(self.fp.read(4)):
|
||||||
|
raise SyntaxError("Not a BUFR file")
|
||||||
|
|
||||||
|
self.fp.seek(offset)
|
||||||
|
|
||||||
|
# make something up
|
||||||
|
self.mode = "F"
|
||||||
|
self._size = 1, 1
|
||||||
|
|
||||||
|
loader = self._load()
|
||||||
|
if loader:
|
||||||
|
loader.open(self)
|
||||||
|
|
||||||
|
def _load(self):
|
||||||
|
return _handler
|
||||||
|
|
||||||
|
|
||||||
|
def _save(im, fp, filename):
|
||||||
|
if _handler is None or not hasattr("_handler", "save"):
|
||||||
|
raise OSError("BUFR save handler not installed")
|
||||||
|
_handler.save(im, fp, filename)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# Registry
|
||||||
|
|
||||||
|
Image.register_open(BufrStubImageFile.format, BufrStubImageFile, _accept)
|
||||||
|
Image.register_save(BufrStubImageFile.format, _save)
|
||||||
|
|
||||||
|
Image.register_extension(BufrStubImageFile.format, ".bufr")
|
||||||
120
venv/lib/python3.9/site-packages/PIL/ContainerIO.py
Normal file
|
|
@ -0,0 +1,120 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library.
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# a class to read from a container file
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 1995-06-18 fl Created
|
||||||
|
# 1995-09-07 fl Added readline(), readlines()
|
||||||
|
#
|
||||||
|
# Copyright (c) 1997-2001 by Secret Labs AB
|
||||||
|
# Copyright (c) 1995 by Fredrik Lundh
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
class ContainerIO:
|
||||||
|
"""
|
||||||
|
A file object that provides read access to a part of an existing
|
||||||
|
file (for example a TAR file).
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, file, offset, length):
|
||||||
|
"""
|
||||||
|
Create file object.
|
||||||
|
|
||||||
|
:param file: Existing file.
|
||||||
|
:param offset: Start of region, in bytes.
|
||||||
|
:param length: Size of region, in bytes.
|
||||||
|
"""
|
||||||
|
self.fh = file
|
||||||
|
self.pos = 0
|
||||||
|
self.offset = offset
|
||||||
|
self.length = length
|
||||||
|
self.fh.seek(offset)
|
||||||
|
|
||||||
|
##
|
||||||
|
# Always false.
|
||||||
|
|
||||||
|
def isatty(self):
|
||||||
|
return False
|
||||||
|
|
||||||
|
def seek(self, offset, mode=io.SEEK_SET):
|
||||||
|
"""
|
||||||
|
Move file pointer.
|
||||||
|
|
||||||
|
:param offset: Offset in bytes.
|
||||||
|
:param mode: Starting position. Use 0 for beginning of region, 1
|
||||||
|
for current offset, and 2 for end of region. You cannot move
|
||||||
|
the pointer outside the defined region.
|
||||||
|
"""
|
||||||
|
if mode == 1:
|
||||||
|
self.pos = self.pos + offset
|
||||||
|
elif mode == 2:
|
||||||
|
self.pos = self.length + offset
|
||||||
|
else:
|
||||||
|
self.pos = offset
|
||||||
|
# clamp
|
||||||
|
self.pos = max(0, min(self.pos, self.length))
|
||||||
|
self.fh.seek(self.offset + self.pos)
|
||||||
|
|
||||||
|
def tell(self):
|
||||||
|
"""
|
||||||
|
Get current file pointer.
|
||||||
|
|
||||||
|
:returns: Offset from start of region, in bytes.
|
||||||
|
"""
|
||||||
|
return self.pos
|
||||||
|
|
||||||
|
def read(self, n=0):
|
||||||
|
"""
|
||||||
|
Read data.
|
||||||
|
|
||||||
|
:param n: Number of bytes to read. If omitted or zero,
|
||||||
|
read until end of region.
|
||||||
|
:returns: An 8-bit string.
|
||||||
|
"""
|
||||||
|
if n:
|
||||||
|
n = min(n, self.length - self.pos)
|
||||||
|
else:
|
||||||
|
n = self.length - self.pos
|
||||||
|
if not n: # EOF
|
||||||
|
return b"" if "b" in self.fh.mode else ""
|
||||||
|
self.pos = self.pos + n
|
||||||
|
return self.fh.read(n)
|
||||||
|
|
||||||
|
def readline(self):
|
||||||
|
"""
|
||||||
|
Read a line of text.
|
||||||
|
|
||||||
|
:returns: An 8-bit string.
|
||||||
|
"""
|
||||||
|
s = b"" if "b" in self.fh.mode else ""
|
||||||
|
newline_character = b"\n" if "b" in self.fh.mode else "\n"
|
||||||
|
while True:
|
||||||
|
c = self.read(1)
|
||||||
|
if not c:
|
||||||
|
break
|
||||||
|
s = s + c
|
||||||
|
if c == newline_character:
|
||||||
|
break
|
||||||
|
return s
|
||||||
|
|
||||||
|
def readlines(self):
|
||||||
|
"""
|
||||||
|
Read multiple lines of text.
|
||||||
|
|
||||||
|
:returns: A list of 8-bit strings.
|
||||||
|
"""
|
||||||
|
lines = []
|
||||||
|
while True:
|
||||||
|
s = self.readline()
|
||||||
|
if not s:
|
||||||
|
break
|
||||||
|
lines.append(s)
|
||||||
|
return lines
|
||||||
76
venv/lib/python3.9/site-packages/PIL/CurImagePlugin.py
Normal file
|
|
@ -0,0 +1,76 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library.
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# Windows Cursor support for PIL
|
||||||
|
#
|
||||||
|
# notes:
|
||||||
|
# uses BmpImagePlugin.py to read the bitmap data.
|
||||||
|
#
|
||||||
|
# history:
|
||||||
|
# 96-05-27 fl Created
|
||||||
|
#
|
||||||
|
# Copyright (c) Secret Labs AB 1997.
|
||||||
|
# Copyright (c) Fredrik Lundh 1996.
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
from . import BmpImagePlugin, Image
|
||||||
|
from ._binary import i8
|
||||||
|
from ._binary import i16le as i16
|
||||||
|
from ._binary import i32le as i32
|
||||||
|
|
||||||
|
#
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _accept(prefix):
|
||||||
|
return prefix[:4] == b"\0\0\2\0"
|
||||||
|
|
||||||
|
|
||||||
|
##
|
||||||
|
# Image plugin for Windows Cursor files.
|
||||||
|
|
||||||
|
|
||||||
|
class CurImageFile(BmpImagePlugin.BmpImageFile):
|
||||||
|
|
||||||
|
format = "CUR"
|
||||||
|
format_description = "Windows Cursor"
|
||||||
|
|
||||||
|
def _open(self):
|
||||||
|
|
||||||
|
offset = self.fp.tell()
|
||||||
|
|
||||||
|
# check magic
|
||||||
|
s = self.fp.read(6)
|
||||||
|
if not _accept(s):
|
||||||
|
raise SyntaxError("not a CUR file")
|
||||||
|
|
||||||
|
# pick the largest cursor in the file
|
||||||
|
m = b""
|
||||||
|
for i in range(i16(s[4:])):
|
||||||
|
s = self.fp.read(16)
|
||||||
|
if not m:
|
||||||
|
m = s
|
||||||
|
elif i8(s[0]) > i8(m[0]) and i8(s[1]) > i8(m[1]):
|
||||||
|
m = s
|
||||||
|
if not m:
|
||||||
|
raise TypeError("No cursors were found")
|
||||||
|
|
||||||
|
# load as bitmap
|
||||||
|
self._bitmap(i32(m[12:]) + offset)
|
||||||
|
|
||||||
|
# patch up the bitmap height
|
||||||
|
self._size = self.size[0], self.size[1] // 2
|
||||||
|
d, e, o, a = self.tile[0]
|
||||||
|
self.tile[0] = d, (0, 0) + self.size, o, a
|
||||||
|
|
||||||
|
return
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
|
||||||
|
Image.register_open(CurImageFile.format, CurImageFile, _accept)
|
||||||
|
|
||||||
|
Image.register_extension(CurImageFile.format, ".cur")
|
||||||
89
venv/lib/python3.9/site-packages/PIL/DcxImagePlugin.py
Normal file
|
|
@ -0,0 +1,89 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library.
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# DCX file handling
|
||||||
|
#
|
||||||
|
# DCX is a container file format defined by Intel, commonly used
|
||||||
|
# for fax applications. Each DCX file consists of a directory
|
||||||
|
# (a list of file offsets) followed by a set of (usually 1-bit)
|
||||||
|
# PCX files.
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 1995-09-09 fl Created
|
||||||
|
# 1996-03-20 fl Properly derived from PcxImageFile.
|
||||||
|
# 1998-07-15 fl Renamed offset attribute to avoid name clash
|
||||||
|
# 2002-07-30 fl Fixed file handling
|
||||||
|
#
|
||||||
|
# Copyright (c) 1997-98 by Secret Labs AB.
|
||||||
|
# Copyright (c) 1995-96 by Fredrik Lundh.
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
from . import Image
|
||||||
|
from ._binary import i32le as i32
|
||||||
|
from .PcxImagePlugin import PcxImageFile
|
||||||
|
|
||||||
|
MAGIC = 0x3ADE68B1 # QUIZ: what's this value, then?
|
||||||
|
|
||||||
|
|
||||||
|
def _accept(prefix):
|
||||||
|
return len(prefix) >= 4 and i32(prefix) == MAGIC
|
||||||
|
|
||||||
|
|
||||||
|
##
|
||||||
|
# Image plugin for the Intel DCX format.
|
||||||
|
|
||||||
|
|
||||||
|
class DcxImageFile(PcxImageFile):
|
||||||
|
|
||||||
|
format = "DCX"
|
||||||
|
format_description = "Intel DCX"
|
||||||
|
_close_exclusive_fp_after_loading = False
|
||||||
|
|
||||||
|
def _open(self):
|
||||||
|
|
||||||
|
# Header
|
||||||
|
s = self.fp.read(4)
|
||||||
|
if not _accept(s):
|
||||||
|
raise SyntaxError("not a DCX file")
|
||||||
|
|
||||||
|
# Component directory
|
||||||
|
self._offset = []
|
||||||
|
for i in range(1024):
|
||||||
|
offset = i32(self.fp.read(4))
|
||||||
|
if not offset:
|
||||||
|
break
|
||||||
|
self._offset.append(offset)
|
||||||
|
|
||||||
|
self.__fp = self.fp
|
||||||
|
self.frame = None
|
||||||
|
self.n_frames = len(self._offset)
|
||||||
|
self.is_animated = self.n_frames > 1
|
||||||
|
self.seek(0)
|
||||||
|
|
||||||
|
def seek(self, frame):
|
||||||
|
if not self._seek_check(frame):
|
||||||
|
return
|
||||||
|
self.frame = frame
|
||||||
|
self.fp = self.__fp
|
||||||
|
self.fp.seek(self._offset[frame])
|
||||||
|
PcxImageFile._open(self)
|
||||||
|
|
||||||
|
def tell(self):
|
||||||
|
return self.frame
|
||||||
|
|
||||||
|
def _close__fp(self):
|
||||||
|
try:
|
||||||
|
if self.__fp != self.fp:
|
||||||
|
self.__fp.close()
|
||||||
|
except AttributeError:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
self.__fp = None
|
||||||
|
|
||||||
|
|
||||||
|
Image.register_open(DcxImageFile.format, DcxImageFile, _accept)
|
||||||
|
|
||||||
|
Image.register_extension(DcxImageFile.format, ".dcx")
|
||||||
178
venv/lib/python3.9/site-packages/PIL/DdsImagePlugin.py
Normal file
|
|
@ -0,0 +1,178 @@
|
||||||
|
"""
|
||||||
|
A Pillow loader for .dds files (S3TC-compressed aka DXTC)
|
||||||
|
Jerome Leclanche <jerome@leclan.ch>
|
||||||
|
|
||||||
|
Documentation:
|
||||||
|
https://web.archive.org/web/20170802060935/http://oss.sgi.com/projects/ogl-sample/registry/EXT/texture_compression_s3tc.txt
|
||||||
|
|
||||||
|
The contents of this file are hereby released in the public domain (CC0)
|
||||||
|
Full text of the CC0 license:
|
||||||
|
https://creativecommons.org/publicdomain/zero/1.0/
|
||||||
|
"""
|
||||||
|
|
||||||
|
import struct
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
from . import Image, ImageFile
|
||||||
|
|
||||||
|
# Magic ("DDS ")
|
||||||
|
DDS_MAGIC = 0x20534444
|
||||||
|
|
||||||
|
# DDS flags
|
||||||
|
DDSD_CAPS = 0x1
|
||||||
|
DDSD_HEIGHT = 0x2
|
||||||
|
DDSD_WIDTH = 0x4
|
||||||
|
DDSD_PITCH = 0x8
|
||||||
|
DDSD_PIXELFORMAT = 0x1000
|
||||||
|
DDSD_MIPMAPCOUNT = 0x20000
|
||||||
|
DDSD_LINEARSIZE = 0x80000
|
||||||
|
DDSD_DEPTH = 0x800000
|
||||||
|
|
||||||
|
# DDS caps
|
||||||
|
DDSCAPS_COMPLEX = 0x8
|
||||||
|
DDSCAPS_TEXTURE = 0x1000
|
||||||
|
DDSCAPS_MIPMAP = 0x400000
|
||||||
|
|
||||||
|
DDSCAPS2_CUBEMAP = 0x200
|
||||||
|
DDSCAPS2_CUBEMAP_POSITIVEX = 0x400
|
||||||
|
DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800
|
||||||
|
DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000
|
||||||
|
DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000
|
||||||
|
DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000
|
||||||
|
DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000
|
||||||
|
DDSCAPS2_VOLUME = 0x200000
|
||||||
|
|
||||||
|
# Pixel Format
|
||||||
|
DDPF_ALPHAPIXELS = 0x1
|
||||||
|
DDPF_ALPHA = 0x2
|
||||||
|
DDPF_FOURCC = 0x4
|
||||||
|
DDPF_PALETTEINDEXED8 = 0x20
|
||||||
|
DDPF_RGB = 0x40
|
||||||
|
DDPF_LUMINANCE = 0x20000
|
||||||
|
|
||||||
|
|
||||||
|
# dds.h
|
||||||
|
|
||||||
|
DDS_FOURCC = DDPF_FOURCC
|
||||||
|
DDS_RGB = DDPF_RGB
|
||||||
|
DDS_RGBA = DDPF_RGB | DDPF_ALPHAPIXELS
|
||||||
|
DDS_LUMINANCE = DDPF_LUMINANCE
|
||||||
|
DDS_LUMINANCEA = DDPF_LUMINANCE | DDPF_ALPHAPIXELS
|
||||||
|
DDS_ALPHA = DDPF_ALPHA
|
||||||
|
DDS_PAL8 = DDPF_PALETTEINDEXED8
|
||||||
|
|
||||||
|
DDS_HEADER_FLAGS_TEXTURE = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT
|
||||||
|
DDS_HEADER_FLAGS_MIPMAP = DDSD_MIPMAPCOUNT
|
||||||
|
DDS_HEADER_FLAGS_VOLUME = DDSD_DEPTH
|
||||||
|
DDS_HEADER_FLAGS_PITCH = DDSD_PITCH
|
||||||
|
DDS_HEADER_FLAGS_LINEARSIZE = DDSD_LINEARSIZE
|
||||||
|
|
||||||
|
DDS_HEIGHT = DDSD_HEIGHT
|
||||||
|
DDS_WIDTH = DDSD_WIDTH
|
||||||
|
|
||||||
|
DDS_SURFACE_FLAGS_TEXTURE = DDSCAPS_TEXTURE
|
||||||
|
DDS_SURFACE_FLAGS_MIPMAP = DDSCAPS_COMPLEX | DDSCAPS_MIPMAP
|
||||||
|
DDS_SURFACE_FLAGS_CUBEMAP = DDSCAPS_COMPLEX
|
||||||
|
|
||||||
|
DDS_CUBEMAP_POSITIVEX = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX
|
||||||
|
DDS_CUBEMAP_NEGATIVEX = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX
|
||||||
|
DDS_CUBEMAP_POSITIVEY = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY
|
||||||
|
DDS_CUBEMAP_NEGATIVEY = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY
|
||||||
|
DDS_CUBEMAP_POSITIVEZ = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ
|
||||||
|
DDS_CUBEMAP_NEGATIVEZ = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ
|
||||||
|
|
||||||
|
|
||||||
|
# DXT1
|
||||||
|
DXT1_FOURCC = 0x31545844
|
||||||
|
|
||||||
|
# DXT3
|
||||||
|
DXT3_FOURCC = 0x33545844
|
||||||
|
|
||||||
|
# DXT5
|
||||||
|
DXT5_FOURCC = 0x35545844
|
||||||
|
|
||||||
|
|
||||||
|
# dxgiformat.h
|
||||||
|
|
||||||
|
DXGI_FORMAT_BC7_TYPELESS = 97
|
||||||
|
DXGI_FORMAT_BC7_UNORM = 98
|
||||||
|
DXGI_FORMAT_BC7_UNORM_SRGB = 99
|
||||||
|
|
||||||
|
|
||||||
|
class DdsImageFile(ImageFile.ImageFile):
|
||||||
|
format = "DDS"
|
||||||
|
format_description = "DirectDraw Surface"
|
||||||
|
|
||||||
|
def _open(self):
|
||||||
|
magic, header_size = struct.unpack("<II", self.fp.read(8))
|
||||||
|
if header_size != 124:
|
||||||
|
raise OSError(f"Unsupported header size {repr(header_size)}")
|
||||||
|
header_bytes = self.fp.read(header_size - 4)
|
||||||
|
if len(header_bytes) != 120:
|
||||||
|
raise OSError(f"Incomplete header: {len(header_bytes)} bytes")
|
||||||
|
header = BytesIO(header_bytes)
|
||||||
|
|
||||||
|
flags, height, width = struct.unpack("<3I", header.read(12))
|
||||||
|
self._size = (width, height)
|
||||||
|
self.mode = "RGBA"
|
||||||
|
|
||||||
|
pitch, depth, mipmaps = struct.unpack("<3I", header.read(12))
|
||||||
|
struct.unpack("<11I", header.read(44)) # reserved
|
||||||
|
|
||||||
|
# pixel format
|
||||||
|
pfsize, pfflags = struct.unpack("<2I", header.read(8))
|
||||||
|
fourcc = header.read(4)
|
||||||
|
(bitcount,) = struct.unpack("<I", header.read(4))
|
||||||
|
masks = struct.unpack("<4I", header.read(16))
|
||||||
|
if pfflags & 0x40:
|
||||||
|
# DDPF_RGB - Texture contains uncompressed RGB data
|
||||||
|
masks = {mask: ["R", "G", "B", "A"][i] for i, mask in enumerate(masks)}
|
||||||
|
rawmode = ""
|
||||||
|
if bitcount == 32:
|
||||||
|
rawmode += masks[0xFF000000]
|
||||||
|
rawmode += masks[0xFF0000] + masks[0xFF00] + masks[0xFF]
|
||||||
|
|
||||||
|
self.tile = [("raw", (0, 0) + self.size, 0, (rawmode, 0, 1))]
|
||||||
|
else:
|
||||||
|
data_start = header_size + 4
|
||||||
|
n = 0
|
||||||
|
if fourcc == b"DXT1":
|
||||||
|
self.pixel_format = "DXT1"
|
||||||
|
n = 1
|
||||||
|
elif fourcc == b"DXT3":
|
||||||
|
self.pixel_format = "DXT3"
|
||||||
|
n = 2
|
||||||
|
elif fourcc == b"DXT5":
|
||||||
|
self.pixel_format = "DXT5"
|
||||||
|
n = 3
|
||||||
|
elif fourcc == b"DX10":
|
||||||
|
data_start += 20
|
||||||
|
# ignoring flags which pertain to volume textures and cubemaps
|
||||||
|
dxt10 = BytesIO(self.fp.read(20))
|
||||||
|
dxgi_format, dimension = struct.unpack("<II", dxt10.read(8))
|
||||||
|
if dxgi_format in (DXGI_FORMAT_BC7_TYPELESS, DXGI_FORMAT_BC7_UNORM):
|
||||||
|
self.pixel_format = "BC7"
|
||||||
|
n = 7
|
||||||
|
elif dxgi_format == DXGI_FORMAT_BC7_UNORM_SRGB:
|
||||||
|
self.pixel_format = "BC7"
|
||||||
|
self.info["gamma"] = 1 / 2.2
|
||||||
|
n = 7
|
||||||
|
else:
|
||||||
|
raise NotImplementedError(
|
||||||
|
f"Unimplemented DXGI format {dxgi_format}"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise NotImplementedError(f"Unimplemented pixel format {repr(fourcc)}")
|
||||||
|
|
||||||
|
self.tile = [("bcn", (0, 0) + self.size, data_start, (n))]
|
||||||
|
|
||||||
|
def load_seek(self, pos):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _validate(prefix):
|
||||||
|
return prefix[:4] == b"DDS "
|
||||||
|
|
||||||
|
|
||||||
|
Image.register_open(DdsImageFile.format, DdsImageFile, _validate)
|
||||||
|
Image.register_extension(DdsImageFile.format, ".dds")
|
||||||
419
venv/lib/python3.9/site-packages/PIL/EpsImagePlugin.py
Normal file
|
|
@ -0,0 +1,419 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library.
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# EPS file handling
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 1995-09-01 fl Created (0.1)
|
||||||
|
# 1996-05-18 fl Don't choke on "atend" fields, Ghostscript interface (0.2)
|
||||||
|
# 1996-08-22 fl Don't choke on floating point BoundingBox values
|
||||||
|
# 1996-08-23 fl Handle files from Macintosh (0.3)
|
||||||
|
# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.4)
|
||||||
|
# 2003-09-07 fl Check gs.close status (from Federico Di Gregorio) (0.5)
|
||||||
|
# 2014-05-07 e Handling of EPS with binary preview and fixed resolution
|
||||||
|
# resizing
|
||||||
|
#
|
||||||
|
# Copyright (c) 1997-2003 by Secret Labs AB.
|
||||||
|
# Copyright (c) 1995-2003 by Fredrik Lundh
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
from . import Image, ImageFile
|
||||||
|
from ._binary import i32le as i32
|
||||||
|
|
||||||
|
#
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
|
||||||
|
split = re.compile(r"^%%([^:]*):[ \t]*(.*)[ \t]*$")
|
||||||
|
field = re.compile(r"^%[%!\w]([^:]*)[ \t]*$")
|
||||||
|
|
||||||
|
gs_windows_binary = None
|
||||||
|
if sys.platform.startswith("win"):
|
||||||
|
import shutil
|
||||||
|
|
||||||
|
for binary in ("gswin32c", "gswin64c", "gs"):
|
||||||
|
if shutil.which(binary) is not None:
|
||||||
|
gs_windows_binary = binary
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
gs_windows_binary = False
|
||||||
|
|
||||||
|
|
||||||
|
def has_ghostscript():
|
||||||
|
if gs_windows_binary:
|
||||||
|
return True
|
||||||
|
if not sys.platform.startswith("win"):
|
||||||
|
try:
|
||||||
|
subprocess.check_call(["gs", "--version"], stdout=subprocess.DEVNULL)
|
||||||
|
return True
|
||||||
|
except OSError:
|
||||||
|
# No Ghostscript
|
||||||
|
pass
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def Ghostscript(tile, size, fp, scale=1):
|
||||||
|
"""Render an image using Ghostscript"""
|
||||||
|
|
||||||
|
# Unpack decoder tile
|
||||||
|
decoder, tile, offset, data = tile[0]
|
||||||
|
length, bbox = data
|
||||||
|
|
||||||
|
# Hack to support hi-res rendering
|
||||||
|
scale = int(scale) or 1
|
||||||
|
# orig_size = size
|
||||||
|
# orig_bbox = bbox
|
||||||
|
size = (size[0] * scale, size[1] * scale)
|
||||||
|
# resolution is dependent on bbox and size
|
||||||
|
res = (
|
||||||
|
72.0 * size[0] / (bbox[2] - bbox[0]),
|
||||||
|
72.0 * size[1] / (bbox[3] - bbox[1]),
|
||||||
|
)
|
||||||
|
|
||||||
|
out_fd, outfile = tempfile.mkstemp()
|
||||||
|
os.close(out_fd)
|
||||||
|
|
||||||
|
infile_temp = None
|
||||||
|
if hasattr(fp, "name") and os.path.exists(fp.name):
|
||||||
|
infile = fp.name
|
||||||
|
else:
|
||||||
|
in_fd, infile_temp = tempfile.mkstemp()
|
||||||
|
os.close(in_fd)
|
||||||
|
infile = infile_temp
|
||||||
|
|
||||||
|
# Ignore length and offset!
|
||||||
|
# Ghostscript can read it
|
||||||
|
# Copy whole file to read in Ghostscript
|
||||||
|
with open(infile_temp, "wb") as f:
|
||||||
|
# fetch length of fp
|
||||||
|
fp.seek(0, io.SEEK_END)
|
||||||
|
fsize = fp.tell()
|
||||||
|
# ensure start position
|
||||||
|
# go back
|
||||||
|
fp.seek(0)
|
||||||
|
lengthfile = fsize
|
||||||
|
while lengthfile > 0:
|
||||||
|
s = fp.read(min(lengthfile, 100 * 1024))
|
||||||
|
if not s:
|
||||||
|
break
|
||||||
|
lengthfile -= len(s)
|
||||||
|
f.write(s)
|
||||||
|
|
||||||
|
# Build Ghostscript command
|
||||||
|
command = [
|
||||||
|
"gs",
|
||||||
|
"-q", # quiet mode
|
||||||
|
"-g%dx%d" % size, # set output geometry (pixels)
|
||||||
|
"-r%fx%f" % res, # set input DPI (dots per inch)
|
||||||
|
"-dBATCH", # exit after processing
|
||||||
|
"-dNOPAUSE", # don't pause between pages
|
||||||
|
"-dSAFER", # safe mode
|
||||||
|
"-sDEVICE=ppmraw", # ppm driver
|
||||||
|
f"-sOutputFile={outfile}", # output file
|
||||||
|
# adjust for image origin
|
||||||
|
"-c",
|
||||||
|
f"{-bbox[0]} {-bbox[1]} translate",
|
||||||
|
"-f",
|
||||||
|
infile, # input file
|
||||||
|
# showpage (see https://bugs.ghostscript.com/show_bug.cgi?id=698272)
|
||||||
|
"-c",
|
||||||
|
"showpage",
|
||||||
|
]
|
||||||
|
|
||||||
|
if gs_windows_binary is not None:
|
||||||
|
if not gs_windows_binary:
|
||||||
|
raise OSError("Unable to locate Ghostscript on paths")
|
||||||
|
command[0] = gs_windows_binary
|
||||||
|
|
||||||
|
# push data through Ghostscript
|
||||||
|
try:
|
||||||
|
startupinfo = None
|
||||||
|
if sys.platform.startswith("win"):
|
||||||
|
startupinfo = subprocess.STARTUPINFO()
|
||||||
|
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
|
||||||
|
subprocess.check_call(command, startupinfo=startupinfo)
|
||||||
|
out_im = Image.open(outfile)
|
||||||
|
out_im.load()
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
os.unlink(outfile)
|
||||||
|
if infile_temp:
|
||||||
|
os.unlink(infile_temp)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
im = out_im.im.copy()
|
||||||
|
out_im.close()
|
||||||
|
return im
|
||||||
|
|
||||||
|
|
||||||
|
class PSFile:
|
||||||
|
"""
|
||||||
|
Wrapper for bytesio object that treats either CR or LF as end of line.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, fp):
|
||||||
|
self.fp = fp
|
||||||
|
self.char = None
|
||||||
|
|
||||||
|
def seek(self, offset, whence=io.SEEK_SET):
|
||||||
|
self.char = None
|
||||||
|
self.fp.seek(offset, whence)
|
||||||
|
|
||||||
|
def readline(self):
|
||||||
|
s = self.char or b""
|
||||||
|
self.char = None
|
||||||
|
|
||||||
|
c = self.fp.read(1)
|
||||||
|
while c not in b"\r\n":
|
||||||
|
s = s + c
|
||||||
|
c = self.fp.read(1)
|
||||||
|
|
||||||
|
self.char = self.fp.read(1)
|
||||||
|
# line endings can be 1 or 2 of \r \n, in either order
|
||||||
|
if self.char in b"\r\n":
|
||||||
|
self.char = None
|
||||||
|
|
||||||
|
return s.decode("latin-1")
|
||||||
|
|
||||||
|
|
||||||
|
def _accept(prefix):
|
||||||
|
return prefix[:4] == b"%!PS" or (len(prefix) >= 4 and i32(prefix) == 0xC6D3D0C5)
|
||||||
|
|
||||||
|
|
||||||
|
##
|
||||||
|
# Image plugin for Encapsulated PostScript. This plugin supports only
|
||||||
|
# a few variants of this format.
|
||||||
|
|
||||||
|
|
||||||
|
class EpsImageFile(ImageFile.ImageFile):
|
||||||
|
"""EPS File Parser for the Python Imaging Library"""
|
||||||
|
|
||||||
|
format = "EPS"
|
||||||
|
format_description = "Encapsulated Postscript"
|
||||||
|
|
||||||
|
mode_map = {1: "L", 2: "LAB", 3: "RGB", 4: "CMYK"}
|
||||||
|
|
||||||
|
def _open(self):
|
||||||
|
(length, offset) = self._find_offset(self.fp)
|
||||||
|
|
||||||
|
# Rewrap the open file pointer in something that will
|
||||||
|
# convert line endings and decode to latin-1.
|
||||||
|
fp = PSFile(self.fp)
|
||||||
|
|
||||||
|
# go to offset - start of "%!PS"
|
||||||
|
fp.seek(offset)
|
||||||
|
|
||||||
|
box = None
|
||||||
|
|
||||||
|
self.mode = "RGB"
|
||||||
|
self._size = 1, 1 # FIXME: huh?
|
||||||
|
|
||||||
|
#
|
||||||
|
# Load EPS header
|
||||||
|
|
||||||
|
s_raw = fp.readline()
|
||||||
|
s = s_raw.strip("\r\n")
|
||||||
|
|
||||||
|
while s_raw:
|
||||||
|
if s:
|
||||||
|
if len(s) > 255:
|
||||||
|
raise SyntaxError("not an EPS file")
|
||||||
|
|
||||||
|
try:
|
||||||
|
m = split.match(s)
|
||||||
|
except re.error as e:
|
||||||
|
raise SyntaxError("not an EPS file") from e
|
||||||
|
|
||||||
|
if m:
|
||||||
|
k, v = m.group(1, 2)
|
||||||
|
self.info[k] = v
|
||||||
|
if k == "BoundingBox":
|
||||||
|
try:
|
||||||
|
# Note: The DSC spec says that BoundingBox
|
||||||
|
# fields should be integers, but some drivers
|
||||||
|
# put floating point values there anyway.
|
||||||
|
box = [int(float(i)) for i in v.split()]
|
||||||
|
self._size = box[2] - box[0], box[3] - box[1]
|
||||||
|
self.tile = [
|
||||||
|
("eps", (0, 0) + self.size, offset, (length, box))
|
||||||
|
]
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
else:
|
||||||
|
m = field.match(s)
|
||||||
|
if m:
|
||||||
|
k = m.group(1)
|
||||||
|
|
||||||
|
if k == "EndComments":
|
||||||
|
break
|
||||||
|
if k[:8] == "PS-Adobe":
|
||||||
|
self.info[k[:8]] = k[9:]
|
||||||
|
else:
|
||||||
|
self.info[k] = ""
|
||||||
|
elif s[0] == "%":
|
||||||
|
# handle non-DSC PostScript comments that some
|
||||||
|
# tools mistakenly put in the Comments section
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise OSError("bad EPS header")
|
||||||
|
|
||||||
|
s_raw = fp.readline()
|
||||||
|
s = s_raw.strip("\r\n")
|
||||||
|
|
||||||
|
if s and s[:1] != "%":
|
||||||
|
break
|
||||||
|
|
||||||
|
#
|
||||||
|
# Scan for an "ImageData" descriptor
|
||||||
|
|
||||||
|
while s[:1] == "%":
|
||||||
|
|
||||||
|
if len(s) > 255:
|
||||||
|
raise SyntaxError("not an EPS file")
|
||||||
|
|
||||||
|
if s[:11] == "%ImageData:":
|
||||||
|
# Encoded bitmapped image.
|
||||||
|
x, y, bi, mo = s[11:].split(None, 7)[:4]
|
||||||
|
|
||||||
|
if int(bi) != 8:
|
||||||
|
break
|
||||||
|
try:
|
||||||
|
self.mode = self.mode_map[int(mo)]
|
||||||
|
except ValueError:
|
||||||
|
break
|
||||||
|
|
||||||
|
self._size = int(x), int(y)
|
||||||
|
return
|
||||||
|
|
||||||
|
s = fp.readline().strip("\r\n")
|
||||||
|
if not s:
|
||||||
|
break
|
||||||
|
|
||||||
|
if not box:
|
||||||
|
raise OSError("cannot determine EPS bounding box")
|
||||||
|
|
||||||
|
def _find_offset(self, fp):
|
||||||
|
|
||||||
|
s = fp.read(160)
|
||||||
|
|
||||||
|
if s[:4] == b"%!PS":
|
||||||
|
# for HEAD without binary preview
|
||||||
|
fp.seek(0, io.SEEK_END)
|
||||||
|
length = fp.tell()
|
||||||
|
offset = 0
|
||||||
|
elif i32(s[0:4]) == 0xC6D3D0C5:
|
||||||
|
# FIX for: Some EPS file not handled correctly / issue #302
|
||||||
|
# EPS can contain binary data
|
||||||
|
# or start directly with latin coding
|
||||||
|
# more info see:
|
||||||
|
# https://web.archive.org/web/20160528181353/http://partners.adobe.com/public/developer/en/ps/5002.EPSF_Spec.pdf
|
||||||
|
offset = i32(s[4:8])
|
||||||
|
length = i32(s[8:12])
|
||||||
|
else:
|
||||||
|
raise SyntaxError("not an EPS file")
|
||||||
|
|
||||||
|
return (length, offset)
|
||||||
|
|
||||||
|
def load(self, scale=1):
|
||||||
|
# Load EPS via Ghostscript
|
||||||
|
if not self.tile:
|
||||||
|
return
|
||||||
|
self.im = Ghostscript(self.tile, self.size, self.fp, scale)
|
||||||
|
self.mode = self.im.mode
|
||||||
|
self._size = self.im.size
|
||||||
|
self.tile = []
|
||||||
|
|
||||||
|
def load_seek(self, *args, **kwargs):
|
||||||
|
# we can't incrementally load, so force ImageFile.parser to
|
||||||
|
# use our custom load method by defining this method.
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _save(im, fp, filename, eps=1):
|
||||||
|
"""EPS Writer for the Python Imaging Library."""
|
||||||
|
|
||||||
|
#
|
||||||
|
# make sure image data is available
|
||||||
|
im.load()
|
||||||
|
|
||||||
|
#
|
||||||
|
# determine PostScript image mode
|
||||||
|
if im.mode == "L":
|
||||||
|
operator = (8, 1, "image")
|
||||||
|
elif im.mode == "RGB":
|
||||||
|
operator = (8, 3, "false 3 colorimage")
|
||||||
|
elif im.mode == "CMYK":
|
||||||
|
operator = (8, 4, "false 4 colorimage")
|
||||||
|
else:
|
||||||
|
raise ValueError("image mode is not supported")
|
||||||
|
|
||||||
|
base_fp = fp
|
||||||
|
wrapped_fp = False
|
||||||
|
if fp != sys.stdout:
|
||||||
|
fp = io.TextIOWrapper(fp, encoding="latin-1")
|
||||||
|
wrapped_fp = True
|
||||||
|
|
||||||
|
try:
|
||||||
|
if eps:
|
||||||
|
#
|
||||||
|
# write EPS header
|
||||||
|
fp.write("%!PS-Adobe-3.0 EPSF-3.0\n")
|
||||||
|
fp.write("%%Creator: PIL 0.1 EpsEncode\n")
|
||||||
|
# fp.write("%%CreationDate: %s"...)
|
||||||
|
fp.write("%%%%BoundingBox: 0 0 %d %d\n" % im.size)
|
||||||
|
fp.write("%%Pages: 1\n")
|
||||||
|
fp.write("%%EndComments\n")
|
||||||
|
fp.write("%%Page: 1 1\n")
|
||||||
|
fp.write("%%ImageData: %d %d " % im.size)
|
||||||
|
fp.write('%d %d 0 1 1 "%s"\n' % operator)
|
||||||
|
|
||||||
|
#
|
||||||
|
# image header
|
||||||
|
fp.write("gsave\n")
|
||||||
|
fp.write("10 dict begin\n")
|
||||||
|
fp.write(f"/buf {im.size[0] * operator[1]} string def\n")
|
||||||
|
fp.write("%d %d scale\n" % im.size)
|
||||||
|
fp.write("%d %d 8\n" % im.size) # <= bits
|
||||||
|
fp.write(f"[{im.size[0]} 0 0 -{im.size[1]} 0 {im.size[1]}]\n")
|
||||||
|
fp.write("{ currentfile buf readhexstring pop } bind\n")
|
||||||
|
fp.write(operator[2] + "\n")
|
||||||
|
if hasattr(fp, "flush"):
|
||||||
|
fp.flush()
|
||||||
|
|
||||||
|
ImageFile._save(im, base_fp, [("eps", (0, 0) + im.size, 0, None)])
|
||||||
|
|
||||||
|
fp.write("\n%%%%EndBinary\n")
|
||||||
|
fp.write("grestore end\n")
|
||||||
|
if hasattr(fp, "flush"):
|
||||||
|
fp.flush()
|
||||||
|
finally:
|
||||||
|
if wrapped_fp:
|
||||||
|
fp.detach()
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
Image.register_open(EpsImageFile.format, EpsImageFile, _accept)
|
||||||
|
|
||||||
|
Image.register_save(EpsImageFile.format, _save)
|
||||||
|
|
||||||
|
Image.register_extensions(EpsImageFile.format, [".ps", ".eps"])
|
||||||
|
|
||||||
|
Image.register_mime(EpsImageFile.format, "application/postscript")
|
||||||
318
venv/lib/python3.9/site-packages/PIL/ExifTags.py
Normal file
|
|
@ -0,0 +1,318 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library.
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# EXIF tags
|
||||||
|
#
|
||||||
|
# Copyright (c) 2003 by Secret Labs AB
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
"""
|
||||||
|
This module provides constants and clear-text names for various
|
||||||
|
well-known EXIF tags.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
TAGS = {
|
||||||
|
# possibly incomplete
|
||||||
|
0x000B: "ProcessingSoftware",
|
||||||
|
0x00FE: "NewSubfileType",
|
||||||
|
0x00FF: "SubfileType",
|
||||||
|
0x0100: "ImageWidth",
|
||||||
|
0x0101: "ImageLength",
|
||||||
|
0x0102: "BitsPerSample",
|
||||||
|
0x0103: "Compression",
|
||||||
|
0x0106: "PhotometricInterpretation",
|
||||||
|
0x0107: "Thresholding",
|
||||||
|
0x0108: "CellWidth",
|
||||||
|
0x0109: "CellLength",
|
||||||
|
0x010A: "FillOrder",
|
||||||
|
0x010D: "DocumentName",
|
||||||
|
0x010E: "ImageDescription",
|
||||||
|
0x010F: "Make",
|
||||||
|
0x0110: "Model",
|
||||||
|
0x0111: "StripOffsets",
|
||||||
|
0x0112: "Orientation",
|
||||||
|
0x0115: "SamplesPerPixel",
|
||||||
|
0x0116: "RowsPerStrip",
|
||||||
|
0x0117: "StripByteCounts",
|
||||||
|
0x0118: "MinSampleValue",
|
||||||
|
0x0119: "MaxSampleValue",
|
||||||
|
0x011A: "XResolution",
|
||||||
|
0x011B: "YResolution",
|
||||||
|
0x011C: "PlanarConfiguration",
|
||||||
|
0x011D: "PageName",
|
||||||
|
0x0120: "FreeOffsets",
|
||||||
|
0x0121: "FreeByteCounts",
|
||||||
|
0x0122: "GrayResponseUnit",
|
||||||
|
0x0123: "GrayResponseCurve",
|
||||||
|
0x0124: "T4Options",
|
||||||
|
0x0125: "T6Options",
|
||||||
|
0x0128: "ResolutionUnit",
|
||||||
|
0x0129: "PageNumber",
|
||||||
|
0x012D: "TransferFunction",
|
||||||
|
0x0131: "Software",
|
||||||
|
0x0132: "DateTime",
|
||||||
|
0x013B: "Artist",
|
||||||
|
0x013C: "HostComputer",
|
||||||
|
0x013D: "Predictor",
|
||||||
|
0x013E: "WhitePoint",
|
||||||
|
0x013F: "PrimaryChromaticities",
|
||||||
|
0x0140: "ColorMap",
|
||||||
|
0x0141: "HalftoneHints",
|
||||||
|
0x0142: "TileWidth",
|
||||||
|
0x0143: "TileLength",
|
||||||
|
0x0144: "TileOffsets",
|
||||||
|
0x0145: "TileByteCounts",
|
||||||
|
0x014A: "SubIFDs",
|
||||||
|
0x014C: "InkSet",
|
||||||
|
0x014D: "InkNames",
|
||||||
|
0x014E: "NumberOfInks",
|
||||||
|
0x0150: "DotRange",
|
||||||
|
0x0151: "TargetPrinter",
|
||||||
|
0x0152: "ExtraSamples",
|
||||||
|
0x0153: "SampleFormat",
|
||||||
|
0x0154: "SMinSampleValue",
|
||||||
|
0x0155: "SMaxSampleValue",
|
||||||
|
0x0156: "TransferRange",
|
||||||
|
0x0157: "ClipPath",
|
||||||
|
0x0158: "XClipPathUnits",
|
||||||
|
0x0159: "YClipPathUnits",
|
||||||
|
0x015A: "Indexed",
|
||||||
|
0x015B: "JPEGTables",
|
||||||
|
0x015F: "OPIProxy",
|
||||||
|
0x0200: "JPEGProc",
|
||||||
|
0x0201: "JpegIFOffset",
|
||||||
|
0x0202: "JpegIFByteCount",
|
||||||
|
0x0203: "JpegRestartInterval",
|
||||||
|
0x0205: "JpegLosslessPredictors",
|
||||||
|
0x0206: "JpegPointTransforms",
|
||||||
|
0x0207: "JpegQTables",
|
||||||
|
0x0208: "JpegDCTables",
|
||||||
|
0x0209: "JpegACTables",
|
||||||
|
0x0211: "YCbCrCoefficients",
|
||||||
|
0x0212: "YCbCrSubSampling",
|
||||||
|
0x0213: "YCbCrPositioning",
|
||||||
|
0x0214: "ReferenceBlackWhite",
|
||||||
|
0x02BC: "XMLPacket",
|
||||||
|
0x1000: "RelatedImageFileFormat",
|
||||||
|
0x1001: "RelatedImageWidth",
|
||||||
|
0x1002: "RelatedImageLength",
|
||||||
|
0x4746: "Rating",
|
||||||
|
0x4749: "RatingPercent",
|
||||||
|
0x800D: "ImageID",
|
||||||
|
0x828D: "CFARepeatPatternDim",
|
||||||
|
0x828E: "CFAPattern",
|
||||||
|
0x828F: "BatteryLevel",
|
||||||
|
0x8298: "Copyright",
|
||||||
|
0x829A: "ExposureTime",
|
||||||
|
0x829D: "FNumber",
|
||||||
|
0x83BB: "IPTCNAA",
|
||||||
|
0x8649: "ImageResources",
|
||||||
|
0x8769: "ExifOffset",
|
||||||
|
0x8773: "InterColorProfile",
|
||||||
|
0x8822: "ExposureProgram",
|
||||||
|
0x8824: "SpectralSensitivity",
|
||||||
|
0x8825: "GPSInfo",
|
||||||
|
0x8827: "ISOSpeedRatings",
|
||||||
|
0x8828: "OECF",
|
||||||
|
0x8829: "Interlace",
|
||||||
|
0x882A: "TimeZoneOffset",
|
||||||
|
0x882B: "SelfTimerMode",
|
||||||
|
0x9000: "ExifVersion",
|
||||||
|
0x9003: "DateTimeOriginal",
|
||||||
|
0x9004: "DateTimeDigitized",
|
||||||
|
0x9101: "ComponentsConfiguration",
|
||||||
|
0x9102: "CompressedBitsPerPixel",
|
||||||
|
0x9201: "ShutterSpeedValue",
|
||||||
|
0x9202: "ApertureValue",
|
||||||
|
0x9203: "BrightnessValue",
|
||||||
|
0x9204: "ExposureBiasValue",
|
||||||
|
0x9205: "MaxApertureValue",
|
||||||
|
0x9206: "SubjectDistance",
|
||||||
|
0x9207: "MeteringMode",
|
||||||
|
0x9208: "LightSource",
|
||||||
|
0x9209: "Flash",
|
||||||
|
0x920A: "FocalLength",
|
||||||
|
0x920B: "FlashEnergy",
|
||||||
|
0x920C: "SpatialFrequencyResponse",
|
||||||
|
0x920D: "Noise",
|
||||||
|
0x9211: "ImageNumber",
|
||||||
|
0x9212: "SecurityClassification",
|
||||||
|
0x9213: "ImageHistory",
|
||||||
|
0x9214: "SubjectLocation",
|
||||||
|
0x9215: "ExposureIndex",
|
||||||
|
0x9216: "TIFF/EPStandardID",
|
||||||
|
0x927C: "MakerNote",
|
||||||
|
0x9286: "UserComment",
|
||||||
|
0x9290: "SubsecTime",
|
||||||
|
0x9291: "SubsecTimeOriginal",
|
||||||
|
0x9292: "SubsecTimeDigitized",
|
||||||
|
0x9400: "AmbientTemperature",
|
||||||
|
0x9401: "Humidity",
|
||||||
|
0x9402: "Pressure",
|
||||||
|
0x9403: "WaterDepth",
|
||||||
|
0x9404: "Acceleration",
|
||||||
|
0x9405: "CameraElevationAngle",
|
||||||
|
0x9C9B: "XPTitle",
|
||||||
|
0x9C9C: "XPComment",
|
||||||
|
0x9C9D: "XPAuthor",
|
||||||
|
0x9C9E: "XPKeywords",
|
||||||
|
0x9C9F: "XPSubject",
|
||||||
|
0xA000: "FlashPixVersion",
|
||||||
|
0xA001: "ColorSpace",
|
||||||
|
0xA002: "ExifImageWidth",
|
||||||
|
0xA003: "ExifImageHeight",
|
||||||
|
0xA004: "RelatedSoundFile",
|
||||||
|
0xA005: "ExifInteroperabilityOffset",
|
||||||
|
0xA20B: "FlashEnergy",
|
||||||
|
0xA20C: "SpatialFrequencyResponse",
|
||||||
|
0xA20E: "FocalPlaneXResolution",
|
||||||
|
0xA20F: "FocalPlaneYResolution",
|
||||||
|
0xA210: "FocalPlaneResolutionUnit",
|
||||||
|
0xA214: "SubjectLocation",
|
||||||
|
0xA215: "ExposureIndex",
|
||||||
|
0xA217: "SensingMethod",
|
||||||
|
0xA300: "FileSource",
|
||||||
|
0xA301: "SceneType",
|
||||||
|
0xA302: "CFAPattern",
|
||||||
|
0xA401: "CustomRendered",
|
||||||
|
0xA402: "ExposureMode",
|
||||||
|
0xA403: "WhiteBalance",
|
||||||
|
0xA404: "DigitalZoomRatio",
|
||||||
|
0xA405: "FocalLengthIn35mmFilm",
|
||||||
|
0xA406: "SceneCaptureType",
|
||||||
|
0xA407: "GainControl",
|
||||||
|
0xA408: "Contrast",
|
||||||
|
0xA409: "Saturation",
|
||||||
|
0xA40A: "Sharpness",
|
||||||
|
0xA40B: "DeviceSettingDescription",
|
||||||
|
0xA40C: "SubjectDistanceRange",
|
||||||
|
0xA420: "ImageUniqueID",
|
||||||
|
0xA430: "CameraOwnerName",
|
||||||
|
0xA431: "BodySerialNumber",
|
||||||
|
0xA432: "LensSpecification",
|
||||||
|
0xA433: "LensMake",
|
||||||
|
0xA434: "LensModel",
|
||||||
|
0xA435: "LensSerialNumber",
|
||||||
|
0xA500: "Gamma",
|
||||||
|
0xC4A5: "PrintImageMatching",
|
||||||
|
0xC612: "DNGVersion",
|
||||||
|
0xC613: "DNGBackwardVersion",
|
||||||
|
0xC614: "UniqueCameraModel",
|
||||||
|
0xC615: "LocalizedCameraModel",
|
||||||
|
0xC616: "CFAPlaneColor",
|
||||||
|
0xC617: "CFALayout",
|
||||||
|
0xC618: "LinearizationTable",
|
||||||
|
0xC619: "BlackLevelRepeatDim",
|
||||||
|
0xC61A: "BlackLevel",
|
||||||
|
0xC61B: "BlackLevelDeltaH",
|
||||||
|
0xC61C: "BlackLevelDeltaV",
|
||||||
|
0xC61D: "WhiteLevel",
|
||||||
|
0xC61E: "DefaultScale",
|
||||||
|
0xC61F: "DefaultCropOrigin",
|
||||||
|
0xC620: "DefaultCropSize",
|
||||||
|
0xC621: "ColorMatrix1",
|
||||||
|
0xC622: "ColorMatrix2",
|
||||||
|
0xC623: "CameraCalibration1",
|
||||||
|
0xC624: "CameraCalibration2",
|
||||||
|
0xC625: "ReductionMatrix1",
|
||||||
|
0xC626: "ReductionMatrix2",
|
||||||
|
0xC627: "AnalogBalance",
|
||||||
|
0xC628: "AsShotNeutral",
|
||||||
|
0xC629: "AsShotWhiteXY",
|
||||||
|
0xC62A: "BaselineExposure",
|
||||||
|
0xC62B: "BaselineNoise",
|
||||||
|
0xC62C: "BaselineSharpness",
|
||||||
|
0xC62D: "BayerGreenSplit",
|
||||||
|
0xC62E: "LinearResponseLimit",
|
||||||
|
0xC62F: "CameraSerialNumber",
|
||||||
|
0xC630: "LensInfo",
|
||||||
|
0xC631: "ChromaBlurRadius",
|
||||||
|
0xC632: "AntiAliasStrength",
|
||||||
|
0xC633: "ShadowScale",
|
||||||
|
0xC634: "DNGPrivateData",
|
||||||
|
0xC635: "MakerNoteSafety",
|
||||||
|
0xC65A: "CalibrationIlluminant1",
|
||||||
|
0xC65B: "CalibrationIlluminant2",
|
||||||
|
0xC65C: "BestQualityScale",
|
||||||
|
0xC65D: "RawDataUniqueID",
|
||||||
|
0xC68B: "OriginalRawFileName",
|
||||||
|
0xC68C: "OriginalRawFileData",
|
||||||
|
0xC68D: "ActiveArea",
|
||||||
|
0xC68E: "MaskedAreas",
|
||||||
|
0xC68F: "AsShotICCProfile",
|
||||||
|
0xC690: "AsShotPreProfileMatrix",
|
||||||
|
0xC691: "CurrentICCProfile",
|
||||||
|
0xC692: "CurrentPreProfileMatrix",
|
||||||
|
0xC6BF: "ColorimetricReference",
|
||||||
|
0xC6F3: "CameraCalibrationSignature",
|
||||||
|
0xC6F4: "ProfileCalibrationSignature",
|
||||||
|
0xC6F6: "AsShotProfileName",
|
||||||
|
0xC6F7: "NoiseReductionApplied",
|
||||||
|
0xC6F8: "ProfileName",
|
||||||
|
0xC6F9: "ProfileHueSatMapDims",
|
||||||
|
0xC6FA: "ProfileHueSatMapData1",
|
||||||
|
0xC6FB: "ProfileHueSatMapData2",
|
||||||
|
0xC6FC: "ProfileToneCurve",
|
||||||
|
0xC6FD: "ProfileEmbedPolicy",
|
||||||
|
0xC6FE: "ProfileCopyright",
|
||||||
|
0xC714: "ForwardMatrix1",
|
||||||
|
0xC715: "ForwardMatrix2",
|
||||||
|
0xC716: "PreviewApplicationName",
|
||||||
|
0xC717: "PreviewApplicationVersion",
|
||||||
|
0xC718: "PreviewSettingsName",
|
||||||
|
0xC719: "PreviewSettingsDigest",
|
||||||
|
0xC71A: "PreviewColorSpace",
|
||||||
|
0xC71B: "PreviewDateTime",
|
||||||
|
0xC71C: "RawImageDigest",
|
||||||
|
0xC71D: "OriginalRawFileDigest",
|
||||||
|
0xC71E: "SubTileBlockSize",
|
||||||
|
0xC71F: "RowInterleaveFactor",
|
||||||
|
0xC725: "ProfileLookTableDims",
|
||||||
|
0xC726: "ProfileLookTableData",
|
||||||
|
0xC740: "OpcodeList1",
|
||||||
|
0xC741: "OpcodeList2",
|
||||||
|
0xC74E: "OpcodeList3",
|
||||||
|
0xC761: "NoiseProfile",
|
||||||
|
}
|
||||||
|
"""Maps EXIF tags to tag names."""
|
||||||
|
|
||||||
|
|
||||||
|
GPSTAGS = {
|
||||||
|
0: "GPSVersionID",
|
||||||
|
1: "GPSLatitudeRef",
|
||||||
|
2: "GPSLatitude",
|
||||||
|
3: "GPSLongitudeRef",
|
||||||
|
4: "GPSLongitude",
|
||||||
|
5: "GPSAltitudeRef",
|
||||||
|
6: "GPSAltitude",
|
||||||
|
7: "GPSTimeStamp",
|
||||||
|
8: "GPSSatellites",
|
||||||
|
9: "GPSStatus",
|
||||||
|
10: "GPSMeasureMode",
|
||||||
|
11: "GPSDOP",
|
||||||
|
12: "GPSSpeedRef",
|
||||||
|
13: "GPSSpeed",
|
||||||
|
14: "GPSTrackRef",
|
||||||
|
15: "GPSTrack",
|
||||||
|
16: "GPSImgDirectionRef",
|
||||||
|
17: "GPSImgDirection",
|
||||||
|
18: "GPSMapDatum",
|
||||||
|
19: "GPSDestLatitudeRef",
|
||||||
|
20: "GPSDestLatitude",
|
||||||
|
21: "GPSDestLongitudeRef",
|
||||||
|
22: "GPSDestLongitude",
|
||||||
|
23: "GPSDestBearingRef",
|
||||||
|
24: "GPSDestBearing",
|
||||||
|
25: "GPSDestDistanceRef",
|
||||||
|
26: "GPSDestDistance",
|
||||||
|
27: "GPSProcessingMethod",
|
||||||
|
28: "GPSAreaInformation",
|
||||||
|
29: "GPSDateStamp",
|
||||||
|
30: "GPSDifferential",
|
||||||
|
31: "GPSHPositioningError",
|
||||||
|
}
|
||||||
|
"""Maps EXIF GPS tags to tag names."""
|
||||||
76
venv/lib/python3.9/site-packages/PIL/FitsStubImagePlugin.py
Normal file
|
|
@ -0,0 +1,76 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# FITS stub adapter
|
||||||
|
#
|
||||||
|
# Copyright (c) 1998-2003 by Fredrik Lundh
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
from . import Image, ImageFile
|
||||||
|
|
||||||
|
_handler = None
|
||||||
|
|
||||||
|
|
||||||
|
def register_handler(handler):
|
||||||
|
"""
|
||||||
|
Install application-specific FITS image handler.
|
||||||
|
|
||||||
|
:param handler: Handler object.
|
||||||
|
"""
|
||||||
|
global _handler
|
||||||
|
_handler = handler
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# Image adapter
|
||||||
|
|
||||||
|
|
||||||
|
def _accept(prefix):
|
||||||
|
return prefix[:6] == b"SIMPLE"
|
||||||
|
|
||||||
|
|
||||||
|
class FITSStubImageFile(ImageFile.StubImageFile):
|
||||||
|
|
||||||
|
format = "FITS"
|
||||||
|
format_description = "FITS"
|
||||||
|
|
||||||
|
def _open(self):
|
||||||
|
|
||||||
|
offset = self.fp.tell()
|
||||||
|
|
||||||
|
if not _accept(self.fp.read(6)):
|
||||||
|
raise SyntaxError("Not a FITS file")
|
||||||
|
|
||||||
|
# FIXME: add more sanity checks here; mandatory header items
|
||||||
|
# include SIMPLE, BITPIX, NAXIS, etc.
|
||||||
|
|
||||||
|
self.fp.seek(offset)
|
||||||
|
|
||||||
|
# make something up
|
||||||
|
self.mode = "F"
|
||||||
|
self._size = 1, 1
|
||||||
|
|
||||||
|
loader = self._load()
|
||||||
|
if loader:
|
||||||
|
loader.open(self)
|
||||||
|
|
||||||
|
def _load(self):
|
||||||
|
return _handler
|
||||||
|
|
||||||
|
|
||||||
|
def _save(im, fp, filename):
|
||||||
|
if _handler is None or not hasattr("_handler", "save"):
|
||||||
|
raise OSError("FITS save handler not installed")
|
||||||
|
_handler.save(im, fp, filename)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# Registry
|
||||||
|
|
||||||
|
Image.register_open(FITSStubImageFile.format, FITSStubImageFile, _accept)
|
||||||
|
Image.register_save(FITSStubImageFile.format, _save)
|
||||||
|
|
||||||
|
Image.register_extensions(FITSStubImageFile.format, [".fit", ".fits"])
|
||||||
172
venv/lib/python3.9/site-packages/PIL/FliImagePlugin.py
Normal file
|
|
@ -0,0 +1,172 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library.
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# FLI/FLC file handling.
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 95-09-01 fl Created
|
||||||
|
# 97-01-03 fl Fixed parser, setup decoder tile
|
||||||
|
# 98-07-15 fl Renamed offset attribute to avoid name clash
|
||||||
|
#
|
||||||
|
# Copyright (c) Secret Labs AB 1997-98.
|
||||||
|
# Copyright (c) Fredrik Lundh 1995-97.
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
|
||||||
|
from . import Image, ImageFile, ImagePalette
|
||||||
|
from ._binary import i8
|
||||||
|
from ._binary import i16le as i16
|
||||||
|
from ._binary import i32le as i32
|
||||||
|
from ._binary import o8
|
||||||
|
|
||||||
|
#
|
||||||
|
# decoder
|
||||||
|
|
||||||
|
|
||||||
|
def _accept(prefix):
|
||||||
|
return len(prefix) >= 6 and i16(prefix[4:6]) in [0xAF11, 0xAF12]
|
||||||
|
|
||||||
|
|
||||||
|
##
|
||||||
|
# Image plugin for the FLI/FLC animation format. Use the <b>seek</b>
|
||||||
|
# method to load individual frames.
|
||||||
|
|
||||||
|
|
||||||
|
class FliImageFile(ImageFile.ImageFile):
|
||||||
|
|
||||||
|
format = "FLI"
|
||||||
|
format_description = "Autodesk FLI/FLC Animation"
|
||||||
|
_close_exclusive_fp_after_loading = False
|
||||||
|
|
||||||
|
def _open(self):
|
||||||
|
|
||||||
|
# HEAD
|
||||||
|
s = self.fp.read(128)
|
||||||
|
if not (
|
||||||
|
_accept(s)
|
||||||
|
and i16(s[14:16]) in [0, 3] # flags
|
||||||
|
and s[20:22] == b"\x00\x00" # reserved
|
||||||
|
):
|
||||||
|
raise SyntaxError("not an FLI/FLC file")
|
||||||
|
|
||||||
|
# frames
|
||||||
|
self.n_frames = i16(s[6:8])
|
||||||
|
self.is_animated = self.n_frames > 1
|
||||||
|
|
||||||
|
# image characteristics
|
||||||
|
self.mode = "P"
|
||||||
|
self._size = i16(s[8:10]), i16(s[10:12])
|
||||||
|
|
||||||
|
# animation speed
|
||||||
|
duration = i32(s[16:20])
|
||||||
|
magic = i16(s[4:6])
|
||||||
|
if magic == 0xAF11:
|
||||||
|
duration = (duration * 1000) // 70
|
||||||
|
self.info["duration"] = duration
|
||||||
|
|
||||||
|
# look for palette
|
||||||
|
palette = [(a, a, a) for a in range(256)]
|
||||||
|
|
||||||
|
s = self.fp.read(16)
|
||||||
|
|
||||||
|
self.__offset = 128
|
||||||
|
|
||||||
|
if i16(s[4:6]) == 0xF100:
|
||||||
|
# prefix chunk; ignore it
|
||||||
|
self.__offset = self.__offset + i32(s)
|
||||||
|
s = self.fp.read(16)
|
||||||
|
|
||||||
|
if i16(s[4:6]) == 0xF1FA:
|
||||||
|
# look for palette chunk
|
||||||
|
s = self.fp.read(6)
|
||||||
|
if i16(s[4:6]) == 11:
|
||||||
|
self._palette(palette, 2)
|
||||||
|
elif i16(s[4:6]) == 4:
|
||||||
|
self._palette(palette, 0)
|
||||||
|
|
||||||
|
palette = [o8(r) + o8(g) + o8(b) for (r, g, b) in palette]
|
||||||
|
self.palette = ImagePalette.raw("RGB", b"".join(palette))
|
||||||
|
|
||||||
|
# set things up to decode first frame
|
||||||
|
self.__frame = -1
|
||||||
|
self.__fp = self.fp
|
||||||
|
self.__rewind = self.fp.tell()
|
||||||
|
self.seek(0)
|
||||||
|
|
||||||
|
def _palette(self, palette, shift):
|
||||||
|
# load palette
|
||||||
|
|
||||||
|
i = 0
|
||||||
|
for e in range(i16(self.fp.read(2))):
|
||||||
|
s = self.fp.read(2)
|
||||||
|
i = i + i8(s[0])
|
||||||
|
n = i8(s[1])
|
||||||
|
if n == 0:
|
||||||
|
n = 256
|
||||||
|
s = self.fp.read(n * 3)
|
||||||
|
for n in range(0, len(s), 3):
|
||||||
|
r = i8(s[n]) << shift
|
||||||
|
g = i8(s[n + 1]) << shift
|
||||||
|
b = i8(s[n + 2]) << shift
|
||||||
|
palette[i] = (r, g, b)
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
def seek(self, frame):
|
||||||
|
if not self._seek_check(frame):
|
||||||
|
return
|
||||||
|
if frame < self.__frame:
|
||||||
|
self._seek(0)
|
||||||
|
|
||||||
|
for f in range(self.__frame + 1, frame + 1):
|
||||||
|
self._seek(f)
|
||||||
|
|
||||||
|
def _seek(self, frame):
|
||||||
|
if frame == 0:
|
||||||
|
self.__frame = -1
|
||||||
|
self.__fp.seek(self.__rewind)
|
||||||
|
self.__offset = 128
|
||||||
|
else:
|
||||||
|
# ensure that the previous frame was loaded
|
||||||
|
self.load()
|
||||||
|
|
||||||
|
if frame != self.__frame + 1:
|
||||||
|
raise ValueError(f"cannot seek to frame {frame}")
|
||||||
|
self.__frame = frame
|
||||||
|
|
||||||
|
# move to next frame
|
||||||
|
self.fp = self.__fp
|
||||||
|
self.fp.seek(self.__offset)
|
||||||
|
|
||||||
|
s = self.fp.read(4)
|
||||||
|
if not s:
|
||||||
|
raise EOFError
|
||||||
|
|
||||||
|
framesize = i32(s)
|
||||||
|
|
||||||
|
self.decodermaxblock = framesize
|
||||||
|
self.tile = [("fli", (0, 0) + self.size, self.__offset, None)]
|
||||||
|
|
||||||
|
self.__offset += framesize
|
||||||
|
|
||||||
|
def tell(self):
|
||||||
|
return self.__frame
|
||||||
|
|
||||||
|
def _close__fp(self):
|
||||||
|
try:
|
||||||
|
if self.__fp != self.fp:
|
||||||
|
self.__fp.close()
|
||||||
|
except AttributeError:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
self.__fp = None
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# registry
|
||||||
|
|
||||||
|
Image.register_open(FliImageFile.format, FliImageFile, _accept)
|
||||||
|
|
||||||
|
Image.register_extensions(FliImageFile.format, [".fli", ".flc"])
|
||||||
111
venv/lib/python3.9/site-packages/PIL/FontFile.py
Normal file
|
|
@ -0,0 +1,111 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# base class for raster font file parsers
|
||||||
|
#
|
||||||
|
# history:
|
||||||
|
# 1997-06-05 fl created
|
||||||
|
# 1997-08-19 fl restrict image width
|
||||||
|
#
|
||||||
|
# Copyright (c) 1997-1998 by Secret Labs AB
|
||||||
|
# Copyright (c) 1997-1998 by Fredrik Lundh
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
from . import Image, _binary
|
||||||
|
|
||||||
|
WIDTH = 800
|
||||||
|
|
||||||
|
|
||||||
|
def puti16(fp, values):
|
||||||
|
"""Write network order (big-endian) 16-bit sequence"""
|
||||||
|
for v in values:
|
||||||
|
if v < 0:
|
||||||
|
v += 65536
|
||||||
|
fp.write(_binary.o16be(v))
|
||||||
|
|
||||||
|
|
||||||
|
class FontFile:
|
||||||
|
"""Base class for raster font file handlers."""
|
||||||
|
|
||||||
|
bitmap = None
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
|
||||||
|
self.info = {}
|
||||||
|
self.glyph = [None] * 256
|
||||||
|
|
||||||
|
def __getitem__(self, ix):
|
||||||
|
return self.glyph[ix]
|
||||||
|
|
||||||
|
def compile(self):
|
||||||
|
"""Create metrics and bitmap"""
|
||||||
|
|
||||||
|
if self.bitmap:
|
||||||
|
return
|
||||||
|
|
||||||
|
# create bitmap large enough to hold all data
|
||||||
|
h = w = maxwidth = 0
|
||||||
|
lines = 1
|
||||||
|
for glyph in self:
|
||||||
|
if glyph:
|
||||||
|
d, dst, src, im = glyph
|
||||||
|
h = max(h, src[3] - src[1])
|
||||||
|
w = w + (src[2] - src[0])
|
||||||
|
if w > WIDTH:
|
||||||
|
lines += 1
|
||||||
|
w = src[2] - src[0]
|
||||||
|
maxwidth = max(maxwidth, w)
|
||||||
|
|
||||||
|
xsize = maxwidth
|
||||||
|
ysize = lines * h
|
||||||
|
|
||||||
|
if xsize == 0 and ysize == 0:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
self.ysize = h
|
||||||
|
|
||||||
|
# paste glyphs into bitmap
|
||||||
|
self.bitmap = Image.new("1", (xsize, ysize))
|
||||||
|
self.metrics = [None] * 256
|
||||||
|
x = y = 0
|
||||||
|
for i in range(256):
|
||||||
|
glyph = self[i]
|
||||||
|
if glyph:
|
||||||
|
d, dst, src, im = glyph
|
||||||
|
xx = src[2] - src[0]
|
||||||
|
# yy = src[3] - src[1]
|
||||||
|
x0, y0 = x, y
|
||||||
|
x = x + xx
|
||||||
|
if x > WIDTH:
|
||||||
|
x, y = 0, y + h
|
||||||
|
x0, y0 = x, y
|
||||||
|
x = xx
|
||||||
|
s = src[0] + x0, src[1] + y0, src[2] + x0, src[3] + y0
|
||||||
|
self.bitmap.paste(im.crop(src), s)
|
||||||
|
self.metrics[i] = d, dst, s
|
||||||
|
|
||||||
|
def save(self, filename):
|
||||||
|
"""Save font"""
|
||||||
|
|
||||||
|
self.compile()
|
||||||
|
|
||||||
|
# font data
|
||||||
|
self.bitmap.save(os.path.splitext(filename)[0] + ".pbm", "PNG")
|
||||||
|
|
||||||
|
# font metrics
|
||||||
|
with open(os.path.splitext(filename)[0] + ".pil", "wb") as fp:
|
||||||
|
fp.write(b"PILfont\n")
|
||||||
|
fp.write(f";;;;;;{self.ysize};\n".encode("ascii")) # HACK!!!
|
||||||
|
fp.write(b"DATA\n")
|
||||||
|
for id in range(256):
|
||||||
|
m = self.metrics[id]
|
||||||
|
if not m:
|
||||||
|
puti16(fp, [0] * 10)
|
||||||
|
else:
|
||||||
|
puti16(fp, m[0] + m[1] + m[2])
|
||||||
243
venv/lib/python3.9/site-packages/PIL/FpxImagePlugin.py
Normal file
|
|
@ -0,0 +1,243 @@
|
||||||
|
#
|
||||||
|
# THIS IS WORK IN PROGRESS
|
||||||
|
#
|
||||||
|
# The Python Imaging Library.
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# FlashPix support for PIL
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 97-01-25 fl Created (reads uncompressed RGB images only)
|
||||||
|
#
|
||||||
|
# Copyright (c) Secret Labs AB 1997.
|
||||||
|
# Copyright (c) Fredrik Lundh 1997.
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
import olefile
|
||||||
|
|
||||||
|
from . import Image, ImageFile
|
||||||
|
from ._binary import i8
|
||||||
|
from ._binary import i32le as i32
|
||||||
|
|
||||||
|
# we map from colour field tuples to (mode, rawmode) descriptors
|
||||||
|
MODES = {
|
||||||
|
# opacity
|
||||||
|
(0x00007FFE): ("A", "L"),
|
||||||
|
# monochrome
|
||||||
|
(0x00010000,): ("L", "L"),
|
||||||
|
(0x00018000, 0x00017FFE): ("RGBA", "LA"),
|
||||||
|
# photo YCC
|
||||||
|
(0x00020000, 0x00020001, 0x00020002): ("RGB", "YCC;P"),
|
||||||
|
(0x00028000, 0x00028001, 0x00028002, 0x00027FFE): ("RGBA", "YCCA;P"),
|
||||||
|
# standard RGB (NIFRGB)
|
||||||
|
(0x00030000, 0x00030001, 0x00030002): ("RGB", "RGB"),
|
||||||
|
(0x00038000, 0x00038001, 0x00038002, 0x00037FFE): ("RGBA", "RGBA"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _accept(prefix):
|
||||||
|
return prefix[:8] == olefile.MAGIC
|
||||||
|
|
||||||
|
|
||||||
|
##
|
||||||
|
# Image plugin for the FlashPix images.
|
||||||
|
|
||||||
|
|
||||||
|
class FpxImageFile(ImageFile.ImageFile):
|
||||||
|
|
||||||
|
format = "FPX"
|
||||||
|
format_description = "FlashPix"
|
||||||
|
|
||||||
|
def _open(self):
|
||||||
|
#
|
||||||
|
# read the OLE directory and see if this is a likely
|
||||||
|
# to be a FlashPix file
|
||||||
|
|
||||||
|
try:
|
||||||
|
self.ole = olefile.OleFileIO(self.fp)
|
||||||
|
except OSError as e:
|
||||||
|
raise SyntaxError("not an FPX file; invalid OLE file") from e
|
||||||
|
|
||||||
|
if self.ole.root.clsid != "56616700-C154-11CE-8553-00AA00A1F95B":
|
||||||
|
raise SyntaxError("not an FPX file; bad root CLSID")
|
||||||
|
|
||||||
|
self._open_index(1)
|
||||||
|
|
||||||
|
def _open_index(self, index=1):
|
||||||
|
#
|
||||||
|
# get the Image Contents Property Set
|
||||||
|
|
||||||
|
prop = self.ole.getproperties(
|
||||||
|
[f"Data Object Store {index:06d}", "\005Image Contents"]
|
||||||
|
)
|
||||||
|
|
||||||
|
# size (highest resolution)
|
||||||
|
|
||||||
|
self._size = prop[0x1000002], prop[0x1000003]
|
||||||
|
|
||||||
|
size = max(self.size)
|
||||||
|
i = 1
|
||||||
|
while size > 64:
|
||||||
|
size = size / 2
|
||||||
|
i += 1
|
||||||
|
self.maxid = i - 1
|
||||||
|
|
||||||
|
# mode. instead of using a single field for this, flashpix
|
||||||
|
# requires you to specify the mode for each channel in each
|
||||||
|
# resolution subimage, and leaves it to the decoder to make
|
||||||
|
# sure that they all match. for now, we'll cheat and assume
|
||||||
|
# that this is always the case.
|
||||||
|
|
||||||
|
id = self.maxid << 16
|
||||||
|
|
||||||
|
s = prop[0x2000002 | id]
|
||||||
|
|
||||||
|
colors = []
|
||||||
|
bands = i32(s, 4)
|
||||||
|
if bands > 4:
|
||||||
|
raise OSError("Invalid number of bands")
|
||||||
|
for i in range(bands):
|
||||||
|
# note: for now, we ignore the "uncalibrated" flag
|
||||||
|
colors.append(i32(s, 8 + i * 4) & 0x7FFFFFFF)
|
||||||
|
|
||||||
|
self.mode, self.rawmode = MODES[tuple(colors)]
|
||||||
|
|
||||||
|
# load JPEG tables, if any
|
||||||
|
self.jpeg = {}
|
||||||
|
for i in range(256):
|
||||||
|
id = 0x3000001 | (i << 16)
|
||||||
|
if id in prop:
|
||||||
|
self.jpeg[i] = prop[id]
|
||||||
|
|
||||||
|
self._open_subimage(1, self.maxid)
|
||||||
|
|
||||||
|
def _open_subimage(self, index=1, subimage=0):
|
||||||
|
#
|
||||||
|
# setup tile descriptors for a given subimage
|
||||||
|
|
||||||
|
stream = [
|
||||||
|
f"Data Object Store {index:06d}",
|
||||||
|
f"Resolution {subimage:04d}",
|
||||||
|
"Subimage 0000 Header",
|
||||||
|
]
|
||||||
|
|
||||||
|
fp = self.ole.openstream(stream)
|
||||||
|
|
||||||
|
# skip prefix
|
||||||
|
fp.read(28)
|
||||||
|
|
||||||
|
# header stream
|
||||||
|
s = fp.read(36)
|
||||||
|
|
||||||
|
size = i32(s, 4), i32(s, 8)
|
||||||
|
# tilecount = i32(s, 12)
|
||||||
|
tilesize = i32(s, 16), i32(s, 20)
|
||||||
|
# channels = i32(s, 24)
|
||||||
|
offset = i32(s, 28)
|
||||||
|
length = i32(s, 32)
|
||||||
|
|
||||||
|
if size != self.size:
|
||||||
|
raise OSError("subimage mismatch")
|
||||||
|
|
||||||
|
# get tile descriptors
|
||||||
|
fp.seek(28 + offset)
|
||||||
|
s = fp.read(i32(s, 12) * length)
|
||||||
|
|
||||||
|
x = y = 0
|
||||||
|
xsize, ysize = size
|
||||||
|
xtile, ytile = tilesize
|
||||||
|
self.tile = []
|
||||||
|
|
||||||
|
for i in range(0, len(s), length):
|
||||||
|
|
||||||
|
compression = i32(s, i + 8)
|
||||||
|
|
||||||
|
if compression == 0:
|
||||||
|
self.tile.append(
|
||||||
|
(
|
||||||
|
"raw",
|
||||||
|
(x, y, x + xtile, y + ytile),
|
||||||
|
i32(s, i) + 28,
|
||||||
|
(self.rawmode),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
elif compression == 1:
|
||||||
|
|
||||||
|
# FIXME: the fill decoder is not implemented
|
||||||
|
self.tile.append(
|
||||||
|
(
|
||||||
|
"fill",
|
||||||
|
(x, y, x + xtile, y + ytile),
|
||||||
|
i32(s, i) + 28,
|
||||||
|
(self.rawmode, s[12:16]),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
elif compression == 2:
|
||||||
|
|
||||||
|
internal_color_conversion = i8(s[14])
|
||||||
|
jpeg_tables = i8(s[15])
|
||||||
|
rawmode = self.rawmode
|
||||||
|
|
||||||
|
if internal_color_conversion:
|
||||||
|
# The image is stored as usual (usually YCbCr).
|
||||||
|
if rawmode == "RGBA":
|
||||||
|
# For "RGBA", data is stored as YCbCrA based on
|
||||||
|
# negative RGB. The following trick works around
|
||||||
|
# this problem :
|
||||||
|
jpegmode, rawmode = "YCbCrK", "CMYK"
|
||||||
|
else:
|
||||||
|
jpegmode = None # let the decoder decide
|
||||||
|
|
||||||
|
else:
|
||||||
|
# The image is stored as defined by rawmode
|
||||||
|
jpegmode = rawmode
|
||||||
|
|
||||||
|
self.tile.append(
|
||||||
|
(
|
||||||
|
"jpeg",
|
||||||
|
(x, y, x + xtile, y + ytile),
|
||||||
|
i32(s, i) + 28,
|
||||||
|
(rawmode, jpegmode),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
# FIXME: jpeg tables are tile dependent; the prefix
|
||||||
|
# data must be placed in the tile descriptor itself!
|
||||||
|
|
||||||
|
if jpeg_tables:
|
||||||
|
self.tile_prefix = self.jpeg[jpeg_tables]
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise OSError("unknown/invalid compression")
|
||||||
|
|
||||||
|
x = x + xtile
|
||||||
|
if x >= xsize:
|
||||||
|
x, y = 0, y + ytile
|
||||||
|
if y >= ysize:
|
||||||
|
break # isn't really required
|
||||||
|
|
||||||
|
self.stream = stream
|
||||||
|
self.fp = None
|
||||||
|
|
||||||
|
def load(self):
|
||||||
|
|
||||||
|
if not self.fp:
|
||||||
|
self.fp = self.ole.openstream(self.stream[:2] + ["Subimage 0000 Data"])
|
||||||
|
|
||||||
|
return ImageFile.ImageFile.load(self)
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
Image.register_open(FpxImageFile.format, FpxImageFile, _accept)
|
||||||
|
|
||||||
|
Image.register_extension(FpxImageFile.format, ".fpx")
|
||||||
106
venv/lib/python3.9/site-packages/PIL/FtexImagePlugin.py
Normal file
|
|
@ -0,0 +1,106 @@
|
||||||
|
"""
|
||||||
|
A Pillow loader for .ftc and .ftu files (FTEX)
|
||||||
|
Jerome Leclanche <jerome@leclan.ch>
|
||||||
|
|
||||||
|
The contents of this file are hereby released in the public domain (CC0)
|
||||||
|
Full text of the CC0 license:
|
||||||
|
https://creativecommons.org/publicdomain/zero/1.0/
|
||||||
|
|
||||||
|
Independence War 2: Edge Of Chaos - Texture File Format - 16 October 2001
|
||||||
|
|
||||||
|
The textures used for 3D objects in Independence War 2: Edge Of Chaos are in a
|
||||||
|
packed custom format called FTEX. This file format uses file extensions FTC
|
||||||
|
and FTU.
|
||||||
|
* FTC files are compressed textures (using standard texture compression).
|
||||||
|
* FTU files are not compressed.
|
||||||
|
Texture File Format
|
||||||
|
The FTC and FTU texture files both use the same format. This
|
||||||
|
has the following structure:
|
||||||
|
{header}
|
||||||
|
{format_directory}
|
||||||
|
{data}
|
||||||
|
Where:
|
||||||
|
{header} = {
|
||||||
|
u32:magic,
|
||||||
|
u32:version,
|
||||||
|
u32:width,
|
||||||
|
u32:height,
|
||||||
|
u32:mipmap_count,
|
||||||
|
u32:format_count
|
||||||
|
}
|
||||||
|
|
||||||
|
* The "magic" number is "FTEX".
|
||||||
|
* "width" and "height" are the dimensions of the texture.
|
||||||
|
* "mipmap_count" is the number of mipmaps in the texture.
|
||||||
|
* "format_count" is the number of texture formats (different versions of the
|
||||||
|
same texture) in this file.
|
||||||
|
|
||||||
|
{format_directory} = format_count * { u32:format, u32:where }
|
||||||
|
|
||||||
|
The format value is 0 for DXT1 compressed textures and 1 for 24-bit RGB
|
||||||
|
uncompressed textures.
|
||||||
|
The texture data for a format starts at the position "where" in the file.
|
||||||
|
|
||||||
|
Each set of texture data in the file has the following structure:
|
||||||
|
{data} = format_count * { u32:mipmap_size, mipmap_size * { u8 } }
|
||||||
|
* "mipmap_size" is the number of bytes in that mip level. For compressed
|
||||||
|
textures this is the size of the texture data compressed with DXT1. For 24 bit
|
||||||
|
uncompressed textures, this is 3 * width * height. Following this are the image
|
||||||
|
bytes for that mipmap level.
|
||||||
|
|
||||||
|
Note: All data is stored in little-Endian (Intel) byte order.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import struct
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
from . import Image, ImageFile
|
||||||
|
|
||||||
|
MAGIC = b"FTEX"
|
||||||
|
FORMAT_DXT1 = 0
|
||||||
|
FORMAT_UNCOMPRESSED = 1
|
||||||
|
|
||||||
|
|
||||||
|
class FtexImageFile(ImageFile.ImageFile):
|
||||||
|
format = "FTEX"
|
||||||
|
format_description = "Texture File Format (IW2:EOC)"
|
||||||
|
|
||||||
|
def _open(self):
|
||||||
|
struct.unpack("<I", self.fp.read(4)) # magic
|
||||||
|
struct.unpack("<i", self.fp.read(4)) # version
|
||||||
|
self._size = struct.unpack("<2i", self.fp.read(8))
|
||||||
|
mipmap_count, format_count = struct.unpack("<2i", self.fp.read(8))
|
||||||
|
|
||||||
|
self.mode = "RGB"
|
||||||
|
|
||||||
|
# Only support single-format files.
|
||||||
|
# I don't know of any multi-format file.
|
||||||
|
assert format_count == 1
|
||||||
|
|
||||||
|
format, where = struct.unpack("<2i", self.fp.read(8))
|
||||||
|
self.fp.seek(where)
|
||||||
|
(mipmap_size,) = struct.unpack("<i", self.fp.read(4))
|
||||||
|
|
||||||
|
data = self.fp.read(mipmap_size)
|
||||||
|
|
||||||
|
if format == FORMAT_DXT1:
|
||||||
|
self.mode = "RGBA"
|
||||||
|
self.tile = [("bcn", (0, 0) + self.size, 0, (1))]
|
||||||
|
elif format == FORMAT_UNCOMPRESSED:
|
||||||
|
self.tile = [("raw", (0, 0) + self.size, 0, ("RGB", 0, 1))]
|
||||||
|
else:
|
||||||
|
raise ValueError(f"Invalid texture compression format: {repr(format)}")
|
||||||
|
|
||||||
|
self.fp.close()
|
||||||
|
self.fp = BytesIO(data)
|
||||||
|
|
||||||
|
def load_seek(self, pos):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _validate(prefix):
|
||||||
|
return prefix[:4] == MAGIC
|
||||||
|
|
||||||
|
|
||||||
|
Image.register_open(FtexImageFile.format, FtexImageFile, _validate)
|
||||||
|
Image.register_extensions(FtexImageFile.format, [".ftc", ".ftu"])
|
||||||
100
venv/lib/python3.9/site-packages/PIL/GbrImagePlugin.py
Normal file
|
|
@ -0,0 +1,100 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library
|
||||||
|
#
|
||||||
|
# load a GIMP brush file
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 96-03-14 fl Created
|
||||||
|
# 16-01-08 es Version 2
|
||||||
|
#
|
||||||
|
# Copyright (c) Secret Labs AB 1997.
|
||||||
|
# Copyright (c) Fredrik Lundh 1996.
|
||||||
|
# Copyright (c) Eric Soroos 2016.
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
#
|
||||||
|
# See https://github.com/GNOME/gimp/blob/mainline/devel-docs/gbr.txt for
|
||||||
|
# format documentation.
|
||||||
|
#
|
||||||
|
# This code Interprets version 1 and 2 .gbr files.
|
||||||
|
# Version 1 files are obsolete, and should not be used for new
|
||||||
|
# brushes.
|
||||||
|
# Version 2 files are saved by GIMP v2.8 (at least)
|
||||||
|
# Version 3 files have a format specifier of 18 for 16bit floats in
|
||||||
|
# the color depth field. This is currently unsupported by Pillow.
|
||||||
|
|
||||||
|
from . import Image, ImageFile
|
||||||
|
from ._binary import i32be as i32
|
||||||
|
|
||||||
|
|
||||||
|
def _accept(prefix):
|
||||||
|
return len(prefix) >= 8 and i32(prefix[:4]) >= 20 and i32(prefix[4:8]) in (1, 2)
|
||||||
|
|
||||||
|
|
||||||
|
##
|
||||||
|
# Image plugin for the GIMP brush format.
|
||||||
|
|
||||||
|
|
||||||
|
class GbrImageFile(ImageFile.ImageFile):
|
||||||
|
|
||||||
|
format = "GBR"
|
||||||
|
format_description = "GIMP brush file"
|
||||||
|
|
||||||
|
def _open(self):
|
||||||
|
header_size = i32(self.fp.read(4))
|
||||||
|
version = i32(self.fp.read(4))
|
||||||
|
if header_size < 20:
|
||||||
|
raise SyntaxError("not a GIMP brush")
|
||||||
|
if version not in (1, 2):
|
||||||
|
raise SyntaxError(f"Unsupported GIMP brush version: {version}")
|
||||||
|
|
||||||
|
width = i32(self.fp.read(4))
|
||||||
|
height = i32(self.fp.read(4))
|
||||||
|
color_depth = i32(self.fp.read(4))
|
||||||
|
if width <= 0 or height <= 0:
|
||||||
|
raise SyntaxError("not a GIMP brush")
|
||||||
|
if color_depth not in (1, 4):
|
||||||
|
raise SyntaxError(f"Unsupported GIMP brush color depth: {color_depth}")
|
||||||
|
|
||||||
|
if version == 1:
|
||||||
|
comment_length = header_size - 20
|
||||||
|
else:
|
||||||
|
comment_length = header_size - 28
|
||||||
|
magic_number = self.fp.read(4)
|
||||||
|
if magic_number != b"GIMP":
|
||||||
|
raise SyntaxError("not a GIMP brush, bad magic number")
|
||||||
|
self.info["spacing"] = i32(self.fp.read(4))
|
||||||
|
|
||||||
|
comment = self.fp.read(comment_length)[:-1]
|
||||||
|
|
||||||
|
if color_depth == 1:
|
||||||
|
self.mode = "L"
|
||||||
|
else:
|
||||||
|
self.mode = "RGBA"
|
||||||
|
|
||||||
|
self._size = width, height
|
||||||
|
|
||||||
|
self.info["comment"] = comment
|
||||||
|
|
||||||
|
# Image might not be small
|
||||||
|
Image._decompression_bomb_check(self.size)
|
||||||
|
|
||||||
|
# Data is an uncompressed block of w * h * bytes/pixel
|
||||||
|
self._data_size = width * height * color_depth
|
||||||
|
|
||||||
|
def load(self):
|
||||||
|
if self.im:
|
||||||
|
# Already loaded
|
||||||
|
return
|
||||||
|
|
||||||
|
self.im = Image.core.new(self.mode, self.size)
|
||||||
|
self.frombytes(self.fp.read(self._data_size))
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# registry
|
||||||
|
|
||||||
|
|
||||||
|
Image.register_open(GbrImageFile.format, GbrImageFile, _accept)
|
||||||
|
Image.register_extension(GbrImageFile.format, ".gbr")
|
||||||
91
venv/lib/python3.9/site-packages/PIL/GdImageFile.py
Normal file
|
|
@ -0,0 +1,91 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library.
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# GD file handling
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 1996-04-12 fl Created
|
||||||
|
#
|
||||||
|
# Copyright (c) 1997 by Secret Labs AB.
|
||||||
|
# Copyright (c) 1996 by Fredrik Lundh.
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
|
||||||
|
"""
|
||||||
|
.. note::
|
||||||
|
This format cannot be automatically recognized, so the
|
||||||
|
class is not registered for use with :py:func:`PIL.Image.open()`. To open a
|
||||||
|
gd file, use the :py:func:`PIL.GdImageFile.open()` function instead.
|
||||||
|
|
||||||
|
.. warning::
|
||||||
|
THE GD FORMAT IS NOT DESIGNED FOR DATA INTERCHANGE. This
|
||||||
|
implementation is provided for convenience and demonstrational
|
||||||
|
purposes only.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
from . import ImageFile, ImagePalette, UnidentifiedImageError
|
||||||
|
from ._binary import i8
|
||||||
|
from ._binary import i16be as i16
|
||||||
|
from ._binary import i32be as i32
|
||||||
|
|
||||||
|
|
||||||
|
class GdImageFile(ImageFile.ImageFile):
|
||||||
|
"""
|
||||||
|
Image plugin for the GD uncompressed format. Note that this format
|
||||||
|
is not supported by the standard :py:func:`PIL.Image.open()` function. To use
|
||||||
|
this plugin, you have to import the :py:mod:`PIL.GdImageFile` module and
|
||||||
|
use the :py:func:`PIL.GdImageFile.open()` function.
|
||||||
|
"""
|
||||||
|
|
||||||
|
format = "GD"
|
||||||
|
format_description = "GD uncompressed images"
|
||||||
|
|
||||||
|
def _open(self):
|
||||||
|
|
||||||
|
# Header
|
||||||
|
s = self.fp.read(1037)
|
||||||
|
|
||||||
|
if not i16(s[:2]) in [65534, 65535]:
|
||||||
|
raise SyntaxError("Not a valid GD 2.x .gd file")
|
||||||
|
|
||||||
|
self.mode = "L" # FIXME: "P"
|
||||||
|
self._size = i16(s[2:4]), i16(s[4:6])
|
||||||
|
|
||||||
|
trueColor = i8(s[6])
|
||||||
|
trueColorOffset = 2 if trueColor else 0
|
||||||
|
|
||||||
|
# transparency index
|
||||||
|
tindex = i32(s[7 + trueColorOffset : 7 + trueColorOffset + 4])
|
||||||
|
if tindex < 256:
|
||||||
|
self.info["transparency"] = tindex
|
||||||
|
|
||||||
|
self.palette = ImagePalette.raw(
|
||||||
|
"XBGR", s[7 + trueColorOffset + 4 : 7 + trueColorOffset + 4 + 256 * 4]
|
||||||
|
)
|
||||||
|
|
||||||
|
self.tile = [
|
||||||
|
("raw", (0, 0) + self.size, 7 + trueColorOffset + 4 + 256 * 4, ("L", 0, 1))
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def open(fp, mode="r"):
|
||||||
|
"""
|
||||||
|
Load texture from a GD image file.
|
||||||
|
|
||||||
|
:param filename: GD file name, or an opened file handle.
|
||||||
|
:param mode: Optional mode. In this version, if the mode argument
|
||||||
|
is given, it must be "r".
|
||||||
|
:returns: An image instance.
|
||||||
|
:raises OSError: If the image could not be read.
|
||||||
|
"""
|
||||||
|
if mode != "r":
|
||||||
|
raise ValueError("bad mode")
|
||||||
|
|
||||||
|
try:
|
||||||
|
return GdImageFile(fp)
|
||||||
|
except SyntaxError as e:
|
||||||
|
raise UnidentifiedImageError("cannot identify this image file") from e
|
||||||
888
venv/lib/python3.9/site-packages/PIL/GifImagePlugin.py
Normal file
|
|
@ -0,0 +1,888 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library.
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# GIF file handling
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 1995-09-01 fl Created
|
||||||
|
# 1996-12-14 fl Added interlace support
|
||||||
|
# 1996-12-30 fl Added animation support
|
||||||
|
# 1997-01-05 fl Added write support, fixed local colour map bug
|
||||||
|
# 1997-02-23 fl Make sure to load raster data in getdata()
|
||||||
|
# 1997-07-05 fl Support external decoder (0.4)
|
||||||
|
# 1998-07-09 fl Handle all modes when saving (0.5)
|
||||||
|
# 1998-07-15 fl Renamed offset attribute to avoid name clash
|
||||||
|
# 2001-04-16 fl Added rewind support (seek to frame 0) (0.6)
|
||||||
|
# 2001-04-17 fl Added palette optimization (0.7)
|
||||||
|
# 2002-06-06 fl Added transparency support for save (0.8)
|
||||||
|
# 2004-02-24 fl Disable interlacing for small images
|
||||||
|
#
|
||||||
|
# Copyright (c) 1997-2004 by Secret Labs AB
|
||||||
|
# Copyright (c) 1995-2004 by Fredrik Lundh
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
import itertools
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence
|
||||||
|
from ._binary import i8
|
||||||
|
from ._binary import i16le as i16
|
||||||
|
from ._binary import o8
|
||||||
|
from ._binary import o16le as o16
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# Identify/read GIF files
|
||||||
|
|
||||||
|
|
||||||
|
def _accept(prefix):
|
||||||
|
return prefix[:6] in [b"GIF87a", b"GIF89a"]
|
||||||
|
|
||||||
|
|
||||||
|
##
|
||||||
|
# Image plugin for GIF images. This plugin supports both GIF87 and
|
||||||
|
# GIF89 images.
|
||||||
|
|
||||||
|
|
||||||
|
class GifImageFile(ImageFile.ImageFile):
|
||||||
|
|
||||||
|
format = "GIF"
|
||||||
|
format_description = "Compuserve GIF"
|
||||||
|
_close_exclusive_fp_after_loading = False
|
||||||
|
|
||||||
|
global_palette = None
|
||||||
|
|
||||||
|
def data(self):
|
||||||
|
s = self.fp.read(1)
|
||||||
|
if s and i8(s):
|
||||||
|
return self.fp.read(i8(s))
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _open(self):
|
||||||
|
|
||||||
|
# Screen
|
||||||
|
s = self.fp.read(13)
|
||||||
|
if not _accept(s):
|
||||||
|
raise SyntaxError("not a GIF file")
|
||||||
|
|
||||||
|
self.info["version"] = s[:6]
|
||||||
|
self._size = i16(s[6:]), i16(s[8:])
|
||||||
|
self.tile = []
|
||||||
|
flags = i8(s[10])
|
||||||
|
bits = (flags & 7) + 1
|
||||||
|
|
||||||
|
if flags & 128:
|
||||||
|
# get global palette
|
||||||
|
self.info["background"] = i8(s[11])
|
||||||
|
# check if palette contains colour indices
|
||||||
|
p = self.fp.read(3 << bits)
|
||||||
|
for i in range(0, len(p), 3):
|
||||||
|
if not (i // 3 == i8(p[i]) == i8(p[i + 1]) == i8(p[i + 2])):
|
||||||
|
p = ImagePalette.raw("RGB", p)
|
||||||
|
self.global_palette = self.palette = p
|
||||||
|
break
|
||||||
|
|
||||||
|
self.__fp = self.fp # FIXME: hack
|
||||||
|
self.__rewind = self.fp.tell()
|
||||||
|
self._n_frames = None
|
||||||
|
self._is_animated = None
|
||||||
|
self._seek(0) # get ready to read first frame
|
||||||
|
|
||||||
|
@property
|
||||||
|
def n_frames(self):
|
||||||
|
if self._n_frames is None:
|
||||||
|
current = self.tell()
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
self.seek(self.tell() + 1)
|
||||||
|
except EOFError:
|
||||||
|
self._n_frames = self.tell() + 1
|
||||||
|
self.seek(current)
|
||||||
|
return self._n_frames
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_animated(self):
|
||||||
|
if self._is_animated is None:
|
||||||
|
if self._n_frames is not None:
|
||||||
|
self._is_animated = self._n_frames != 1
|
||||||
|
else:
|
||||||
|
current = self.tell()
|
||||||
|
|
||||||
|
try:
|
||||||
|
self.seek(1)
|
||||||
|
self._is_animated = True
|
||||||
|
except EOFError:
|
||||||
|
self._is_animated = False
|
||||||
|
|
||||||
|
self.seek(current)
|
||||||
|
return self._is_animated
|
||||||
|
|
||||||
|
def seek(self, frame):
|
||||||
|
if not self._seek_check(frame):
|
||||||
|
return
|
||||||
|
if frame < self.__frame:
|
||||||
|
if frame != 0:
|
||||||
|
self.im = None
|
||||||
|
self._seek(0)
|
||||||
|
|
||||||
|
last_frame = self.__frame
|
||||||
|
for f in range(self.__frame + 1, frame + 1):
|
||||||
|
try:
|
||||||
|
self._seek(f)
|
||||||
|
except EOFError as e:
|
||||||
|
self.seek(last_frame)
|
||||||
|
raise EOFError("no more images in GIF file") from e
|
||||||
|
|
||||||
|
def _seek(self, frame):
|
||||||
|
|
||||||
|
if frame == 0:
|
||||||
|
# rewind
|
||||||
|
self.__offset = 0
|
||||||
|
self.dispose = None
|
||||||
|
self.dispose_extent = [0, 0, 0, 0] # x0, y0, x1, y1
|
||||||
|
self.__frame = -1
|
||||||
|
self.__fp.seek(self.__rewind)
|
||||||
|
self._prev_im = None
|
||||||
|
self.disposal_method = 0
|
||||||
|
else:
|
||||||
|
# ensure that the previous frame was loaded
|
||||||
|
if not self.im:
|
||||||
|
self.load()
|
||||||
|
|
||||||
|
if frame != self.__frame + 1:
|
||||||
|
raise ValueError(f"cannot seek to frame {frame}")
|
||||||
|
self.__frame = frame
|
||||||
|
|
||||||
|
self.tile = []
|
||||||
|
|
||||||
|
self.fp = self.__fp
|
||||||
|
if self.__offset:
|
||||||
|
# backup to last frame
|
||||||
|
self.fp.seek(self.__offset)
|
||||||
|
while self.data():
|
||||||
|
pass
|
||||||
|
self.__offset = 0
|
||||||
|
|
||||||
|
if self.dispose:
|
||||||
|
self.im.paste(self.dispose, self.dispose_extent)
|
||||||
|
|
||||||
|
from copy import copy
|
||||||
|
|
||||||
|
self.palette = copy(self.global_palette)
|
||||||
|
|
||||||
|
info = {}
|
||||||
|
while True:
|
||||||
|
|
||||||
|
s = self.fp.read(1)
|
||||||
|
if not s or s == b";":
|
||||||
|
break
|
||||||
|
|
||||||
|
elif s == b"!":
|
||||||
|
#
|
||||||
|
# extensions
|
||||||
|
#
|
||||||
|
s = self.fp.read(1)
|
||||||
|
block = self.data()
|
||||||
|
if i8(s) == 249:
|
||||||
|
#
|
||||||
|
# graphic control extension
|
||||||
|
#
|
||||||
|
flags = i8(block[0])
|
||||||
|
if flags & 1:
|
||||||
|
info["transparency"] = i8(block[3])
|
||||||
|
info["duration"] = i16(block[1:3]) * 10
|
||||||
|
|
||||||
|
# disposal method - find the value of bits 4 - 6
|
||||||
|
dispose_bits = 0b00011100 & flags
|
||||||
|
dispose_bits = dispose_bits >> 2
|
||||||
|
if dispose_bits:
|
||||||
|
# only set the dispose if it is not
|
||||||
|
# unspecified. I'm not sure if this is
|
||||||
|
# correct, but it seems to prevent the last
|
||||||
|
# frame from looking odd for some animations
|
||||||
|
self.disposal_method = dispose_bits
|
||||||
|
elif i8(s) == 254:
|
||||||
|
#
|
||||||
|
# comment extension
|
||||||
|
#
|
||||||
|
while block:
|
||||||
|
if "comment" in info:
|
||||||
|
info["comment"] += block
|
||||||
|
else:
|
||||||
|
info["comment"] = block
|
||||||
|
block = self.data()
|
||||||
|
continue
|
||||||
|
elif i8(s) == 255:
|
||||||
|
#
|
||||||
|
# application extension
|
||||||
|
#
|
||||||
|
info["extension"] = block, self.fp.tell()
|
||||||
|
if block[:11] == b"NETSCAPE2.0":
|
||||||
|
block = self.data()
|
||||||
|
if len(block) >= 3 and i8(block[0]) == 1:
|
||||||
|
info["loop"] = i16(block[1:3])
|
||||||
|
while self.data():
|
||||||
|
pass
|
||||||
|
|
||||||
|
elif s == b",":
|
||||||
|
#
|
||||||
|
# local image
|
||||||
|
#
|
||||||
|
s = self.fp.read(9)
|
||||||
|
|
||||||
|
# extent
|
||||||
|
x0, y0 = i16(s[0:]), i16(s[2:])
|
||||||
|
x1, y1 = x0 + i16(s[4:]), y0 + i16(s[6:])
|
||||||
|
if x1 > self.size[0] or y1 > self.size[1]:
|
||||||
|
self._size = max(x1, self.size[0]), max(y1, self.size[1])
|
||||||
|
self.dispose_extent = x0, y0, x1, y1
|
||||||
|
flags = i8(s[8])
|
||||||
|
|
||||||
|
interlace = (flags & 64) != 0
|
||||||
|
|
||||||
|
if flags & 128:
|
||||||
|
bits = (flags & 7) + 1
|
||||||
|
self.palette = ImagePalette.raw("RGB", self.fp.read(3 << bits))
|
||||||
|
|
||||||
|
# image data
|
||||||
|
bits = i8(self.fp.read(1))
|
||||||
|
self.__offset = self.fp.tell()
|
||||||
|
self.tile = [
|
||||||
|
("gif", (x0, y0, x1, y1), self.__offset, (bits, interlace))
|
||||||
|
]
|
||||||
|
break
|
||||||
|
|
||||||
|
else:
|
||||||
|
pass
|
||||||
|
# raise OSError, "illegal GIF tag `%x`" % i8(s)
|
||||||
|
|
||||||
|
try:
|
||||||
|
if self.disposal_method < 2:
|
||||||
|
# do not dispose or none specified
|
||||||
|
self.dispose = None
|
||||||
|
elif self.disposal_method == 2:
|
||||||
|
# replace with background colour
|
||||||
|
Image._decompression_bomb_check(self.size)
|
||||||
|
self.dispose = Image.core.fill("P", self.size, self.info["background"])
|
||||||
|
else:
|
||||||
|
# replace with previous contents
|
||||||
|
if self.im:
|
||||||
|
self.dispose = self.im.copy()
|
||||||
|
|
||||||
|
# only dispose the extent in this frame
|
||||||
|
if self.dispose:
|
||||||
|
self.dispose = self._crop(self.dispose, self.dispose_extent)
|
||||||
|
except (AttributeError, KeyError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
if not self.tile:
|
||||||
|
# self.__fp = None
|
||||||
|
raise EOFError
|
||||||
|
|
||||||
|
for k in ["transparency", "duration", "comment", "extension", "loop"]:
|
||||||
|
if k in info:
|
||||||
|
self.info[k] = info[k]
|
||||||
|
elif k in self.info:
|
||||||
|
del self.info[k]
|
||||||
|
|
||||||
|
self.mode = "L"
|
||||||
|
if self.palette:
|
||||||
|
self.mode = "P"
|
||||||
|
|
||||||
|
def tell(self):
|
||||||
|
return self.__frame
|
||||||
|
|
||||||
|
def load_end(self):
|
||||||
|
ImageFile.ImageFile.load_end(self)
|
||||||
|
|
||||||
|
# if the disposal method is 'do not dispose', transparent
|
||||||
|
# pixels should show the content of the previous frame
|
||||||
|
if self._prev_im and self.disposal_method == 1:
|
||||||
|
# we do this by pasting the updated area onto the previous
|
||||||
|
# frame which we then use as the current image content
|
||||||
|
updated = self._crop(self.im, self.dispose_extent)
|
||||||
|
self._prev_im.paste(updated, self.dispose_extent, updated.convert("RGBA"))
|
||||||
|
self.im = self._prev_im
|
||||||
|
self._prev_im = self.im.copy()
|
||||||
|
|
||||||
|
def _close__fp(self):
|
||||||
|
try:
|
||||||
|
if self.__fp != self.fp:
|
||||||
|
self.__fp.close()
|
||||||
|
except AttributeError:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
self.__fp = None
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# Write GIF files
|
||||||
|
|
||||||
|
|
||||||
|
RAWMODE = {"1": "L", "L": "L", "P": "P"}
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_mode(im, initial_call=False):
|
||||||
|
"""
|
||||||
|
Takes an image (or frame), returns an image in a mode that is appropriate
|
||||||
|
for saving in a Gif.
|
||||||
|
|
||||||
|
It may return the original image, or it may return an image converted to
|
||||||
|
palette or 'L' mode.
|
||||||
|
|
||||||
|
UNDONE: What is the point of mucking with the initial call palette, for
|
||||||
|
an image that shouldn't have a palette, or it would be a mode 'P' and
|
||||||
|
get returned in the RAWMODE clause.
|
||||||
|
|
||||||
|
:param im: Image object
|
||||||
|
:param initial_call: Default false, set to true for a single frame.
|
||||||
|
:returns: Image object
|
||||||
|
"""
|
||||||
|
if im.mode in RAWMODE:
|
||||||
|
im.load()
|
||||||
|
return im
|
||||||
|
if Image.getmodebase(im.mode) == "RGB":
|
||||||
|
if initial_call:
|
||||||
|
palette_size = 256
|
||||||
|
if im.palette:
|
||||||
|
palette_size = len(im.palette.getdata()[1]) // 3
|
||||||
|
return im.convert("P", palette=Image.ADAPTIVE, colors=palette_size)
|
||||||
|
else:
|
||||||
|
return im.convert("P")
|
||||||
|
return im.convert("L")
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_palette(im, palette, info):
|
||||||
|
"""
|
||||||
|
Normalizes the palette for image.
|
||||||
|
- Sets the palette to the incoming palette, if provided.
|
||||||
|
- Ensures that there's a palette for L mode images
|
||||||
|
- Optimizes the palette if necessary/desired.
|
||||||
|
|
||||||
|
:param im: Image object
|
||||||
|
:param palette: bytes object containing the source palette, or ....
|
||||||
|
:param info: encoderinfo
|
||||||
|
:returns: Image object
|
||||||
|
"""
|
||||||
|
source_palette = None
|
||||||
|
if palette:
|
||||||
|
# a bytes palette
|
||||||
|
if isinstance(palette, (bytes, bytearray, list)):
|
||||||
|
source_palette = bytearray(palette[:768])
|
||||||
|
if isinstance(palette, ImagePalette.ImagePalette):
|
||||||
|
source_palette = bytearray(
|
||||||
|
itertools.chain.from_iterable(
|
||||||
|
zip(
|
||||||
|
palette.palette[:256],
|
||||||
|
palette.palette[256:512],
|
||||||
|
palette.palette[512:768],
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
if im.mode == "P":
|
||||||
|
if not source_palette:
|
||||||
|
source_palette = im.im.getpalette("RGB")[:768]
|
||||||
|
else: # L-mode
|
||||||
|
if not source_palette:
|
||||||
|
source_palette = bytearray(i // 3 for i in range(768))
|
||||||
|
im.palette = ImagePalette.ImagePalette("RGB", palette=source_palette)
|
||||||
|
|
||||||
|
used_palette_colors = _get_optimize(im, info)
|
||||||
|
if used_palette_colors is not None:
|
||||||
|
return im.remap_palette(used_palette_colors, source_palette)
|
||||||
|
|
||||||
|
im.palette.palette = source_palette
|
||||||
|
return im
|
||||||
|
|
||||||
|
|
||||||
|
def _write_single_frame(im, fp, palette):
|
||||||
|
im_out = _normalize_mode(im, True)
|
||||||
|
for k, v in im_out.info.items():
|
||||||
|
im.encoderinfo.setdefault(k, v)
|
||||||
|
im_out = _normalize_palette(im_out, palette, im.encoderinfo)
|
||||||
|
|
||||||
|
for s in _get_global_header(im_out, im.encoderinfo):
|
||||||
|
fp.write(s)
|
||||||
|
|
||||||
|
# local image header
|
||||||
|
flags = 0
|
||||||
|
if get_interlace(im):
|
||||||
|
flags = flags | 64
|
||||||
|
_write_local_header(fp, im, (0, 0), flags)
|
||||||
|
|
||||||
|
im_out.encoderconfig = (8, get_interlace(im))
|
||||||
|
ImageFile._save(im_out, fp, [("gif", (0, 0) + im.size, 0, RAWMODE[im_out.mode])])
|
||||||
|
|
||||||
|
fp.write(b"\0") # end of image data
|
||||||
|
|
||||||
|
|
||||||
|
def _write_multiple_frames(im, fp, palette):
|
||||||
|
|
||||||
|
duration = im.encoderinfo.get("duration", im.info.get("duration"))
|
||||||
|
disposal = im.encoderinfo.get("disposal", im.info.get("disposal"))
|
||||||
|
|
||||||
|
im_frames = []
|
||||||
|
frame_count = 0
|
||||||
|
background_im = None
|
||||||
|
for imSequence in itertools.chain([im], im.encoderinfo.get("append_images", [])):
|
||||||
|
for im_frame in ImageSequence.Iterator(imSequence):
|
||||||
|
# a copy is required here since seek can still mutate the image
|
||||||
|
im_frame = _normalize_mode(im_frame.copy())
|
||||||
|
if frame_count == 0:
|
||||||
|
for k, v in im_frame.info.items():
|
||||||
|
im.encoderinfo.setdefault(k, v)
|
||||||
|
im_frame = _normalize_palette(im_frame, palette, im.encoderinfo)
|
||||||
|
|
||||||
|
encoderinfo = im.encoderinfo.copy()
|
||||||
|
if isinstance(duration, (list, tuple)):
|
||||||
|
encoderinfo["duration"] = duration[frame_count]
|
||||||
|
if isinstance(disposal, (list, tuple)):
|
||||||
|
encoderinfo["disposal"] = disposal[frame_count]
|
||||||
|
frame_count += 1
|
||||||
|
|
||||||
|
if im_frames:
|
||||||
|
# delta frame
|
||||||
|
previous = im_frames[-1]
|
||||||
|
if encoderinfo.get("disposal") == 2:
|
||||||
|
if background_im is None:
|
||||||
|
background = _get_background(
|
||||||
|
im,
|
||||||
|
im.encoderinfo.get("background", im.info.get("background")),
|
||||||
|
)
|
||||||
|
background_im = Image.new("P", im_frame.size, background)
|
||||||
|
background_im.putpalette(im_frames[0]["im"].palette)
|
||||||
|
base_im = background_im
|
||||||
|
else:
|
||||||
|
base_im = previous["im"]
|
||||||
|
if _get_palette_bytes(im_frame) == _get_palette_bytes(base_im):
|
||||||
|
delta = ImageChops.subtract_modulo(im_frame, base_im)
|
||||||
|
else:
|
||||||
|
delta = ImageChops.subtract_modulo(
|
||||||
|
im_frame.convert("RGB"), base_im.convert("RGB")
|
||||||
|
)
|
||||||
|
bbox = delta.getbbox()
|
||||||
|
if not bbox:
|
||||||
|
# This frame is identical to the previous frame
|
||||||
|
if duration:
|
||||||
|
previous["encoderinfo"]["duration"] += encoderinfo["duration"]
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
bbox = None
|
||||||
|
im_frames.append({"im": im_frame, "bbox": bbox, "encoderinfo": encoderinfo})
|
||||||
|
|
||||||
|
if len(im_frames) > 1:
|
||||||
|
for frame_data in im_frames:
|
||||||
|
im_frame = frame_data["im"]
|
||||||
|
if not frame_data["bbox"]:
|
||||||
|
# global header
|
||||||
|
for s in _get_global_header(im_frame, frame_data["encoderinfo"]):
|
||||||
|
fp.write(s)
|
||||||
|
offset = (0, 0)
|
||||||
|
else:
|
||||||
|
# compress difference
|
||||||
|
frame_data["encoderinfo"]["include_color_table"] = True
|
||||||
|
|
||||||
|
im_frame = im_frame.crop(frame_data["bbox"])
|
||||||
|
offset = frame_data["bbox"][:2]
|
||||||
|
_write_frame_data(fp, im_frame, offset, frame_data["encoderinfo"])
|
||||||
|
return True
|
||||||
|
elif "duration" in im.encoderinfo and isinstance(
|
||||||
|
im.encoderinfo["duration"], (list, tuple)
|
||||||
|
):
|
||||||
|
# Since multiple frames will not be written, add together the frame durations
|
||||||
|
im.encoderinfo["duration"] = sum(im.encoderinfo["duration"])
|
||||||
|
|
||||||
|
|
||||||
|
def _save_all(im, fp, filename):
|
||||||
|
_save(im, fp, filename, save_all=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _save(im, fp, filename, save_all=False):
|
||||||
|
# header
|
||||||
|
if "palette" in im.encoderinfo or "palette" in im.info:
|
||||||
|
palette = im.encoderinfo.get("palette", im.info.get("palette"))
|
||||||
|
else:
|
||||||
|
palette = None
|
||||||
|
im.encoderinfo["optimize"] = im.encoderinfo.get("optimize", True)
|
||||||
|
|
||||||
|
if not save_all or not _write_multiple_frames(im, fp, palette):
|
||||||
|
_write_single_frame(im, fp, palette)
|
||||||
|
|
||||||
|
fp.write(b";") # end of file
|
||||||
|
|
||||||
|
if hasattr(fp, "flush"):
|
||||||
|
fp.flush()
|
||||||
|
|
||||||
|
|
||||||
|
def get_interlace(im):
|
||||||
|
interlace = im.encoderinfo.get("interlace", 1)
|
||||||
|
|
||||||
|
# workaround for @PIL153
|
||||||
|
if min(im.size) < 16:
|
||||||
|
interlace = 0
|
||||||
|
|
||||||
|
return interlace
|
||||||
|
|
||||||
|
|
||||||
|
def _write_local_header(fp, im, offset, flags):
|
||||||
|
transparent_color_exists = False
|
||||||
|
try:
|
||||||
|
transparency = im.encoderinfo["transparency"]
|
||||||
|
except KeyError:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
transparency = int(transparency)
|
||||||
|
# optimize the block away if transparent color is not used
|
||||||
|
transparent_color_exists = True
|
||||||
|
|
||||||
|
used_palette_colors = _get_optimize(im, im.encoderinfo)
|
||||||
|
if used_palette_colors is not None:
|
||||||
|
# adjust the transparency index after optimize
|
||||||
|
try:
|
||||||
|
transparency = used_palette_colors.index(transparency)
|
||||||
|
except ValueError:
|
||||||
|
transparent_color_exists = False
|
||||||
|
|
||||||
|
if "duration" in im.encoderinfo:
|
||||||
|
duration = int(im.encoderinfo["duration"] / 10)
|
||||||
|
else:
|
||||||
|
duration = 0
|
||||||
|
|
||||||
|
disposal = int(im.encoderinfo.get("disposal", 0))
|
||||||
|
|
||||||
|
if transparent_color_exists or duration != 0 or disposal:
|
||||||
|
packed_flag = 1 if transparent_color_exists else 0
|
||||||
|
packed_flag |= disposal << 2
|
||||||
|
if not transparent_color_exists:
|
||||||
|
transparency = 0
|
||||||
|
|
||||||
|
fp.write(
|
||||||
|
b"!"
|
||||||
|
+ o8(249) # extension intro
|
||||||
|
+ o8(4) # length
|
||||||
|
+ o8(packed_flag) # packed fields
|
||||||
|
+ o16(duration) # duration
|
||||||
|
+ o8(transparency) # transparency index
|
||||||
|
+ o8(0)
|
||||||
|
)
|
||||||
|
|
||||||
|
if "comment" in im.encoderinfo and 1 <= len(im.encoderinfo["comment"]):
|
||||||
|
fp.write(b"!" + o8(254)) # extension intro
|
||||||
|
comment = im.encoderinfo["comment"]
|
||||||
|
if isinstance(comment, str):
|
||||||
|
comment = comment.encode()
|
||||||
|
for i in range(0, len(comment), 255):
|
||||||
|
subblock = comment[i : i + 255]
|
||||||
|
fp.write(o8(len(subblock)) + subblock)
|
||||||
|
fp.write(o8(0))
|
||||||
|
if "loop" in im.encoderinfo:
|
||||||
|
number_of_loops = im.encoderinfo["loop"]
|
||||||
|
fp.write(
|
||||||
|
b"!"
|
||||||
|
+ o8(255) # extension intro
|
||||||
|
+ o8(11)
|
||||||
|
+ b"NETSCAPE2.0"
|
||||||
|
+ o8(3)
|
||||||
|
+ o8(1)
|
||||||
|
+ o16(number_of_loops) # number of loops
|
||||||
|
+ o8(0)
|
||||||
|
)
|
||||||
|
include_color_table = im.encoderinfo.get("include_color_table")
|
||||||
|
if include_color_table:
|
||||||
|
palette_bytes = _get_palette_bytes(im)
|
||||||
|
color_table_size = _get_color_table_size(palette_bytes)
|
||||||
|
if color_table_size:
|
||||||
|
flags = flags | 128 # local color table flag
|
||||||
|
flags = flags | color_table_size
|
||||||
|
|
||||||
|
fp.write(
|
||||||
|
b","
|
||||||
|
+ o16(offset[0]) # offset
|
||||||
|
+ o16(offset[1])
|
||||||
|
+ o16(im.size[0]) # size
|
||||||
|
+ o16(im.size[1])
|
||||||
|
+ o8(flags) # flags
|
||||||
|
)
|
||||||
|
if include_color_table and color_table_size:
|
||||||
|
fp.write(_get_header_palette(palette_bytes))
|
||||||
|
fp.write(o8(8)) # bits
|
||||||
|
|
||||||
|
|
||||||
|
def _save_netpbm(im, fp, filename):
|
||||||
|
|
||||||
|
# Unused by default.
|
||||||
|
# To use, uncomment the register_save call at the end of the file.
|
||||||
|
#
|
||||||
|
# If you need real GIF compression and/or RGB quantization, you
|
||||||
|
# can use the external NETPBM/PBMPLUS utilities. See comments
|
||||||
|
# below for information on how to enable this.
|
||||||
|
tempfile = im._dump()
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(filename, "wb") as f:
|
||||||
|
if im.mode != "RGB":
|
||||||
|
subprocess.check_call(
|
||||||
|
["ppmtogif", tempfile], stdout=f, stderr=subprocess.DEVNULL
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# Pipe ppmquant output into ppmtogif
|
||||||
|
# "ppmquant 256 %s | ppmtogif > %s" % (tempfile, filename)
|
||||||
|
quant_cmd = ["ppmquant", "256", tempfile]
|
||||||
|
togif_cmd = ["ppmtogif"]
|
||||||
|
quant_proc = subprocess.Popen(
|
||||||
|
quant_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL
|
||||||
|
)
|
||||||
|
togif_proc = subprocess.Popen(
|
||||||
|
togif_cmd,
|
||||||
|
stdin=quant_proc.stdout,
|
||||||
|
stdout=f,
|
||||||
|
stderr=subprocess.DEVNULL,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Allow ppmquant to receive SIGPIPE if ppmtogif exits
|
||||||
|
quant_proc.stdout.close()
|
||||||
|
|
||||||
|
retcode = quant_proc.wait()
|
||||||
|
if retcode:
|
||||||
|
raise subprocess.CalledProcessError(retcode, quant_cmd)
|
||||||
|
|
||||||
|
retcode = togif_proc.wait()
|
||||||
|
if retcode:
|
||||||
|
raise subprocess.CalledProcessError(retcode, togif_cmd)
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
os.unlink(tempfile)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# Force optimization so that we can test performance against
|
||||||
|
# cases where it took lots of memory and time previously.
|
||||||
|
_FORCE_OPTIMIZE = False
|
||||||
|
|
||||||
|
|
||||||
|
def _get_optimize(im, info):
|
||||||
|
"""
|
||||||
|
Palette optimization is a potentially expensive operation.
|
||||||
|
|
||||||
|
This function determines if the palette should be optimized using
|
||||||
|
some heuristics, then returns the list of palette entries in use.
|
||||||
|
|
||||||
|
:param im: Image object
|
||||||
|
:param info: encoderinfo
|
||||||
|
:returns: list of indexes of palette entries in use, or None
|
||||||
|
"""
|
||||||
|
if im.mode in ("P", "L") and info and info.get("optimize", 0):
|
||||||
|
# Potentially expensive operation.
|
||||||
|
|
||||||
|
# The palette saves 3 bytes per color not used, but palette
|
||||||
|
# lengths are restricted to 3*(2**N) bytes. Max saving would
|
||||||
|
# be 768 -> 6 bytes if we went all the way down to 2 colors.
|
||||||
|
# * If we're over 128 colors, we can't save any space.
|
||||||
|
# * If there aren't any holes, it's not worth collapsing.
|
||||||
|
# * If we have a 'large' image, the palette is in the noise.
|
||||||
|
|
||||||
|
# create the new palette if not every color is used
|
||||||
|
optimise = _FORCE_OPTIMIZE or im.mode == "L"
|
||||||
|
if optimise or im.width * im.height < 512 * 512:
|
||||||
|
# check which colors are used
|
||||||
|
used_palette_colors = []
|
||||||
|
for i, count in enumerate(im.histogram()):
|
||||||
|
if count:
|
||||||
|
used_palette_colors.append(i)
|
||||||
|
|
||||||
|
if optimise or (
|
||||||
|
len(used_palette_colors) <= 128
|
||||||
|
and max(used_palette_colors) > len(used_palette_colors)
|
||||||
|
):
|
||||||
|
return used_palette_colors
|
||||||
|
|
||||||
|
|
||||||
|
def _get_color_table_size(palette_bytes):
|
||||||
|
# calculate the palette size for the header
|
||||||
|
if not palette_bytes:
|
||||||
|
return 0
|
||||||
|
elif len(palette_bytes) < 9:
|
||||||
|
return 1
|
||||||
|
else:
|
||||||
|
return math.ceil(math.log(len(palette_bytes) // 3, 2)) - 1
|
||||||
|
|
||||||
|
|
||||||
|
def _get_header_palette(palette_bytes):
|
||||||
|
"""
|
||||||
|
Returns the palette, null padded to the next power of 2 (*3) bytes
|
||||||
|
suitable for direct inclusion in the GIF header
|
||||||
|
|
||||||
|
:param palette_bytes: Unpadded palette bytes, in RGBRGB form
|
||||||
|
:returns: Null padded palette
|
||||||
|
"""
|
||||||
|
color_table_size = _get_color_table_size(palette_bytes)
|
||||||
|
|
||||||
|
# add the missing amount of bytes
|
||||||
|
# the palette has to be 2<<n in size
|
||||||
|
actual_target_size_diff = (2 << color_table_size) - len(palette_bytes) // 3
|
||||||
|
if actual_target_size_diff > 0:
|
||||||
|
palette_bytes += o8(0) * 3 * actual_target_size_diff
|
||||||
|
return palette_bytes
|
||||||
|
|
||||||
|
|
||||||
|
def _get_palette_bytes(im):
|
||||||
|
"""
|
||||||
|
Gets the palette for inclusion in the gif header
|
||||||
|
|
||||||
|
:param im: Image object
|
||||||
|
:returns: Bytes, len<=768 suitable for inclusion in gif header
|
||||||
|
"""
|
||||||
|
return im.palette.palette
|
||||||
|
|
||||||
|
|
||||||
|
def _get_background(im, infoBackground):
|
||||||
|
background = 0
|
||||||
|
if infoBackground:
|
||||||
|
background = infoBackground
|
||||||
|
if isinstance(background, tuple):
|
||||||
|
# WebPImagePlugin stores an RGBA value in info["background"]
|
||||||
|
# So it must be converted to the same format as GifImagePlugin's
|
||||||
|
# info["background"] - a global color table index
|
||||||
|
background = im.palette.getcolor(background)
|
||||||
|
return background
|
||||||
|
|
||||||
|
|
||||||
|
def _get_global_header(im, info):
|
||||||
|
"""Return a list of strings representing a GIF header"""
|
||||||
|
|
||||||
|
# Header Block
|
||||||
|
# http://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp
|
||||||
|
|
||||||
|
version = b"87a"
|
||||||
|
for extensionKey in ["transparency", "duration", "loop", "comment"]:
|
||||||
|
if info and extensionKey in info:
|
||||||
|
if (extensionKey == "duration" and info[extensionKey] == 0) or (
|
||||||
|
extensionKey == "comment" and not (1 <= len(info[extensionKey]) <= 255)
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
version = b"89a"
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
if im.info.get("version") == b"89a":
|
||||||
|
version = b"89a"
|
||||||
|
|
||||||
|
background = _get_background(im, info.get("background"))
|
||||||
|
|
||||||
|
palette_bytes = _get_palette_bytes(im)
|
||||||
|
color_table_size = _get_color_table_size(palette_bytes)
|
||||||
|
|
||||||
|
return [
|
||||||
|
b"GIF" # signature
|
||||||
|
+ version # version
|
||||||
|
+ o16(im.size[0]) # canvas width
|
||||||
|
+ o16(im.size[1]), # canvas height
|
||||||
|
# Logical Screen Descriptor
|
||||||
|
# size of global color table + global color table flag
|
||||||
|
o8(color_table_size + 128), # packed fields
|
||||||
|
# background + reserved/aspect
|
||||||
|
o8(background) + o8(0),
|
||||||
|
# Global Color Table
|
||||||
|
_get_header_palette(palette_bytes),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _write_frame_data(fp, im_frame, offset, params):
|
||||||
|
try:
|
||||||
|
im_frame.encoderinfo = params
|
||||||
|
|
||||||
|
# local image header
|
||||||
|
_write_local_header(fp, im_frame, offset, 0)
|
||||||
|
|
||||||
|
ImageFile._save(
|
||||||
|
im_frame, fp, [("gif", (0, 0) + im_frame.size, 0, RAWMODE[im_frame.mode])]
|
||||||
|
)
|
||||||
|
|
||||||
|
fp.write(b"\0") # end of image data
|
||||||
|
finally:
|
||||||
|
del im_frame.encoderinfo
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# Legacy GIF utilities
|
||||||
|
|
||||||
|
|
||||||
|
def getheader(im, palette=None, info=None):
|
||||||
|
"""
|
||||||
|
Legacy Method to get Gif data from image.
|
||||||
|
|
||||||
|
Warning:: May modify image data.
|
||||||
|
|
||||||
|
:param im: Image object
|
||||||
|
:param palette: bytes object containing the source palette, or ....
|
||||||
|
:param info: encoderinfo
|
||||||
|
:returns: tuple of(list of header items, optimized palette)
|
||||||
|
|
||||||
|
"""
|
||||||
|
used_palette_colors = _get_optimize(im, info)
|
||||||
|
|
||||||
|
if info is None:
|
||||||
|
info = {}
|
||||||
|
|
||||||
|
if "background" not in info and "background" in im.info:
|
||||||
|
info["background"] = im.info["background"]
|
||||||
|
|
||||||
|
im_mod = _normalize_palette(im, palette, info)
|
||||||
|
im.palette = im_mod.palette
|
||||||
|
im.im = im_mod.im
|
||||||
|
header = _get_global_header(im, info)
|
||||||
|
|
||||||
|
return header, used_palette_colors
|
||||||
|
|
||||||
|
|
||||||
|
# To specify duration, add the time in milliseconds to getdata(),
|
||||||
|
# e.g. getdata(im_frame, duration=1000)
|
||||||
|
def getdata(im, offset=(0, 0), **params):
|
||||||
|
"""
|
||||||
|
Legacy Method
|
||||||
|
|
||||||
|
Return a list of strings representing this image.
|
||||||
|
The first string is a local image header, the rest contains
|
||||||
|
encoded image data.
|
||||||
|
|
||||||
|
:param im: Image object
|
||||||
|
:param offset: Tuple of (x, y) pixels. Defaults to (0,0)
|
||||||
|
:param \\**params: E.g. duration or other encoder info parameters
|
||||||
|
:returns: List of Bytes containing gif encoded frame data
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
class Collector:
|
||||||
|
data = []
|
||||||
|
|
||||||
|
def write(self, data):
|
||||||
|
self.data.append(data)
|
||||||
|
|
||||||
|
im.load() # make sure raster data is available
|
||||||
|
|
||||||
|
fp = Collector()
|
||||||
|
|
||||||
|
_write_frame_data(fp, im, offset, params)
|
||||||
|
|
||||||
|
return fp.data
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# Registry
|
||||||
|
|
||||||
|
Image.register_open(GifImageFile.format, GifImageFile, _accept)
|
||||||
|
Image.register_save(GifImageFile.format, _save)
|
||||||
|
Image.register_save_all(GifImageFile.format, _save_all)
|
||||||
|
Image.register_extension(GifImageFile.format, ".gif")
|
||||||
|
Image.register_mime(GifImageFile.format, "image/gif")
|
||||||
|
|
||||||
|
#
|
||||||
|
# Uncomment the following line if you wish to use NETPBM/PBMPLUS
|
||||||
|
# instead of the built-in "uncompressed" GIF encoder
|
||||||
|
|
||||||
|
# Image.register_save(GifImageFile.format, _save_netpbm)
|
||||||
140
venv/lib/python3.9/site-packages/PIL/GimpGradientFile.py
Normal file
|
|
@ -0,0 +1,140 @@
|
||||||
|
#
|
||||||
|
# Python Imaging Library
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# stuff to read (and render) GIMP gradient files
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 97-08-23 fl Created
|
||||||
|
#
|
||||||
|
# Copyright (c) Secret Labs AB 1997.
|
||||||
|
# Copyright (c) Fredrik Lundh 1997.
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
"""
|
||||||
|
Stuff to translate curve segments to palette values (derived from
|
||||||
|
the corresponding code in GIMP, written by Federico Mena Quintero.
|
||||||
|
See the GIMP distribution for more information.)
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
from math import log, pi, sin, sqrt
|
||||||
|
|
||||||
|
from ._binary import o8
|
||||||
|
|
||||||
|
EPSILON = 1e-10
|
||||||
|
"""""" # Enable auto-doc for data member
|
||||||
|
|
||||||
|
|
||||||
|
def linear(middle, pos):
|
||||||
|
if pos <= middle:
|
||||||
|
if middle < EPSILON:
|
||||||
|
return 0.0
|
||||||
|
else:
|
||||||
|
return 0.5 * pos / middle
|
||||||
|
else:
|
||||||
|
pos = pos - middle
|
||||||
|
middle = 1.0 - middle
|
||||||
|
if middle < EPSILON:
|
||||||
|
return 1.0
|
||||||
|
else:
|
||||||
|
return 0.5 + 0.5 * pos / middle
|
||||||
|
|
||||||
|
|
||||||
|
def curved(middle, pos):
|
||||||
|
return pos ** (log(0.5) / log(max(middle, EPSILON)))
|
||||||
|
|
||||||
|
|
||||||
|
def sine(middle, pos):
|
||||||
|
return (sin((-pi / 2.0) + pi * linear(middle, pos)) + 1.0) / 2.0
|
||||||
|
|
||||||
|
|
||||||
|
def sphere_increasing(middle, pos):
|
||||||
|
return sqrt(1.0 - (linear(middle, pos) - 1.0) ** 2)
|
||||||
|
|
||||||
|
|
||||||
|
def sphere_decreasing(middle, pos):
|
||||||
|
return 1.0 - sqrt(1.0 - linear(middle, pos) ** 2)
|
||||||
|
|
||||||
|
|
||||||
|
SEGMENTS = [linear, curved, sine, sphere_increasing, sphere_decreasing]
|
||||||
|
"""""" # Enable auto-doc for data member
|
||||||
|
|
||||||
|
|
||||||
|
class GradientFile:
|
||||||
|
|
||||||
|
gradient = None
|
||||||
|
|
||||||
|
def getpalette(self, entries=256):
|
||||||
|
|
||||||
|
palette = []
|
||||||
|
|
||||||
|
ix = 0
|
||||||
|
x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix]
|
||||||
|
|
||||||
|
for i in range(entries):
|
||||||
|
|
||||||
|
x = i / (entries - 1)
|
||||||
|
|
||||||
|
while x1 < x:
|
||||||
|
ix += 1
|
||||||
|
x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix]
|
||||||
|
|
||||||
|
w = x1 - x0
|
||||||
|
|
||||||
|
if w < EPSILON:
|
||||||
|
scale = segment(0.5, 0.5)
|
||||||
|
else:
|
||||||
|
scale = segment((xm - x0) / w, (x - x0) / w)
|
||||||
|
|
||||||
|
# expand to RGBA
|
||||||
|
r = o8(int(255 * ((rgb1[0] - rgb0[0]) * scale + rgb0[0]) + 0.5))
|
||||||
|
g = o8(int(255 * ((rgb1[1] - rgb0[1]) * scale + rgb0[1]) + 0.5))
|
||||||
|
b = o8(int(255 * ((rgb1[2] - rgb0[2]) * scale + rgb0[2]) + 0.5))
|
||||||
|
a = o8(int(255 * ((rgb1[3] - rgb0[3]) * scale + rgb0[3]) + 0.5))
|
||||||
|
|
||||||
|
# add to palette
|
||||||
|
palette.append(r + g + b + a)
|
||||||
|
|
||||||
|
return b"".join(palette), "RGBA"
|
||||||
|
|
||||||
|
|
||||||
|
class GimpGradientFile(GradientFile):
|
||||||
|
"""File handler for GIMP's gradient format."""
|
||||||
|
|
||||||
|
def __init__(self, fp):
|
||||||
|
|
||||||
|
if fp.readline()[:13] != b"GIMP Gradient":
|
||||||
|
raise SyntaxError("not a GIMP gradient file")
|
||||||
|
|
||||||
|
line = fp.readline()
|
||||||
|
|
||||||
|
# GIMP 1.2 gradient files don't contain a name, but GIMP 1.3 files do
|
||||||
|
if line.startswith(b"Name: "):
|
||||||
|
line = fp.readline().strip()
|
||||||
|
|
||||||
|
count = int(line)
|
||||||
|
|
||||||
|
gradient = []
|
||||||
|
|
||||||
|
for i in range(count):
|
||||||
|
|
||||||
|
s = fp.readline().split()
|
||||||
|
w = [float(x) for x in s[:11]]
|
||||||
|
|
||||||
|
x0, x1 = w[0], w[2]
|
||||||
|
xm = w[1]
|
||||||
|
rgb0 = w[3:7]
|
||||||
|
rgb1 = w[7:11]
|
||||||
|
|
||||||
|
segment = SEGMENTS[int(s[11])]
|
||||||
|
cspace = int(s[12])
|
||||||
|
|
||||||
|
if cspace != 0:
|
||||||
|
raise OSError("cannot handle HSV colour space")
|
||||||
|
|
||||||
|
gradient.append((x0, x1, xm, rgb0, rgb1, segment))
|
||||||
|
|
||||||
|
self.gradient = gradient
|
||||||
56
venv/lib/python3.9/site-packages/PIL/GimpPaletteFile.py
Normal file
|
|
@ -0,0 +1,56 @@
|
||||||
|
#
|
||||||
|
# Python Imaging Library
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# stuff to read GIMP palette files
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 1997-08-23 fl Created
|
||||||
|
# 2004-09-07 fl Support GIMP 2.0 palette files.
|
||||||
|
#
|
||||||
|
# Copyright (c) Secret Labs AB 1997-2004. All rights reserved.
|
||||||
|
# Copyright (c) Fredrik Lundh 1997-2004.
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
|
from ._binary import o8
|
||||||
|
|
||||||
|
|
||||||
|
class GimpPaletteFile:
|
||||||
|
"""File handler for GIMP's palette format."""
|
||||||
|
|
||||||
|
rawmode = "RGB"
|
||||||
|
|
||||||
|
def __init__(self, fp):
|
||||||
|
|
||||||
|
self.palette = [o8(i) * 3 for i in range(256)]
|
||||||
|
|
||||||
|
if fp.readline()[:12] != b"GIMP Palette":
|
||||||
|
raise SyntaxError("not a GIMP palette file")
|
||||||
|
|
||||||
|
for i in range(256):
|
||||||
|
|
||||||
|
s = fp.readline()
|
||||||
|
if not s:
|
||||||
|
break
|
||||||
|
|
||||||
|
# skip fields and comment lines
|
||||||
|
if re.match(br"\w+:|#", s):
|
||||||
|
continue
|
||||||
|
if len(s) > 100:
|
||||||
|
raise SyntaxError("bad palette file")
|
||||||
|
|
||||||
|
v = tuple(map(int, s.split()[:3]))
|
||||||
|
if len(v) != 3:
|
||||||
|
raise ValueError("bad palette entry")
|
||||||
|
|
||||||
|
self.palette[i] = o8(v[0]) + o8(v[1]) + o8(v[2])
|
||||||
|
|
||||||
|
self.palette = b"".join(self.palette)
|
||||||
|
|
||||||
|
def getpalette(self):
|
||||||
|
|
||||||
|
return self.palette, self.rawmode
|
||||||
74
venv/lib/python3.9/site-packages/PIL/GribStubImagePlugin.py
Normal file
|
|
@ -0,0 +1,74 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# GRIB stub adapter
|
||||||
|
#
|
||||||
|
# Copyright (c) 1996-2003 by Fredrik Lundh
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
from . import Image, ImageFile
|
||||||
|
from ._binary import i8
|
||||||
|
|
||||||
|
_handler = None
|
||||||
|
|
||||||
|
|
||||||
|
def register_handler(handler):
|
||||||
|
"""
|
||||||
|
Install application-specific GRIB image handler.
|
||||||
|
|
||||||
|
:param handler: Handler object.
|
||||||
|
"""
|
||||||
|
global _handler
|
||||||
|
_handler = handler
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# Image adapter
|
||||||
|
|
||||||
|
|
||||||
|
def _accept(prefix):
|
||||||
|
return prefix[0:4] == b"GRIB" and i8(prefix[7]) == 1
|
||||||
|
|
||||||
|
|
||||||
|
class GribStubImageFile(ImageFile.StubImageFile):
|
||||||
|
|
||||||
|
format = "GRIB"
|
||||||
|
format_description = "GRIB"
|
||||||
|
|
||||||
|
def _open(self):
|
||||||
|
|
||||||
|
offset = self.fp.tell()
|
||||||
|
|
||||||
|
if not _accept(self.fp.read(8)):
|
||||||
|
raise SyntaxError("Not a GRIB file")
|
||||||
|
|
||||||
|
self.fp.seek(offset)
|
||||||
|
|
||||||
|
# make something up
|
||||||
|
self.mode = "F"
|
||||||
|
self._size = 1, 1
|
||||||
|
|
||||||
|
loader = self._load()
|
||||||
|
if loader:
|
||||||
|
loader.open(self)
|
||||||
|
|
||||||
|
def _load(self):
|
||||||
|
return _handler
|
||||||
|
|
||||||
|
|
||||||
|
def _save(im, fp, filename):
|
||||||
|
if _handler is None or not hasattr("_handler", "save"):
|
||||||
|
raise OSError("GRIB save handler not installed")
|
||||||
|
_handler.save(im, fp, filename)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# Registry
|
||||||
|
|
||||||
|
Image.register_open(GribStubImageFile.format, GribStubImageFile, _accept)
|
||||||
|
Image.register_save(GribStubImageFile.format, _save)
|
||||||
|
|
||||||
|
Image.register_extension(GribStubImageFile.format, ".grib")
|
||||||
73
venv/lib/python3.9/site-packages/PIL/Hdf5StubImagePlugin.py
Normal file
|
|
@ -0,0 +1,73 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# HDF5 stub adapter
|
||||||
|
#
|
||||||
|
# Copyright (c) 2000-2003 by Fredrik Lundh
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
from . import Image, ImageFile
|
||||||
|
|
||||||
|
_handler = None
|
||||||
|
|
||||||
|
|
||||||
|
def register_handler(handler):
|
||||||
|
"""
|
||||||
|
Install application-specific HDF5 image handler.
|
||||||
|
|
||||||
|
:param handler: Handler object.
|
||||||
|
"""
|
||||||
|
global _handler
|
||||||
|
_handler = handler
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# Image adapter
|
||||||
|
|
||||||
|
|
||||||
|
def _accept(prefix):
|
||||||
|
return prefix[:8] == b"\x89HDF\r\n\x1a\n"
|
||||||
|
|
||||||
|
|
||||||
|
class HDF5StubImageFile(ImageFile.StubImageFile):
|
||||||
|
|
||||||
|
format = "HDF5"
|
||||||
|
format_description = "HDF5"
|
||||||
|
|
||||||
|
def _open(self):
|
||||||
|
|
||||||
|
offset = self.fp.tell()
|
||||||
|
|
||||||
|
if not _accept(self.fp.read(8)):
|
||||||
|
raise SyntaxError("Not an HDF file")
|
||||||
|
|
||||||
|
self.fp.seek(offset)
|
||||||
|
|
||||||
|
# make something up
|
||||||
|
self.mode = "F"
|
||||||
|
self._size = 1, 1
|
||||||
|
|
||||||
|
loader = self._load()
|
||||||
|
if loader:
|
||||||
|
loader.open(self)
|
||||||
|
|
||||||
|
def _load(self):
|
||||||
|
return _handler
|
||||||
|
|
||||||
|
|
||||||
|
def _save(im, fp, filename):
|
||||||
|
if _handler is None or not hasattr("_handler", "save"):
|
||||||
|
raise OSError("HDF5 save handler not installed")
|
||||||
|
_handler.save(im, fp, filename)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# Registry
|
||||||
|
|
||||||
|
Image.register_open(HDF5StubImageFile.format, HDF5StubImageFile, _accept)
|
||||||
|
Image.register_save(HDF5StubImageFile.format, _save)
|
||||||
|
|
||||||
|
Image.register_extensions(HDF5StubImageFile.format, [".h5", ".hdf"])
|
||||||
384
venv/lib/python3.9/site-packages/PIL/IcnsImagePlugin.py
Normal file
|
|
@ -0,0 +1,384 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library.
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# macOS icns file decoder, based on icns.py by Bob Ippolito.
|
||||||
|
#
|
||||||
|
# history:
|
||||||
|
# 2004-10-09 fl Turned into a PIL plugin; removed 2.3 dependencies.
|
||||||
|
#
|
||||||
|
# Copyright (c) 2004 by Bob Ippolito.
|
||||||
|
# Copyright (c) 2004 by Secret Labs.
|
||||||
|
# Copyright (c) 2004 by Fredrik Lundh.
|
||||||
|
# Copyright (c) 2014 by Alastair Houghton.
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import struct
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
from PIL import Image, ImageFile, PngImagePlugin, features
|
||||||
|
from PIL._binary import i8
|
||||||
|
|
||||||
|
enable_jpeg2k = features.check_codec("jpg_2000")
|
||||||
|
if enable_jpeg2k:
|
||||||
|
from PIL import Jpeg2KImagePlugin
|
||||||
|
|
||||||
|
HEADERSIZE = 8
|
||||||
|
|
||||||
|
|
||||||
|
def nextheader(fobj):
|
||||||
|
return struct.unpack(">4sI", fobj.read(HEADERSIZE))
|
||||||
|
|
||||||
|
|
||||||
|
def read_32t(fobj, start_length, size):
|
||||||
|
# The 128x128 icon seems to have an extra header for some reason.
|
||||||
|
(start, length) = start_length
|
||||||
|
fobj.seek(start)
|
||||||
|
sig = fobj.read(4)
|
||||||
|
if sig != b"\x00\x00\x00\x00":
|
||||||
|
raise SyntaxError("Unknown signature, expecting 0x00000000")
|
||||||
|
return read_32(fobj, (start + 4, length - 4), size)
|
||||||
|
|
||||||
|
|
||||||
|
def read_32(fobj, start_length, size):
|
||||||
|
"""
|
||||||
|
Read a 32bit RGB icon resource. Seems to be either uncompressed or
|
||||||
|
an RLE packbits-like scheme.
|
||||||
|
"""
|
||||||
|
(start, length) = start_length
|
||||||
|
fobj.seek(start)
|
||||||
|
pixel_size = (size[0] * size[2], size[1] * size[2])
|
||||||
|
sizesq = pixel_size[0] * pixel_size[1]
|
||||||
|
if length == sizesq * 3:
|
||||||
|
# uncompressed ("RGBRGBGB")
|
||||||
|
indata = fobj.read(length)
|
||||||
|
im = Image.frombuffer("RGB", pixel_size, indata, "raw", "RGB", 0, 1)
|
||||||
|
else:
|
||||||
|
# decode image
|
||||||
|
im = Image.new("RGB", pixel_size, None)
|
||||||
|
for band_ix in range(3):
|
||||||
|
data = []
|
||||||
|
bytesleft = sizesq
|
||||||
|
while bytesleft > 0:
|
||||||
|
byte = fobj.read(1)
|
||||||
|
if not byte:
|
||||||
|
break
|
||||||
|
byte = i8(byte)
|
||||||
|
if byte & 0x80:
|
||||||
|
blocksize = byte - 125
|
||||||
|
byte = fobj.read(1)
|
||||||
|
for i in range(blocksize):
|
||||||
|
data.append(byte)
|
||||||
|
else:
|
||||||
|
blocksize = byte + 1
|
||||||
|
data.append(fobj.read(blocksize))
|
||||||
|
bytesleft -= blocksize
|
||||||
|
if bytesleft <= 0:
|
||||||
|
break
|
||||||
|
if bytesleft != 0:
|
||||||
|
raise SyntaxError(f"Error reading channel [{repr(bytesleft)} left]")
|
||||||
|
band = Image.frombuffer("L", pixel_size, b"".join(data), "raw", "L", 0, 1)
|
||||||
|
im.im.putband(band.im, band_ix)
|
||||||
|
return {"RGB": im}
|
||||||
|
|
||||||
|
|
||||||
|
def read_mk(fobj, start_length, size):
|
||||||
|
# Alpha masks seem to be uncompressed
|
||||||
|
start = start_length[0]
|
||||||
|
fobj.seek(start)
|
||||||
|
pixel_size = (size[0] * size[2], size[1] * size[2])
|
||||||
|
sizesq = pixel_size[0] * pixel_size[1]
|
||||||
|
band = Image.frombuffer("L", pixel_size, fobj.read(sizesq), "raw", "L", 0, 1)
|
||||||
|
return {"A": band}
|
||||||
|
|
||||||
|
|
||||||
|
def read_png_or_jpeg2000(fobj, start_length, size):
|
||||||
|
(start, length) = start_length
|
||||||
|
fobj.seek(start)
|
||||||
|
sig = fobj.read(12)
|
||||||
|
if sig[:8] == b"\x89PNG\x0d\x0a\x1a\x0a":
|
||||||
|
fobj.seek(start)
|
||||||
|
im = PngImagePlugin.PngImageFile(fobj)
|
||||||
|
return {"RGBA": im}
|
||||||
|
elif (
|
||||||
|
sig[:4] == b"\xff\x4f\xff\x51"
|
||||||
|
or sig[:4] == b"\x0d\x0a\x87\x0a"
|
||||||
|
or sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a"
|
||||||
|
):
|
||||||
|
if not enable_jpeg2k:
|
||||||
|
raise ValueError(
|
||||||
|
"Unsupported icon subimage format (rebuild PIL "
|
||||||
|
"with JPEG 2000 support to fix this)"
|
||||||
|
)
|
||||||
|
# j2k, jpc or j2c
|
||||||
|
fobj.seek(start)
|
||||||
|
jp2kstream = fobj.read(length)
|
||||||
|
f = io.BytesIO(jp2kstream)
|
||||||
|
im = Jpeg2KImagePlugin.Jpeg2KImageFile(f)
|
||||||
|
if im.mode != "RGBA":
|
||||||
|
im = im.convert("RGBA")
|
||||||
|
return {"RGBA": im}
|
||||||
|
else:
|
||||||
|
raise ValueError("Unsupported icon subimage format")
|
||||||
|
|
||||||
|
|
||||||
|
class IcnsFile:
|
||||||
|
|
||||||
|
SIZES = {
|
||||||
|
(512, 512, 2): [(b"ic10", read_png_or_jpeg2000)],
|
||||||
|
(512, 512, 1): [(b"ic09", read_png_or_jpeg2000)],
|
||||||
|
(256, 256, 2): [(b"ic14", read_png_or_jpeg2000)],
|
||||||
|
(256, 256, 1): [(b"ic08", read_png_or_jpeg2000)],
|
||||||
|
(128, 128, 2): [(b"ic13", read_png_or_jpeg2000)],
|
||||||
|
(128, 128, 1): [
|
||||||
|
(b"ic07", read_png_or_jpeg2000),
|
||||||
|
(b"it32", read_32t),
|
||||||
|
(b"t8mk", read_mk),
|
||||||
|
],
|
||||||
|
(64, 64, 1): [(b"icp6", read_png_or_jpeg2000)],
|
||||||
|
(32, 32, 2): [(b"ic12", read_png_or_jpeg2000)],
|
||||||
|
(48, 48, 1): [(b"ih32", read_32), (b"h8mk", read_mk)],
|
||||||
|
(32, 32, 1): [
|
||||||
|
(b"icp5", read_png_or_jpeg2000),
|
||||||
|
(b"il32", read_32),
|
||||||
|
(b"l8mk", read_mk),
|
||||||
|
],
|
||||||
|
(16, 16, 2): [(b"ic11", read_png_or_jpeg2000)],
|
||||||
|
(16, 16, 1): [
|
||||||
|
(b"icp4", read_png_or_jpeg2000),
|
||||||
|
(b"is32", read_32),
|
||||||
|
(b"s8mk", read_mk),
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
def __init__(self, fobj):
|
||||||
|
"""
|
||||||
|
fobj is a file-like object as an icns resource
|
||||||
|
"""
|
||||||
|
# signature : (start, length)
|
||||||
|
self.dct = dct = {}
|
||||||
|
self.fobj = fobj
|
||||||
|
sig, filesize = nextheader(fobj)
|
||||||
|
if sig != b"icns":
|
||||||
|
raise SyntaxError("not an icns file")
|
||||||
|
i = HEADERSIZE
|
||||||
|
while i < filesize:
|
||||||
|
sig, blocksize = nextheader(fobj)
|
||||||
|
if blocksize <= 0:
|
||||||
|
raise SyntaxError("invalid block header")
|
||||||
|
i += HEADERSIZE
|
||||||
|
blocksize -= HEADERSIZE
|
||||||
|
dct[sig] = (i, blocksize)
|
||||||
|
fobj.seek(blocksize, io.SEEK_CUR)
|
||||||
|
i += blocksize
|
||||||
|
|
||||||
|
def itersizes(self):
|
||||||
|
sizes = []
|
||||||
|
for size, fmts in self.SIZES.items():
|
||||||
|
for (fmt, reader) in fmts:
|
||||||
|
if fmt in self.dct:
|
||||||
|
sizes.append(size)
|
||||||
|
break
|
||||||
|
return sizes
|
||||||
|
|
||||||
|
def bestsize(self):
|
||||||
|
sizes = self.itersizes()
|
||||||
|
if not sizes:
|
||||||
|
raise SyntaxError("No 32bit icon resources found")
|
||||||
|
return max(sizes)
|
||||||
|
|
||||||
|
def dataforsize(self, size):
|
||||||
|
"""
|
||||||
|
Get an icon resource as {channel: array}. Note that
|
||||||
|
the arrays are bottom-up like windows bitmaps and will likely
|
||||||
|
need to be flipped or transposed in some way.
|
||||||
|
"""
|
||||||
|
dct = {}
|
||||||
|
for code, reader in self.SIZES[size]:
|
||||||
|
desc = self.dct.get(code)
|
||||||
|
if desc is not None:
|
||||||
|
dct.update(reader(self.fobj, desc, size))
|
||||||
|
return dct
|
||||||
|
|
||||||
|
def getimage(self, size=None):
|
||||||
|
if size is None:
|
||||||
|
size = self.bestsize()
|
||||||
|
if len(size) == 2:
|
||||||
|
size = (size[0], size[1], 1)
|
||||||
|
channels = self.dataforsize(size)
|
||||||
|
|
||||||
|
im = channels.get("RGBA", None)
|
||||||
|
if im:
|
||||||
|
return im
|
||||||
|
|
||||||
|
im = channels.get("RGB").copy()
|
||||||
|
try:
|
||||||
|
im.putalpha(channels["A"])
|
||||||
|
except KeyError:
|
||||||
|
pass
|
||||||
|
return im
|
||||||
|
|
||||||
|
|
||||||
|
##
|
||||||
|
# Image plugin for Mac OS icons.
|
||||||
|
|
||||||
|
|
||||||
|
class IcnsImageFile(ImageFile.ImageFile):
|
||||||
|
"""
|
||||||
|
PIL image support for Mac OS .icns files.
|
||||||
|
Chooses the best resolution, but will possibly load
|
||||||
|
a different size image if you mutate the size attribute
|
||||||
|
before calling 'load'.
|
||||||
|
|
||||||
|
The info dictionary has a key 'sizes' that is a list
|
||||||
|
of sizes that the icns file has.
|
||||||
|
"""
|
||||||
|
|
||||||
|
format = "ICNS"
|
||||||
|
format_description = "Mac OS icns resource"
|
||||||
|
|
||||||
|
def _open(self):
|
||||||
|
self.icns = IcnsFile(self.fp)
|
||||||
|
self.mode = "RGBA"
|
||||||
|
self.info["sizes"] = self.icns.itersizes()
|
||||||
|
self.best_size = self.icns.bestsize()
|
||||||
|
self.size = (
|
||||||
|
self.best_size[0] * self.best_size[2],
|
||||||
|
self.best_size[1] * self.best_size[2],
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def size(self):
|
||||||
|
return self._size
|
||||||
|
|
||||||
|
@size.setter
|
||||||
|
def size(self, value):
|
||||||
|
info_size = value
|
||||||
|
if info_size not in self.info["sizes"] and len(info_size) == 2:
|
||||||
|
info_size = (info_size[0], info_size[1], 1)
|
||||||
|
if (
|
||||||
|
info_size not in self.info["sizes"]
|
||||||
|
and len(info_size) == 3
|
||||||
|
and info_size[2] == 1
|
||||||
|
):
|
||||||
|
simple_sizes = [
|
||||||
|
(size[0] * size[2], size[1] * size[2]) for size in self.info["sizes"]
|
||||||
|
]
|
||||||
|
if value in simple_sizes:
|
||||||
|
info_size = self.info["sizes"][simple_sizes.index(value)]
|
||||||
|
if info_size not in self.info["sizes"]:
|
||||||
|
raise ValueError("This is not one of the allowed sizes of this image")
|
||||||
|
self._size = value
|
||||||
|
|
||||||
|
def load(self):
|
||||||
|
if len(self.size) == 3:
|
||||||
|
self.best_size = self.size
|
||||||
|
self.size = (
|
||||||
|
self.best_size[0] * self.best_size[2],
|
||||||
|
self.best_size[1] * self.best_size[2],
|
||||||
|
)
|
||||||
|
|
||||||
|
Image.Image.load(self)
|
||||||
|
if self.im and self.im.size == self.size:
|
||||||
|
# Already loaded
|
||||||
|
return
|
||||||
|
self.load_prepare()
|
||||||
|
# This is likely NOT the best way to do it, but whatever.
|
||||||
|
im = self.icns.getimage(self.best_size)
|
||||||
|
|
||||||
|
# If this is a PNG or JPEG 2000, it won't be loaded yet
|
||||||
|
im.load()
|
||||||
|
|
||||||
|
self.im = im.im
|
||||||
|
self.mode = im.mode
|
||||||
|
self.size = im.size
|
||||||
|
self.load_end()
|
||||||
|
|
||||||
|
|
||||||
|
def _save(im, fp, filename):
|
||||||
|
"""
|
||||||
|
Saves the image as a series of PNG files,
|
||||||
|
that are then converted to a .icns file
|
||||||
|
using the macOS command line utility 'iconutil'.
|
||||||
|
|
||||||
|
macOS only.
|
||||||
|
"""
|
||||||
|
if hasattr(fp, "flush"):
|
||||||
|
fp.flush()
|
||||||
|
|
||||||
|
# create the temporary set of pngs
|
||||||
|
with tempfile.TemporaryDirectory(".iconset") as iconset:
|
||||||
|
provided_images = {
|
||||||
|
im.width: im for im in im.encoderinfo.get("append_images", [])
|
||||||
|
}
|
||||||
|
last_w = None
|
||||||
|
second_path = None
|
||||||
|
for w in [16, 32, 128, 256, 512]:
|
||||||
|
prefix = f"icon_{w}x{w}"
|
||||||
|
|
||||||
|
first_path = os.path.join(iconset, prefix + ".png")
|
||||||
|
if last_w == w:
|
||||||
|
shutil.copyfile(second_path, first_path)
|
||||||
|
else:
|
||||||
|
im_w = provided_images.get(w, im.resize((w, w), Image.LANCZOS))
|
||||||
|
im_w.save(first_path)
|
||||||
|
|
||||||
|
second_path = os.path.join(iconset, prefix + "@2x.png")
|
||||||
|
im_w2 = provided_images.get(w * 2, im.resize((w * 2, w * 2), Image.LANCZOS))
|
||||||
|
im_w2.save(second_path)
|
||||||
|
last_w = w * 2
|
||||||
|
|
||||||
|
# iconutil -c icns -o {} {}
|
||||||
|
|
||||||
|
fp_only = not filename
|
||||||
|
if fp_only:
|
||||||
|
f, filename = tempfile.mkstemp(".icns")
|
||||||
|
os.close(f)
|
||||||
|
convert_cmd = ["iconutil", "-c", "icns", "-o", filename, iconset]
|
||||||
|
convert_proc = subprocess.Popen(
|
||||||
|
convert_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL
|
||||||
|
)
|
||||||
|
|
||||||
|
convert_proc.stdout.close()
|
||||||
|
|
||||||
|
retcode = convert_proc.wait()
|
||||||
|
|
||||||
|
if retcode:
|
||||||
|
raise subprocess.CalledProcessError(retcode, convert_cmd)
|
||||||
|
|
||||||
|
if fp_only:
|
||||||
|
with open(filename, "rb") as f:
|
||||||
|
fp.write(f.read())
|
||||||
|
|
||||||
|
|
||||||
|
Image.register_open(IcnsImageFile.format, IcnsImageFile, lambda x: x[:4] == b"icns")
|
||||||
|
Image.register_extension(IcnsImageFile.format, ".icns")
|
||||||
|
|
||||||
|
if sys.platform == "darwin":
|
||||||
|
Image.register_save(IcnsImageFile.format, _save)
|
||||||
|
|
||||||
|
Image.register_mime(IcnsImageFile.format, "image/icns")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
if len(sys.argv) < 2:
|
||||||
|
print("Syntax: python IcnsImagePlugin.py [file]")
|
||||||
|
sys.exit()
|
||||||
|
|
||||||
|
with open(sys.argv[1], "rb") as fp:
|
||||||
|
imf = IcnsImageFile(fp)
|
||||||
|
for size in imf.info["sizes"]:
|
||||||
|
imf.size = size
|
||||||
|
imf.save("out-%s-%s-%s.png" % size)
|
||||||
|
with Image.open(sys.argv[1]) as im:
|
||||||
|
im.save("out.png")
|
||||||
|
if sys.platform == "windows":
|
||||||
|
os.startfile("out.png")
|
||||||
326
venv/lib/python3.9/site-packages/PIL/IcoImagePlugin.py
Normal file
|
|
@ -0,0 +1,326 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library.
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# Windows Icon support for PIL
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 96-05-27 fl Created
|
||||||
|
#
|
||||||
|
# Copyright (c) Secret Labs AB 1997.
|
||||||
|
# Copyright (c) Fredrik Lundh 1996.
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
# This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis
|
||||||
|
# <casadebender@gmail.com>.
|
||||||
|
# https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
|
||||||
|
#
|
||||||
|
# Icon format references:
|
||||||
|
# * https://en.wikipedia.org/wiki/ICO_(file_format)
|
||||||
|
# * https://msdn.microsoft.com/en-us/library/ms997538.aspx
|
||||||
|
|
||||||
|
|
||||||
|
import struct
|
||||||
|
import warnings
|
||||||
|
from io import BytesIO
|
||||||
|
from math import ceil, log
|
||||||
|
|
||||||
|
from . import BmpImagePlugin, Image, ImageFile, PngImagePlugin
|
||||||
|
from ._binary import i8
|
||||||
|
from ._binary import i16le as i16
|
||||||
|
from ._binary import i32le as i32
|
||||||
|
|
||||||
|
#
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
|
||||||
|
_MAGIC = b"\0\0\1\0"
|
||||||
|
|
||||||
|
|
||||||
|
def _save(im, fp, filename):
|
||||||
|
fp.write(_MAGIC) # (2+2)
|
||||||
|
sizes = im.encoderinfo.get(
|
||||||
|
"sizes",
|
||||||
|
[(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)],
|
||||||
|
)
|
||||||
|
width, height = im.size
|
||||||
|
sizes = filter(
|
||||||
|
lambda x: False
|
||||||
|
if (x[0] > width or x[1] > height or x[0] > 256 or x[1] > 256)
|
||||||
|
else True,
|
||||||
|
sizes,
|
||||||
|
)
|
||||||
|
sizes = list(sizes)
|
||||||
|
fp.write(struct.pack("<H", len(sizes))) # idCount(2)
|
||||||
|
offset = fp.tell() + len(sizes) * 16
|
||||||
|
for size in sizes:
|
||||||
|
width, height = size
|
||||||
|
# 0 means 256
|
||||||
|
fp.write(struct.pack("B", width if width < 256 else 0)) # bWidth(1)
|
||||||
|
fp.write(struct.pack("B", height if height < 256 else 0)) # bHeight(1)
|
||||||
|
fp.write(b"\0") # bColorCount(1)
|
||||||
|
fp.write(b"\0") # bReserved(1)
|
||||||
|
fp.write(b"\0\0") # wPlanes(2)
|
||||||
|
fp.write(struct.pack("<H", 32)) # wBitCount(2)
|
||||||
|
|
||||||
|
image_io = BytesIO()
|
||||||
|
# TODO: invent a more convenient method for proportional scalings
|
||||||
|
tmp = im.copy()
|
||||||
|
tmp.thumbnail(size, Image.LANCZOS, reducing_gap=None)
|
||||||
|
tmp.save(image_io, "png")
|
||||||
|
image_io.seek(0)
|
||||||
|
image_bytes = image_io.read()
|
||||||
|
bytes_len = len(image_bytes)
|
||||||
|
fp.write(struct.pack("<I", bytes_len)) # dwBytesInRes(4)
|
||||||
|
fp.write(struct.pack("<I", offset)) # dwImageOffset(4)
|
||||||
|
current = fp.tell()
|
||||||
|
fp.seek(offset)
|
||||||
|
fp.write(image_bytes)
|
||||||
|
offset = offset + bytes_len
|
||||||
|
fp.seek(current)
|
||||||
|
|
||||||
|
|
||||||
|
def _accept(prefix):
|
||||||
|
return prefix[:4] == _MAGIC
|
||||||
|
|
||||||
|
|
||||||
|
class IcoFile:
|
||||||
|
def __init__(self, buf):
|
||||||
|
"""
|
||||||
|
Parse image from file-like object containing ico file data
|
||||||
|
"""
|
||||||
|
|
||||||
|
# check magic
|
||||||
|
s = buf.read(6)
|
||||||
|
if not _accept(s):
|
||||||
|
raise SyntaxError("not an ICO file")
|
||||||
|
|
||||||
|
self.buf = buf
|
||||||
|
self.entry = []
|
||||||
|
|
||||||
|
# Number of items in file
|
||||||
|
self.nb_items = i16(s[4:])
|
||||||
|
|
||||||
|
# Get headers for each item
|
||||||
|
for i in range(self.nb_items):
|
||||||
|
s = buf.read(16)
|
||||||
|
|
||||||
|
icon_header = {
|
||||||
|
"width": i8(s[0]),
|
||||||
|
"height": i8(s[1]),
|
||||||
|
"nb_color": i8(s[2]), # No. of colors in image (0 if >=8bpp)
|
||||||
|
"reserved": i8(s[3]),
|
||||||
|
"planes": i16(s[4:]),
|
||||||
|
"bpp": i16(s[6:]),
|
||||||
|
"size": i32(s[8:]),
|
||||||
|
"offset": i32(s[12:]),
|
||||||
|
}
|
||||||
|
|
||||||
|
# See Wikipedia
|
||||||
|
for j in ("width", "height"):
|
||||||
|
if not icon_header[j]:
|
||||||
|
icon_header[j] = 256
|
||||||
|
|
||||||
|
# See Wikipedia notes about color depth.
|
||||||
|
# We need this just to differ images with equal sizes
|
||||||
|
icon_header["color_depth"] = (
|
||||||
|
icon_header["bpp"]
|
||||||
|
or (
|
||||||
|
icon_header["nb_color"] != 0
|
||||||
|
and ceil(log(icon_header["nb_color"], 2))
|
||||||
|
)
|
||||||
|
or 256
|
||||||
|
)
|
||||||
|
|
||||||
|
icon_header["dim"] = (icon_header["width"], icon_header["height"])
|
||||||
|
icon_header["square"] = icon_header["width"] * icon_header["height"]
|
||||||
|
|
||||||
|
self.entry.append(icon_header)
|
||||||
|
|
||||||
|
self.entry = sorted(self.entry, key=lambda x: x["color_depth"])
|
||||||
|
# ICO images are usually squares
|
||||||
|
# self.entry = sorted(self.entry, key=lambda x: x['width'])
|
||||||
|
self.entry = sorted(self.entry, key=lambda x: x["square"])
|
||||||
|
self.entry.reverse()
|
||||||
|
|
||||||
|
def sizes(self):
|
||||||
|
"""
|
||||||
|
Get a list of all available icon sizes and color depths.
|
||||||
|
"""
|
||||||
|
return {(h["width"], h["height"]) for h in self.entry}
|
||||||
|
|
||||||
|
def getentryindex(self, size, bpp=False):
|
||||||
|
for (i, h) in enumerate(self.entry):
|
||||||
|
if size == h["dim"] and (bpp is False or bpp == h["color_depth"]):
|
||||||
|
return i
|
||||||
|
return 0
|
||||||
|
|
||||||
|
def getimage(self, size, bpp=False):
|
||||||
|
"""
|
||||||
|
Get an image from the icon
|
||||||
|
"""
|
||||||
|
return self.frame(self.getentryindex(size, bpp))
|
||||||
|
|
||||||
|
def frame(self, idx):
|
||||||
|
"""
|
||||||
|
Get an image from frame idx
|
||||||
|
"""
|
||||||
|
|
||||||
|
header = self.entry[idx]
|
||||||
|
|
||||||
|
self.buf.seek(header["offset"])
|
||||||
|
data = self.buf.read(8)
|
||||||
|
self.buf.seek(header["offset"])
|
||||||
|
|
||||||
|
if data[:8] == PngImagePlugin._MAGIC:
|
||||||
|
# png frame
|
||||||
|
im = PngImagePlugin.PngImageFile(self.buf)
|
||||||
|
else:
|
||||||
|
# XOR + AND mask bmp frame
|
||||||
|
im = BmpImagePlugin.DibImageFile(self.buf)
|
||||||
|
Image._decompression_bomb_check(im.size)
|
||||||
|
|
||||||
|
# change tile dimension to only encompass XOR image
|
||||||
|
im._size = (im.size[0], int(im.size[1] / 2))
|
||||||
|
d, e, o, a = im.tile[0]
|
||||||
|
im.tile[0] = d, (0, 0) + im.size, o, a
|
||||||
|
|
||||||
|
# figure out where AND mask image starts
|
||||||
|
mode = a[0]
|
||||||
|
bpp = 8
|
||||||
|
for k, v in BmpImagePlugin.BIT2MODE.items():
|
||||||
|
if mode == v[1]:
|
||||||
|
bpp = k
|
||||||
|
break
|
||||||
|
|
||||||
|
if 32 == bpp:
|
||||||
|
# 32-bit color depth icon image allows semitransparent areas
|
||||||
|
# PIL's DIB format ignores transparency bits, recover them.
|
||||||
|
# The DIB is packed in BGRX byte order where X is the alpha
|
||||||
|
# channel.
|
||||||
|
|
||||||
|
# Back up to start of bmp data
|
||||||
|
self.buf.seek(o)
|
||||||
|
# extract every 4th byte (eg. 3,7,11,15,...)
|
||||||
|
alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4]
|
||||||
|
|
||||||
|
# convert to an 8bpp grayscale image
|
||||||
|
mask = Image.frombuffer(
|
||||||
|
"L", # 8bpp
|
||||||
|
im.size, # (w, h)
|
||||||
|
alpha_bytes, # source chars
|
||||||
|
"raw", # raw decoder
|
||||||
|
("L", 0, -1), # 8bpp inverted, unpadded, reversed
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# get AND image from end of bitmap
|
||||||
|
w = im.size[0]
|
||||||
|
if (w % 32) > 0:
|
||||||
|
# bitmap row data is aligned to word boundaries
|
||||||
|
w += 32 - (im.size[0] % 32)
|
||||||
|
|
||||||
|
# the total mask data is
|
||||||
|
# padded row size * height / bits per char
|
||||||
|
|
||||||
|
and_mask_offset = o + int(im.size[0] * im.size[1] * (bpp / 8.0))
|
||||||
|
total_bytes = int((w * im.size[1]) / 8)
|
||||||
|
|
||||||
|
self.buf.seek(and_mask_offset)
|
||||||
|
mask_data = self.buf.read(total_bytes)
|
||||||
|
|
||||||
|
# convert raw data to image
|
||||||
|
mask = Image.frombuffer(
|
||||||
|
"1", # 1 bpp
|
||||||
|
im.size, # (w, h)
|
||||||
|
mask_data, # source chars
|
||||||
|
"raw", # raw decoder
|
||||||
|
("1;I", int(w / 8), -1), # 1bpp inverted, padded, reversed
|
||||||
|
)
|
||||||
|
|
||||||
|
# now we have two images, im is XOR image and mask is AND image
|
||||||
|
|
||||||
|
# apply mask image as alpha channel
|
||||||
|
im = im.convert("RGBA")
|
||||||
|
im.putalpha(mask)
|
||||||
|
|
||||||
|
return im
|
||||||
|
|
||||||
|
|
||||||
|
##
|
||||||
|
# Image plugin for Windows Icon files.
|
||||||
|
|
||||||
|
|
||||||
|
class IcoImageFile(ImageFile.ImageFile):
|
||||||
|
"""
|
||||||
|
PIL read-only image support for Microsoft Windows .ico files.
|
||||||
|
|
||||||
|
By default the largest resolution image in the file will be loaded. This
|
||||||
|
can be changed by altering the 'size' attribute before calling 'load'.
|
||||||
|
|
||||||
|
The info dictionary has a key 'sizes' that is a list of the sizes available
|
||||||
|
in the icon file.
|
||||||
|
|
||||||
|
Handles classic, XP and Vista icon formats.
|
||||||
|
|
||||||
|
When saving, PNG compression is used. Support for this was only added in
|
||||||
|
Windows Vista.
|
||||||
|
|
||||||
|
This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis
|
||||||
|
<casadebender@gmail.com>.
|
||||||
|
https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
|
||||||
|
"""
|
||||||
|
|
||||||
|
format = "ICO"
|
||||||
|
format_description = "Windows Icon"
|
||||||
|
|
||||||
|
def _open(self):
|
||||||
|
self.ico = IcoFile(self.fp)
|
||||||
|
self.info["sizes"] = self.ico.sizes()
|
||||||
|
self.size = self.ico.entry[0]["dim"]
|
||||||
|
self.load()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def size(self):
|
||||||
|
return self._size
|
||||||
|
|
||||||
|
@size.setter
|
||||||
|
def size(self, value):
|
||||||
|
if value not in self.info["sizes"]:
|
||||||
|
raise ValueError("This is not one of the allowed sizes of this image")
|
||||||
|
self._size = value
|
||||||
|
|
||||||
|
def load(self):
|
||||||
|
if self.im and self.im.size == self.size:
|
||||||
|
# Already loaded
|
||||||
|
return
|
||||||
|
im = self.ico.getimage(self.size)
|
||||||
|
# if tile is PNG, it won't really be loaded yet
|
||||||
|
im.load()
|
||||||
|
self.im = im.im
|
||||||
|
self.mode = im.mode
|
||||||
|
if im.size != self.size:
|
||||||
|
warnings.warn("Image was not the expected size")
|
||||||
|
|
||||||
|
index = self.ico.getentryindex(self.size)
|
||||||
|
sizes = list(self.info["sizes"])
|
||||||
|
sizes[index] = im.size
|
||||||
|
self.info["sizes"] = set(sizes)
|
||||||
|
|
||||||
|
self.size = im.size
|
||||||
|
|
||||||
|
def load_seek(self):
|
||||||
|
# Flag the ImageFile.Parser so that it
|
||||||
|
# just does all the decode at the end.
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
Image.register_open(IcoImageFile.format, IcoImageFile, _accept)
|
||||||
|
Image.register_save(IcoImageFile.format, _save)
|
||||||
|
Image.register_extension(IcoImageFile.format, ".ico")
|
||||||
|
|
||||||
|
Image.register_mime(IcoImageFile.format, "image/x-icon")
|
||||||
377
venv/lib/python3.9/site-packages/PIL/ImImagePlugin.py
Normal file
|
|
@ -0,0 +1,377 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library.
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# IFUNC IM file handling for PIL
|
||||||
|
#
|
||||||
|
# history:
|
||||||
|
# 1995-09-01 fl Created.
|
||||||
|
# 1997-01-03 fl Save palette images
|
||||||
|
# 1997-01-08 fl Added sequence support
|
||||||
|
# 1997-01-23 fl Added P and RGB save support
|
||||||
|
# 1997-05-31 fl Read floating point images
|
||||||
|
# 1997-06-22 fl Save floating point images
|
||||||
|
# 1997-08-27 fl Read and save 1-bit images
|
||||||
|
# 1998-06-25 fl Added support for RGB+LUT images
|
||||||
|
# 1998-07-02 fl Added support for YCC images
|
||||||
|
# 1998-07-15 fl Renamed offset attribute to avoid name clash
|
||||||
|
# 1998-12-29 fl Added I;16 support
|
||||||
|
# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.7)
|
||||||
|
# 2003-09-26 fl Added LA/PA support
|
||||||
|
#
|
||||||
|
# Copyright (c) 1997-2003 by Secret Labs AB.
|
||||||
|
# Copyright (c) 1995-2001 by Fredrik Lundh.
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
|
||||||
|
from . import Image, ImageFile, ImagePalette
|
||||||
|
from ._binary import i8
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# Standard tags
|
||||||
|
|
||||||
|
COMMENT = "Comment"
|
||||||
|
DATE = "Date"
|
||||||
|
EQUIPMENT = "Digitalization equipment"
|
||||||
|
FRAMES = "File size (no of images)"
|
||||||
|
LUT = "Lut"
|
||||||
|
NAME = "Name"
|
||||||
|
SCALE = "Scale (x,y)"
|
||||||
|
SIZE = "Image size (x*y)"
|
||||||
|
MODE = "Image type"
|
||||||
|
|
||||||
|
TAGS = {
|
||||||
|
COMMENT: 0,
|
||||||
|
DATE: 0,
|
||||||
|
EQUIPMENT: 0,
|
||||||
|
FRAMES: 0,
|
||||||
|
LUT: 0,
|
||||||
|
NAME: 0,
|
||||||
|
SCALE: 0,
|
||||||
|
SIZE: 0,
|
||||||
|
MODE: 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
OPEN = {
|
||||||
|
# ifunc93/p3cfunc formats
|
||||||
|
"0 1 image": ("1", "1"),
|
||||||
|
"L 1 image": ("1", "1"),
|
||||||
|
"Greyscale image": ("L", "L"),
|
||||||
|
"Grayscale image": ("L", "L"),
|
||||||
|
"RGB image": ("RGB", "RGB;L"),
|
||||||
|
"RLB image": ("RGB", "RLB"),
|
||||||
|
"RYB image": ("RGB", "RLB"),
|
||||||
|
"B1 image": ("1", "1"),
|
||||||
|
"B2 image": ("P", "P;2"),
|
||||||
|
"B4 image": ("P", "P;4"),
|
||||||
|
"X 24 image": ("RGB", "RGB"),
|
||||||
|
"L 32 S image": ("I", "I;32"),
|
||||||
|
"L 32 F image": ("F", "F;32"),
|
||||||
|
# old p3cfunc formats
|
||||||
|
"RGB3 image": ("RGB", "RGB;T"),
|
||||||
|
"RYB3 image": ("RGB", "RYB;T"),
|
||||||
|
# extensions
|
||||||
|
"LA image": ("LA", "LA;L"),
|
||||||
|
"PA image": ("LA", "PA;L"),
|
||||||
|
"RGBA image": ("RGBA", "RGBA;L"),
|
||||||
|
"RGBX image": ("RGBX", "RGBX;L"),
|
||||||
|
"CMYK image": ("CMYK", "CMYK;L"),
|
||||||
|
"YCC image": ("YCbCr", "YCbCr;L"),
|
||||||
|
}
|
||||||
|
|
||||||
|
# ifunc95 extensions
|
||||||
|
for i in ["8", "8S", "16", "16S", "32", "32F"]:
|
||||||
|
OPEN[f"L {i} image"] = ("F", f"F;{i}")
|
||||||
|
OPEN[f"L*{i} image"] = ("F", f"F;{i}")
|
||||||
|
for i in ["16", "16L", "16B"]:
|
||||||
|
OPEN[f"L {i} image"] = (f"I;{i}", f"I;{i}")
|
||||||
|
OPEN[f"L*{i} image"] = (f"I;{i}", f"I;{i}")
|
||||||
|
for i in ["32S"]:
|
||||||
|
OPEN[f"L {i} image"] = ("I", f"I;{i}")
|
||||||
|
OPEN[f"L*{i} image"] = ("I", f"I;{i}")
|
||||||
|
for i in range(2, 33):
|
||||||
|
OPEN[f"L*{i} image"] = ("F", f"F;{i}")
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# Read IM directory
|
||||||
|
|
||||||
|
split = re.compile(br"^([A-Za-z][^:]*):[ \t]*(.*)[ \t]*$")
|
||||||
|
|
||||||
|
|
||||||
|
def number(s):
|
||||||
|
try:
|
||||||
|
return int(s)
|
||||||
|
except ValueError:
|
||||||
|
return float(s)
|
||||||
|
|
||||||
|
|
||||||
|
##
|
||||||
|
# Image plugin for the IFUNC IM file format.
|
||||||
|
|
||||||
|
|
||||||
|
class ImImageFile(ImageFile.ImageFile):
|
||||||
|
|
||||||
|
format = "IM"
|
||||||
|
format_description = "IFUNC Image Memory"
|
||||||
|
_close_exclusive_fp_after_loading = False
|
||||||
|
|
||||||
|
def _open(self):
|
||||||
|
|
||||||
|
# Quick rejection: if there's not an LF among the first
|
||||||
|
# 100 bytes, this is (probably) not a text header.
|
||||||
|
|
||||||
|
if b"\n" not in self.fp.read(100):
|
||||||
|
raise SyntaxError("not an IM file")
|
||||||
|
self.fp.seek(0)
|
||||||
|
|
||||||
|
n = 0
|
||||||
|
|
||||||
|
# Default values
|
||||||
|
self.info[MODE] = "L"
|
||||||
|
self.info[SIZE] = (512, 512)
|
||||||
|
self.info[FRAMES] = 1
|
||||||
|
|
||||||
|
self.rawmode = "L"
|
||||||
|
|
||||||
|
while True:
|
||||||
|
|
||||||
|
s = self.fp.read(1)
|
||||||
|
|
||||||
|
# Some versions of IFUNC uses \n\r instead of \r\n...
|
||||||
|
if s == b"\r":
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not s or s == b"\0" or s == b"\x1A":
|
||||||
|
break
|
||||||
|
|
||||||
|
# FIXME: this may read whole file if not a text file
|
||||||
|
s = s + self.fp.readline()
|
||||||
|
|
||||||
|
if len(s) > 100:
|
||||||
|
raise SyntaxError("not an IM file")
|
||||||
|
|
||||||
|
if s[-2:] == b"\r\n":
|
||||||
|
s = s[:-2]
|
||||||
|
elif s[-1:] == b"\n":
|
||||||
|
s = s[:-1]
|
||||||
|
|
||||||
|
try:
|
||||||
|
m = split.match(s)
|
||||||
|
except re.error as e:
|
||||||
|
raise SyntaxError("not an IM file") from e
|
||||||
|
|
||||||
|
if m:
|
||||||
|
|
||||||
|
k, v = m.group(1, 2)
|
||||||
|
|
||||||
|
# Don't know if this is the correct encoding,
|
||||||
|
# but a decent guess (I guess)
|
||||||
|
k = k.decode("latin-1", "replace")
|
||||||
|
v = v.decode("latin-1", "replace")
|
||||||
|
|
||||||
|
# Convert value as appropriate
|
||||||
|
if k in [FRAMES, SCALE, SIZE]:
|
||||||
|
v = v.replace("*", ",")
|
||||||
|
v = tuple(map(number, v.split(",")))
|
||||||
|
if len(v) == 1:
|
||||||
|
v = v[0]
|
||||||
|
elif k == MODE and v in OPEN:
|
||||||
|
v, self.rawmode = OPEN[v]
|
||||||
|
|
||||||
|
# Add to dictionary. Note that COMMENT tags are
|
||||||
|
# combined into a list of strings.
|
||||||
|
if k == COMMENT:
|
||||||
|
if k in self.info:
|
||||||
|
self.info[k].append(v)
|
||||||
|
else:
|
||||||
|
self.info[k] = [v]
|
||||||
|
else:
|
||||||
|
self.info[k] = v
|
||||||
|
|
||||||
|
if k in TAGS:
|
||||||
|
n += 1
|
||||||
|
|
||||||
|
else:
|
||||||
|
|
||||||
|
raise SyntaxError(
|
||||||
|
"Syntax error in IM header: " + s.decode("ascii", "replace")
|
||||||
|
)
|
||||||
|
|
||||||
|
if not n:
|
||||||
|
raise SyntaxError("Not an IM file")
|
||||||
|
|
||||||
|
# Basic attributes
|
||||||
|
self._size = self.info[SIZE]
|
||||||
|
self.mode = self.info[MODE]
|
||||||
|
|
||||||
|
# Skip forward to start of image data
|
||||||
|
while s and s[0:1] != b"\x1A":
|
||||||
|
s = self.fp.read(1)
|
||||||
|
if not s:
|
||||||
|
raise SyntaxError("File truncated")
|
||||||
|
|
||||||
|
if LUT in self.info:
|
||||||
|
# convert lookup table to palette or lut attribute
|
||||||
|
palette = self.fp.read(768)
|
||||||
|
greyscale = 1 # greyscale palette
|
||||||
|
linear = 1 # linear greyscale palette
|
||||||
|
for i in range(256):
|
||||||
|
if palette[i] == palette[i + 256] == palette[i + 512]:
|
||||||
|
if i8(palette[i]) != i:
|
||||||
|
linear = 0
|
||||||
|
else:
|
||||||
|
greyscale = 0
|
||||||
|
if self.mode in ["L", "LA", "P", "PA"]:
|
||||||
|
if greyscale:
|
||||||
|
if not linear:
|
||||||
|
self.lut = [i8(c) for c in palette[:256]]
|
||||||
|
else:
|
||||||
|
if self.mode in ["L", "P"]:
|
||||||
|
self.mode = self.rawmode = "P"
|
||||||
|
elif self.mode in ["LA", "PA"]:
|
||||||
|
self.mode = "PA"
|
||||||
|
self.rawmode = "PA;L"
|
||||||
|
self.palette = ImagePalette.raw("RGB;L", palette)
|
||||||
|
elif self.mode == "RGB":
|
||||||
|
if not greyscale or not linear:
|
||||||
|
self.lut = [i8(c) for c in palette]
|
||||||
|
|
||||||
|
self.frame = 0
|
||||||
|
|
||||||
|
self.__offset = offs = self.fp.tell()
|
||||||
|
|
||||||
|
self.__fp = self.fp # FIXME: hack
|
||||||
|
|
||||||
|
if self.rawmode[:2] == "F;":
|
||||||
|
|
||||||
|
# ifunc95 formats
|
||||||
|
try:
|
||||||
|
# use bit decoder (if necessary)
|
||||||
|
bits = int(self.rawmode[2:])
|
||||||
|
if bits not in [8, 16, 32]:
|
||||||
|
self.tile = [("bit", (0, 0) + self.size, offs, (bits, 8, 3, 0, -1))]
|
||||||
|
return
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if self.rawmode in ["RGB;T", "RYB;T"]:
|
||||||
|
# Old LabEye/3PC files. Would be very surprised if anyone
|
||||||
|
# ever stumbled upon such a file ;-)
|
||||||
|
size = self.size[0] * self.size[1]
|
||||||
|
self.tile = [
|
||||||
|
("raw", (0, 0) + self.size, offs, ("G", 0, -1)),
|
||||||
|
("raw", (0, 0) + self.size, offs + size, ("R", 0, -1)),
|
||||||
|
("raw", (0, 0) + self.size, offs + 2 * size, ("B", 0, -1)),
|
||||||
|
]
|
||||||
|
else:
|
||||||
|
# LabEye/IFUNC files
|
||||||
|
self.tile = [("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def n_frames(self):
|
||||||
|
return self.info[FRAMES]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_animated(self):
|
||||||
|
return self.info[FRAMES] > 1
|
||||||
|
|
||||||
|
def seek(self, frame):
|
||||||
|
if not self._seek_check(frame):
|
||||||
|
return
|
||||||
|
|
||||||
|
self.frame = frame
|
||||||
|
|
||||||
|
if self.mode == "1":
|
||||||
|
bits = 1
|
||||||
|
else:
|
||||||
|
bits = 8 * len(self.mode)
|
||||||
|
|
||||||
|
size = ((self.size[0] * bits + 7) // 8) * self.size[1]
|
||||||
|
offs = self.__offset + frame * size
|
||||||
|
|
||||||
|
self.fp = self.__fp
|
||||||
|
|
||||||
|
self.tile = [("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))]
|
||||||
|
|
||||||
|
def tell(self):
|
||||||
|
return self.frame
|
||||||
|
|
||||||
|
def _close__fp(self):
|
||||||
|
try:
|
||||||
|
if self.__fp != self.fp:
|
||||||
|
self.__fp.close()
|
||||||
|
except AttributeError:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
self.__fp = None
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# Save IM files
|
||||||
|
|
||||||
|
|
||||||
|
SAVE = {
|
||||||
|
# mode: (im type, raw mode)
|
||||||
|
"1": ("0 1", "1"),
|
||||||
|
"L": ("Greyscale", "L"),
|
||||||
|
"LA": ("LA", "LA;L"),
|
||||||
|
"P": ("Greyscale", "P"),
|
||||||
|
"PA": ("LA", "PA;L"),
|
||||||
|
"I": ("L 32S", "I;32S"),
|
||||||
|
"I;16": ("L 16", "I;16"),
|
||||||
|
"I;16L": ("L 16L", "I;16L"),
|
||||||
|
"I;16B": ("L 16B", "I;16B"),
|
||||||
|
"F": ("L 32F", "F;32F"),
|
||||||
|
"RGB": ("RGB", "RGB;L"),
|
||||||
|
"RGBA": ("RGBA", "RGBA;L"),
|
||||||
|
"RGBX": ("RGBX", "RGBX;L"),
|
||||||
|
"CMYK": ("CMYK", "CMYK;L"),
|
||||||
|
"YCbCr": ("YCC", "YCbCr;L"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _save(im, fp, filename):
|
||||||
|
|
||||||
|
try:
|
||||||
|
image_type, rawmode = SAVE[im.mode]
|
||||||
|
except KeyError as e:
|
||||||
|
raise ValueError(f"Cannot save {im.mode} images as IM") from e
|
||||||
|
|
||||||
|
frames = im.encoderinfo.get("frames", 1)
|
||||||
|
|
||||||
|
fp.write(f"Image type: {image_type} image\r\n".encode("ascii"))
|
||||||
|
if filename:
|
||||||
|
# Each line must be 100 characters or less,
|
||||||
|
# or: SyntaxError("not an IM file")
|
||||||
|
# 8 characters are used for "Name: " and "\r\n"
|
||||||
|
# Keep just the filename, ditch the potentially overlong path
|
||||||
|
name, ext = os.path.splitext(os.path.basename(filename))
|
||||||
|
name = "".join([name[: 92 - len(ext)], ext])
|
||||||
|
|
||||||
|
fp.write(f"Name: {name}\r\n".encode("ascii"))
|
||||||
|
fp.write(("Image size (x*y): %d*%d\r\n" % im.size).encode("ascii"))
|
||||||
|
fp.write(f"File size (no of images): {frames}\r\n".encode("ascii"))
|
||||||
|
if im.mode in ["P", "PA"]:
|
||||||
|
fp.write(b"Lut: 1\r\n")
|
||||||
|
fp.write(b"\000" * (511 - fp.tell()) + b"\032")
|
||||||
|
if im.mode in ["P", "PA"]:
|
||||||
|
fp.write(im.im.getpalette("RGB", "RGB;L")) # 768 bytes
|
||||||
|
ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, -1))])
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# Registry
|
||||||
|
|
||||||
|
|
||||||
|
Image.register_open(ImImageFile.format, ImImageFile)
|
||||||
|
Image.register_save(ImImageFile.format, _save)
|
||||||
|
|
||||||
|
Image.register_extension(ImImageFile.format, ".im")
|
||||||
3476
venv/lib/python3.9/site-packages/PIL/Image.py
Normal file
328
venv/lib/python3.9/site-packages/PIL/ImageChops.py
Normal file
|
|
@ -0,0 +1,328 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library.
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# standard channel operations
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 1996-03-24 fl Created
|
||||||
|
# 1996-08-13 fl Added logical operations (for "1" images)
|
||||||
|
# 2000-10-12 fl Added offset method (from Image.py)
|
||||||
|
#
|
||||||
|
# Copyright (c) 1997-2000 by Secret Labs AB
|
||||||
|
# Copyright (c) 1996-2000 by Fredrik Lundh
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
from . import Image
|
||||||
|
|
||||||
|
|
||||||
|
def constant(image, value):
|
||||||
|
"""Fill a channel with a given grey level.
|
||||||
|
|
||||||
|
:rtype: :py:class:`~PIL.Image.Image`
|
||||||
|
"""
|
||||||
|
|
||||||
|
return Image.new("L", image.size, value)
|
||||||
|
|
||||||
|
|
||||||
|
def duplicate(image):
|
||||||
|
"""Copy a channel. Alias for :py:meth:`PIL.Image.Image.copy`.
|
||||||
|
|
||||||
|
:rtype: :py:class:`~PIL.Image.Image`
|
||||||
|
"""
|
||||||
|
|
||||||
|
return image.copy()
|
||||||
|
|
||||||
|
|
||||||
|
def invert(image):
|
||||||
|
"""
|
||||||
|
Invert an image (channel).
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
out = MAX - image
|
||||||
|
|
||||||
|
:rtype: :py:class:`~PIL.Image.Image`
|
||||||
|
"""
|
||||||
|
|
||||||
|
image.load()
|
||||||
|
return image._new(image.im.chop_invert())
|
||||||
|
|
||||||
|
|
||||||
|
def lighter(image1, image2):
|
||||||
|
"""
|
||||||
|
Compares the two images, pixel by pixel, and returns a new image containing
|
||||||
|
the lighter values.
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
out = max(image1, image2)
|
||||||
|
|
||||||
|
:rtype: :py:class:`~PIL.Image.Image`
|
||||||
|
"""
|
||||||
|
|
||||||
|
image1.load()
|
||||||
|
image2.load()
|
||||||
|
return image1._new(image1.im.chop_lighter(image2.im))
|
||||||
|
|
||||||
|
|
||||||
|
def darker(image1, image2):
|
||||||
|
"""
|
||||||
|
Compares the two images, pixel by pixel, and returns a new image containing
|
||||||
|
the darker values.
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
out = min(image1, image2)
|
||||||
|
|
||||||
|
:rtype: :py:class:`~PIL.Image.Image`
|
||||||
|
"""
|
||||||
|
|
||||||
|
image1.load()
|
||||||
|
image2.load()
|
||||||
|
return image1._new(image1.im.chop_darker(image2.im))
|
||||||
|
|
||||||
|
|
||||||
|
def difference(image1, image2):
|
||||||
|
"""
|
||||||
|
Returns the absolute value of the pixel-by-pixel difference between the two
|
||||||
|
images.
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
out = abs(image1 - image2)
|
||||||
|
|
||||||
|
:rtype: :py:class:`~PIL.Image.Image`
|
||||||
|
"""
|
||||||
|
|
||||||
|
image1.load()
|
||||||
|
image2.load()
|
||||||
|
return image1._new(image1.im.chop_difference(image2.im))
|
||||||
|
|
||||||
|
|
||||||
|
def multiply(image1, image2):
|
||||||
|
"""
|
||||||
|
Superimposes two images on top of each other.
|
||||||
|
|
||||||
|
If you multiply an image with a solid black image, the result is black. If
|
||||||
|
you multiply with a solid white image, the image is unaffected.
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
out = image1 * image2 / MAX
|
||||||
|
|
||||||
|
:rtype: :py:class:`~PIL.Image.Image`
|
||||||
|
"""
|
||||||
|
|
||||||
|
image1.load()
|
||||||
|
image2.load()
|
||||||
|
return image1._new(image1.im.chop_multiply(image2.im))
|
||||||
|
|
||||||
|
|
||||||
|
def screen(image1, image2):
|
||||||
|
"""
|
||||||
|
Superimposes two inverted images on top of each other.
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
out = MAX - ((MAX - image1) * (MAX - image2) / MAX)
|
||||||
|
|
||||||
|
:rtype: :py:class:`~PIL.Image.Image`
|
||||||
|
"""
|
||||||
|
|
||||||
|
image1.load()
|
||||||
|
image2.load()
|
||||||
|
return image1._new(image1.im.chop_screen(image2.im))
|
||||||
|
|
||||||
|
|
||||||
|
def soft_light(image1, image2):
|
||||||
|
"""
|
||||||
|
Superimposes two images on top of each other using the Soft Light algorithm
|
||||||
|
|
||||||
|
:rtype: :py:class:`~PIL.Image.Image`
|
||||||
|
"""
|
||||||
|
|
||||||
|
image1.load()
|
||||||
|
image2.load()
|
||||||
|
return image1._new(image1.im.chop_soft_light(image2.im))
|
||||||
|
|
||||||
|
|
||||||
|
def hard_light(image1, image2):
|
||||||
|
"""
|
||||||
|
Superimposes two images on top of each other using the Hard Light algorithm
|
||||||
|
|
||||||
|
:rtype: :py:class:`~PIL.Image.Image`
|
||||||
|
"""
|
||||||
|
|
||||||
|
image1.load()
|
||||||
|
image2.load()
|
||||||
|
return image1._new(image1.im.chop_hard_light(image2.im))
|
||||||
|
|
||||||
|
|
||||||
|
def overlay(image1, image2):
|
||||||
|
"""
|
||||||
|
Superimposes two images on top of each other using the Overlay algorithm
|
||||||
|
|
||||||
|
:rtype: :py:class:`~PIL.Image.Image`
|
||||||
|
"""
|
||||||
|
|
||||||
|
image1.load()
|
||||||
|
image2.load()
|
||||||
|
return image1._new(image1.im.chop_overlay(image2.im))
|
||||||
|
|
||||||
|
|
||||||
|
def add(image1, image2, scale=1.0, offset=0):
|
||||||
|
"""
|
||||||
|
Adds two images, dividing the result by scale and adding the
|
||||||
|
offset. If omitted, scale defaults to 1.0, and offset to 0.0.
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
out = ((image1 + image2) / scale + offset)
|
||||||
|
|
||||||
|
:rtype: :py:class:`~PIL.Image.Image`
|
||||||
|
"""
|
||||||
|
|
||||||
|
image1.load()
|
||||||
|
image2.load()
|
||||||
|
return image1._new(image1.im.chop_add(image2.im, scale, offset))
|
||||||
|
|
||||||
|
|
||||||
|
def subtract(image1, image2, scale=1.0, offset=0):
|
||||||
|
"""
|
||||||
|
Subtracts two images, dividing the result by scale and adding the offset.
|
||||||
|
If omitted, scale defaults to 1.0, and offset to 0.0.
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
out = ((image1 - image2) / scale + offset)
|
||||||
|
|
||||||
|
:rtype: :py:class:`~PIL.Image.Image`
|
||||||
|
"""
|
||||||
|
|
||||||
|
image1.load()
|
||||||
|
image2.load()
|
||||||
|
return image1._new(image1.im.chop_subtract(image2.im, scale, offset))
|
||||||
|
|
||||||
|
|
||||||
|
def add_modulo(image1, image2):
|
||||||
|
"""Add two images, without clipping the result.
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
out = ((image1 + image2) % MAX)
|
||||||
|
|
||||||
|
:rtype: :py:class:`~PIL.Image.Image`
|
||||||
|
"""
|
||||||
|
|
||||||
|
image1.load()
|
||||||
|
image2.load()
|
||||||
|
return image1._new(image1.im.chop_add_modulo(image2.im))
|
||||||
|
|
||||||
|
|
||||||
|
def subtract_modulo(image1, image2):
|
||||||
|
"""Subtract two images, without clipping the result.
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
out = ((image1 - image2) % MAX)
|
||||||
|
|
||||||
|
:rtype: :py:class:`~PIL.Image.Image`
|
||||||
|
"""
|
||||||
|
|
||||||
|
image1.load()
|
||||||
|
image2.load()
|
||||||
|
return image1._new(image1.im.chop_subtract_modulo(image2.im))
|
||||||
|
|
||||||
|
|
||||||
|
def logical_and(image1, image2):
|
||||||
|
"""Logical AND between two images.
|
||||||
|
|
||||||
|
Both of the images must have mode "1". If you would like to perform a
|
||||||
|
logical AND on an image with a mode other than "1", try
|
||||||
|
:py:meth:`~PIL.ImageChops.multiply` instead, using a black-and-white mask
|
||||||
|
as the second image.
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
out = ((image1 and image2) % MAX)
|
||||||
|
|
||||||
|
:rtype: :py:class:`~PIL.Image.Image`
|
||||||
|
"""
|
||||||
|
|
||||||
|
image1.load()
|
||||||
|
image2.load()
|
||||||
|
return image1._new(image1.im.chop_and(image2.im))
|
||||||
|
|
||||||
|
|
||||||
|
def logical_or(image1, image2):
|
||||||
|
"""Logical OR between two images.
|
||||||
|
|
||||||
|
Both of the images must have mode "1".
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
out = ((image1 or image2) % MAX)
|
||||||
|
|
||||||
|
:rtype: :py:class:`~PIL.Image.Image`
|
||||||
|
"""
|
||||||
|
|
||||||
|
image1.load()
|
||||||
|
image2.load()
|
||||||
|
return image1._new(image1.im.chop_or(image2.im))
|
||||||
|
|
||||||
|
|
||||||
|
def logical_xor(image1, image2):
|
||||||
|
"""Logical XOR between two images.
|
||||||
|
|
||||||
|
Both of the images must have mode "1".
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
out = ((bool(image1) != bool(image2)) % MAX)
|
||||||
|
|
||||||
|
:rtype: :py:class:`~PIL.Image.Image`
|
||||||
|
"""
|
||||||
|
|
||||||
|
image1.load()
|
||||||
|
image2.load()
|
||||||
|
return image1._new(image1.im.chop_xor(image2.im))
|
||||||
|
|
||||||
|
|
||||||
|
def blend(image1, image2, alpha):
|
||||||
|
"""Blend images using constant transparency weight. Alias for
|
||||||
|
:py:func:`PIL.Image.blend`.
|
||||||
|
|
||||||
|
:rtype: :py:class:`~PIL.Image.Image`
|
||||||
|
"""
|
||||||
|
|
||||||
|
return Image.blend(image1, image2, alpha)
|
||||||
|
|
||||||
|
|
||||||
|
def composite(image1, image2, mask):
|
||||||
|
"""Create composite using transparency mask. Alias for
|
||||||
|
:py:func:`PIL.Image.composite`.
|
||||||
|
|
||||||
|
:rtype: :py:class:`~PIL.Image.Image`
|
||||||
|
"""
|
||||||
|
|
||||||
|
return Image.composite(image1, image2, mask)
|
||||||
|
|
||||||
|
|
||||||
|
def offset(image, xoffset, yoffset=None):
|
||||||
|
"""Returns a copy of the image where data has been offset by the given
|
||||||
|
distances. Data wraps around the edges. If ``yoffset`` is omitted, it
|
||||||
|
is assumed to be equal to ``xoffset``.
|
||||||
|
|
||||||
|
:param xoffset: The horizontal distance.
|
||||||
|
:param yoffset: The vertical distance. If omitted, both
|
||||||
|
distances are set to the same value.
|
||||||
|
:rtype: :py:class:`~PIL.Image.Image`
|
||||||
|
"""
|
||||||
|
|
||||||
|
if yoffset is None:
|
||||||
|
yoffset = xoffset
|
||||||
|
image.load()
|
||||||
|
return image._new(image.im.offset(xoffset, yoffset))
|
||||||
999
venv/lib/python3.9/site-packages/PIL/ImageCms.py
Normal file
|
|
@ -0,0 +1,999 @@
|
||||||
|
# The Python Imaging Library.
|
||||||
|
# $Id$
|
||||||
|
|
||||||
|
# Optional color management support, based on Kevin Cazabon's PyCMS
|
||||||
|
# library.
|
||||||
|
|
||||||
|
# History:
|
||||||
|
|
||||||
|
# 2009-03-08 fl Added to PIL.
|
||||||
|
|
||||||
|
# Copyright (C) 2002-2003 Kevin Cazabon
|
||||||
|
# Copyright (c) 2009 by Fredrik Lundh
|
||||||
|
# Copyright (c) 2013 by Eric Soroos
|
||||||
|
|
||||||
|
# See the README file for information on usage and redistribution. See
|
||||||
|
# below for the original description.
|
||||||
|
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
try:
|
||||||
|
from PIL import _imagingcms
|
||||||
|
except ImportError as ex:
|
||||||
|
# Allow error import for doc purposes, but error out when accessing
|
||||||
|
# anything in core.
|
||||||
|
from ._util import deferred_error
|
||||||
|
|
||||||
|
_imagingcms = deferred_error(ex)
|
||||||
|
|
||||||
|
DESCRIPTION = """
|
||||||
|
pyCMS
|
||||||
|
|
||||||
|
a Python / PIL interface to the littleCMS ICC Color Management System
|
||||||
|
Copyright (C) 2002-2003 Kevin Cazabon
|
||||||
|
kevin@cazabon.com
|
||||||
|
http://www.cazabon.com
|
||||||
|
|
||||||
|
pyCMS home page: http://www.cazabon.com/pyCMS
|
||||||
|
littleCMS home page: http://www.littlecms.com
|
||||||
|
(littleCMS is Copyright (C) 1998-2001 Marti Maria)
|
||||||
|
|
||||||
|
Originally released under LGPL. Graciously donated to PIL in
|
||||||
|
March 2009, for distribution under the standard PIL license
|
||||||
|
|
||||||
|
The pyCMS.py module provides a "clean" interface between Python/PIL and
|
||||||
|
pyCMSdll, taking care of some of the more complex handling of the direct
|
||||||
|
pyCMSdll functions, as well as error-checking and making sure that all
|
||||||
|
relevant data is kept together.
|
||||||
|
|
||||||
|
While it is possible to call pyCMSdll functions directly, it's not highly
|
||||||
|
recommended.
|
||||||
|
|
||||||
|
Version History:
|
||||||
|
|
||||||
|
1.0.0 pil Oct 2013 Port to LCMS 2.
|
||||||
|
|
||||||
|
0.1.0 pil mod March 10, 2009
|
||||||
|
|
||||||
|
Renamed display profile to proof profile. The proof
|
||||||
|
profile is the profile of the device that is being
|
||||||
|
simulated, not the profile of the device which is
|
||||||
|
actually used to display/print the final simulation
|
||||||
|
(that'd be the output profile) - also see LCMSAPI.txt
|
||||||
|
input colorspace -> using 'renderingIntent' -> proof
|
||||||
|
colorspace -> using 'proofRenderingIntent' -> output
|
||||||
|
colorspace
|
||||||
|
|
||||||
|
Added LCMS FLAGS support.
|
||||||
|
Added FLAGS["SOFTPROOFING"] as default flag for
|
||||||
|
buildProofTransform (otherwise the proof profile/intent
|
||||||
|
would be ignored).
|
||||||
|
|
||||||
|
0.1.0 pil March 2009 - added to PIL, as PIL.ImageCms
|
||||||
|
|
||||||
|
0.0.2 alpha Jan 6, 2002
|
||||||
|
|
||||||
|
Added try/except statements around type() checks of
|
||||||
|
potential CObjects... Python won't let you use type()
|
||||||
|
on them, and raises a TypeError (stupid, if you ask
|
||||||
|
me!)
|
||||||
|
|
||||||
|
Added buildProofTransformFromOpenProfiles() function.
|
||||||
|
Additional fixes in DLL, see DLL code for details.
|
||||||
|
|
||||||
|
0.0.1 alpha first public release, Dec. 26, 2002
|
||||||
|
|
||||||
|
Known to-do list with current version (of Python interface, not pyCMSdll):
|
||||||
|
|
||||||
|
none
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
VERSION = "1.0.0 pil"
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------.
|
||||||
|
|
||||||
|
core = _imagingcms
|
||||||
|
|
||||||
|
#
|
||||||
|
# intent/direction values
|
||||||
|
|
||||||
|
INTENT_PERCEPTUAL = 0
|
||||||
|
INTENT_RELATIVE_COLORIMETRIC = 1
|
||||||
|
INTENT_SATURATION = 2
|
||||||
|
INTENT_ABSOLUTE_COLORIMETRIC = 3
|
||||||
|
|
||||||
|
DIRECTION_INPUT = 0
|
||||||
|
DIRECTION_OUTPUT = 1
|
||||||
|
DIRECTION_PROOF = 2
|
||||||
|
|
||||||
|
#
|
||||||
|
# flags
|
||||||
|
|
||||||
|
FLAGS = {
|
||||||
|
"MATRIXINPUT": 1,
|
||||||
|
"MATRIXOUTPUT": 2,
|
||||||
|
"MATRIXONLY": (1 | 2),
|
||||||
|
"NOWHITEONWHITEFIXUP": 4, # Don't hot fix scum dot
|
||||||
|
# Don't create prelinearization tables on precalculated transforms
|
||||||
|
# (internal use):
|
||||||
|
"NOPRELINEARIZATION": 16,
|
||||||
|
"GUESSDEVICECLASS": 32, # Guess device class (for transform2devicelink)
|
||||||
|
"NOTCACHE": 64, # Inhibit 1-pixel cache
|
||||||
|
"NOTPRECALC": 256,
|
||||||
|
"NULLTRANSFORM": 512, # Don't transform anyway
|
||||||
|
"HIGHRESPRECALC": 1024, # Use more memory to give better accuracy
|
||||||
|
"LOWRESPRECALC": 2048, # Use less memory to minimize resources
|
||||||
|
"WHITEBLACKCOMPENSATION": 8192,
|
||||||
|
"BLACKPOINTCOMPENSATION": 8192,
|
||||||
|
"GAMUTCHECK": 4096, # Out of Gamut alarm
|
||||||
|
"SOFTPROOFING": 16384, # Do softproofing
|
||||||
|
"PRESERVEBLACK": 32768, # Black preservation
|
||||||
|
"NODEFAULTRESOURCEDEF": 16777216, # CRD special
|
||||||
|
"GRIDPOINTS": lambda n: ((n) & 0xFF) << 16, # Gridpoints
|
||||||
|
}
|
||||||
|
|
||||||
|
_MAX_FLAG = 0
|
||||||
|
for flag in FLAGS.values():
|
||||||
|
if isinstance(flag, int):
|
||||||
|
_MAX_FLAG = _MAX_FLAG | flag
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------.
|
||||||
|
# Experimental PIL-level API
|
||||||
|
# --------------------------------------------------------------------.
|
||||||
|
|
||||||
|
##
|
||||||
|
# Profile.
|
||||||
|
|
||||||
|
|
||||||
|
class ImageCmsProfile:
|
||||||
|
def __init__(self, profile):
|
||||||
|
"""
|
||||||
|
:param profile: Either a string representing a filename,
|
||||||
|
a file like object containing a profile or a
|
||||||
|
low-level profile object
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
if isinstance(profile, str):
|
||||||
|
if sys.platform == "win32":
|
||||||
|
profile_bytes_path = profile.encode()
|
||||||
|
try:
|
||||||
|
profile_bytes_path.decode("ascii")
|
||||||
|
except UnicodeDecodeError:
|
||||||
|
with open(profile, "rb") as f:
|
||||||
|
self._set(core.profile_frombytes(f.read()))
|
||||||
|
return
|
||||||
|
self._set(core.profile_open(profile), profile)
|
||||||
|
elif hasattr(profile, "read"):
|
||||||
|
self._set(core.profile_frombytes(profile.read()))
|
||||||
|
elif isinstance(profile, _imagingcms.CmsProfile):
|
||||||
|
self._set(profile)
|
||||||
|
else:
|
||||||
|
raise TypeError("Invalid type for Profile")
|
||||||
|
|
||||||
|
def _set(self, profile, filename=None):
|
||||||
|
self.profile = profile
|
||||||
|
self.filename = filename
|
||||||
|
if profile:
|
||||||
|
self.product_name = None # profile.product_name
|
||||||
|
self.product_info = None # profile.product_info
|
||||||
|
else:
|
||||||
|
self.product_name = None
|
||||||
|
self.product_info = None
|
||||||
|
|
||||||
|
def tobytes(self):
|
||||||
|
"""
|
||||||
|
Returns the profile in a format suitable for embedding in
|
||||||
|
saved images.
|
||||||
|
|
||||||
|
:returns: a bytes object containing the ICC profile.
|
||||||
|
"""
|
||||||
|
|
||||||
|
return core.profile_tobytes(self.profile)
|
||||||
|
|
||||||
|
|
||||||
|
class ImageCmsTransform(Image.ImagePointHandler):
|
||||||
|
|
||||||
|
"""
|
||||||
|
Transform. This can be used with the procedural API, or with the standard
|
||||||
|
:py:func:`~PIL.Image.Image.point` method.
|
||||||
|
|
||||||
|
Will return the output profile in the ``output.info['icc_profile']``.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
input,
|
||||||
|
output,
|
||||||
|
input_mode,
|
||||||
|
output_mode,
|
||||||
|
intent=INTENT_PERCEPTUAL,
|
||||||
|
proof=None,
|
||||||
|
proof_intent=INTENT_ABSOLUTE_COLORIMETRIC,
|
||||||
|
flags=0,
|
||||||
|
):
|
||||||
|
if proof is None:
|
||||||
|
self.transform = core.buildTransform(
|
||||||
|
input.profile, output.profile, input_mode, output_mode, intent, flags
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.transform = core.buildProofTransform(
|
||||||
|
input.profile,
|
||||||
|
output.profile,
|
||||||
|
proof.profile,
|
||||||
|
input_mode,
|
||||||
|
output_mode,
|
||||||
|
intent,
|
||||||
|
proof_intent,
|
||||||
|
flags,
|
||||||
|
)
|
||||||
|
# Note: inputMode and outputMode are for pyCMS compatibility only
|
||||||
|
self.input_mode = self.inputMode = input_mode
|
||||||
|
self.output_mode = self.outputMode = output_mode
|
||||||
|
|
||||||
|
self.output_profile = output
|
||||||
|
|
||||||
|
def point(self, im):
|
||||||
|
return self.apply(im)
|
||||||
|
|
||||||
|
def apply(self, im, imOut=None):
|
||||||
|
im.load()
|
||||||
|
if imOut is None:
|
||||||
|
imOut = Image.new(self.output_mode, im.size, None)
|
||||||
|
self.transform.apply(im.im.id, imOut.im.id)
|
||||||
|
imOut.info["icc_profile"] = self.output_profile.tobytes()
|
||||||
|
return imOut
|
||||||
|
|
||||||
|
def apply_in_place(self, im):
|
||||||
|
im.load()
|
||||||
|
if im.mode != self.output_mode:
|
||||||
|
raise ValueError("mode mismatch") # wrong output mode
|
||||||
|
self.transform.apply(im.im.id, im.im.id)
|
||||||
|
im.info["icc_profile"] = self.output_profile.tobytes()
|
||||||
|
return im
|
||||||
|
|
||||||
|
|
||||||
|
def get_display_profile(handle=None):
|
||||||
|
"""
|
||||||
|
(experimental) Fetches the profile for the current display device.
|
||||||
|
|
||||||
|
:returns: ``None`` if the profile is not known.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if sys.platform != "win32":
|
||||||
|
return None
|
||||||
|
|
||||||
|
from PIL import ImageWin
|
||||||
|
|
||||||
|
if isinstance(handle, ImageWin.HDC):
|
||||||
|
profile = core.get_display_profile_win32(handle, 1)
|
||||||
|
else:
|
||||||
|
profile = core.get_display_profile_win32(handle or 0)
|
||||||
|
if profile is None:
|
||||||
|
return None
|
||||||
|
return ImageCmsProfile(profile)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------.
|
||||||
|
# pyCMS compatible layer
|
||||||
|
# --------------------------------------------------------------------.
|
||||||
|
|
||||||
|
|
||||||
|
class PyCMSError(Exception):
|
||||||
|
|
||||||
|
"""(pyCMS) Exception class.
|
||||||
|
This is used for all errors in the pyCMS API."""
|
||||||
|
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def profileToProfile(
|
||||||
|
im,
|
||||||
|
inputProfile,
|
||||||
|
outputProfile,
|
||||||
|
renderingIntent=INTENT_PERCEPTUAL,
|
||||||
|
outputMode=None,
|
||||||
|
inPlace=False,
|
||||||
|
flags=0,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
(pyCMS) Applies an ICC transformation to a given image, mapping from
|
||||||
|
``inputProfile`` to ``outputProfile``.
|
||||||
|
|
||||||
|
If the input or output profiles specified are not valid filenames, a
|
||||||
|
:exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and
|
||||||
|
``outputMode != im.mode``, a :exc:`PyCMSError` will be raised.
|
||||||
|
If an error occurs during application of the profiles,
|
||||||
|
a :exc:`PyCMSError` will be raised.
|
||||||
|
If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS),
|
||||||
|
a :exc:`PyCMSError` will be raised.
|
||||||
|
|
||||||
|
This function applies an ICC transformation to im from ``inputProfile``'s
|
||||||
|
color space to ``outputProfile``'s color space using the specified rendering
|
||||||
|
intent to decide how to handle out-of-gamut colors.
|
||||||
|
|
||||||
|
``outputMode`` can be used to specify that a color mode conversion is to
|
||||||
|
be done using these profiles, but the specified profiles must be able
|
||||||
|
to handle that mode. I.e., if converting im from RGB to CMYK using
|
||||||
|
profiles, the input profile must handle RGB data, and the output
|
||||||
|
profile must handle CMYK data.
|
||||||
|
|
||||||
|
:param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...)
|
||||||
|
or Image.open(...), etc.)
|
||||||
|
:param inputProfile: String, as a valid filename path to the ICC input
|
||||||
|
profile you wish to use for this image, or a profile object
|
||||||
|
:param outputProfile: String, as a valid filename path to the ICC output
|
||||||
|
profile you wish to use for this image, or a profile object
|
||||||
|
:param renderingIntent: Integer (0-3) specifying the rendering intent you
|
||||||
|
wish to use for the transform
|
||||||
|
|
||||||
|
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
|
||||||
|
ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1
|
||||||
|
ImageCms.INTENT_SATURATION = 2
|
||||||
|
ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
|
||||||
|
|
||||||
|
see the pyCMS documentation for details on rendering intents and what
|
||||||
|
they do.
|
||||||
|
:param outputMode: A valid PIL mode for the output image (i.e. "RGB",
|
||||||
|
"CMYK", etc.). Note: if rendering the image "inPlace", outputMode
|
||||||
|
MUST be the same mode as the input, or omitted completely. If
|
||||||
|
omitted, the outputMode will be the same as the mode of the input
|
||||||
|
image (im.mode)
|
||||||
|
:param inPlace: Boolean. If ``True``, the original image is modified in-place,
|
||||||
|
and ``None`` is returned. If ``False`` (default), a new
|
||||||
|
:py:class:`~PIL.Image.Image` object is returned with the transform applied.
|
||||||
|
:param flags: Integer (0-...) specifying additional flags
|
||||||
|
:returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on
|
||||||
|
the value of ``inPlace``
|
||||||
|
:exception PyCMSError:
|
||||||
|
"""
|
||||||
|
|
||||||
|
if outputMode is None:
|
||||||
|
outputMode = im.mode
|
||||||
|
|
||||||
|
if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
|
||||||
|
raise PyCMSError("renderingIntent must be an integer between 0 and 3")
|
||||||
|
|
||||||
|
if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
|
||||||
|
raise PyCMSError("flags must be an integer between 0 and %s" + _MAX_FLAG)
|
||||||
|
|
||||||
|
try:
|
||||||
|
if not isinstance(inputProfile, ImageCmsProfile):
|
||||||
|
inputProfile = ImageCmsProfile(inputProfile)
|
||||||
|
if not isinstance(outputProfile, ImageCmsProfile):
|
||||||
|
outputProfile = ImageCmsProfile(outputProfile)
|
||||||
|
transform = ImageCmsTransform(
|
||||||
|
inputProfile,
|
||||||
|
outputProfile,
|
||||||
|
im.mode,
|
||||||
|
outputMode,
|
||||||
|
renderingIntent,
|
||||||
|
flags=flags,
|
||||||
|
)
|
||||||
|
if inPlace:
|
||||||
|
transform.apply_in_place(im)
|
||||||
|
imOut = None
|
||||||
|
else:
|
||||||
|
imOut = transform.apply(im)
|
||||||
|
except (OSError, TypeError, ValueError) as v:
|
||||||
|
raise PyCMSError(v) from v
|
||||||
|
|
||||||
|
return imOut
|
||||||
|
|
||||||
|
|
||||||
|
def getOpenProfile(profileFilename):
|
||||||
|
"""
|
||||||
|
(pyCMS) Opens an ICC profile file.
|
||||||
|
|
||||||
|
The PyCMSProfile object can be passed back into pyCMS for use in creating
|
||||||
|
transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).
|
||||||
|
|
||||||
|
If ``profileFilename`` is not a valid filename for an ICC profile,
|
||||||
|
a :exc:`PyCMSError` will be raised.
|
||||||
|
|
||||||
|
:param profileFilename: String, as a valid filename path to the ICC profile
|
||||||
|
you wish to open, or a file-like object.
|
||||||
|
:returns: A CmsProfile class object.
|
||||||
|
:exception PyCMSError:
|
||||||
|
"""
|
||||||
|
|
||||||
|
try:
|
||||||
|
return ImageCmsProfile(profileFilename)
|
||||||
|
except (OSError, TypeError, ValueError) as v:
|
||||||
|
raise PyCMSError(v) from v
|
||||||
|
|
||||||
|
|
||||||
|
def buildTransform(
|
||||||
|
inputProfile,
|
||||||
|
outputProfile,
|
||||||
|
inMode,
|
||||||
|
outMode,
|
||||||
|
renderingIntent=INTENT_PERCEPTUAL,
|
||||||
|
flags=0,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
|
||||||
|
``outputProfile``. Use applyTransform to apply the transform to a given
|
||||||
|
image.
|
||||||
|
|
||||||
|
If the input or output profiles specified are not valid filenames, a
|
||||||
|
:exc:`PyCMSError` will be raised. If an error occurs during creation
|
||||||
|
of the transform, a :exc:`PyCMSError` will be raised.
|
||||||
|
|
||||||
|
If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
|
||||||
|
(or by pyCMS), a :exc:`PyCMSError` will be raised.
|
||||||
|
|
||||||
|
This function builds and returns an ICC transform from the ``inputProfile``
|
||||||
|
to the ``outputProfile`` using the ``renderingIntent`` to determine what to do
|
||||||
|
with out-of-gamut colors. It will ONLY work for converting images that
|
||||||
|
are in ``inMode`` to images that are in ``outMode`` color format (PIL mode,
|
||||||
|
i.e. "RGB", "RGBA", "CMYK", etc.).
|
||||||
|
|
||||||
|
Building the transform is a fair part of the overhead in
|
||||||
|
ImageCms.profileToProfile(), so if you're planning on converting multiple
|
||||||
|
images using the same input/output settings, this can save you time.
|
||||||
|
Once you have a transform object, it can be used with
|
||||||
|
ImageCms.applyProfile() to convert images without the need to re-compute
|
||||||
|
the lookup table for the transform.
|
||||||
|
|
||||||
|
The reason pyCMS returns a class object rather than a handle directly
|
||||||
|
to the transform is that it needs to keep track of the PIL input/output
|
||||||
|
modes that the transform is meant for. These attributes are stored in
|
||||||
|
the ``inMode`` and ``outMode`` attributes of the object (which can be
|
||||||
|
manually overridden if you really want to, but I don't know of any
|
||||||
|
time that would be of use, or would even work).
|
||||||
|
|
||||||
|
:param inputProfile: String, as a valid filename path to the ICC input
|
||||||
|
profile you wish to use for this transform, or a profile object
|
||||||
|
:param outputProfile: String, as a valid filename path to the ICC output
|
||||||
|
profile you wish to use for this transform, or a profile object
|
||||||
|
:param inMode: String, as a valid PIL mode that the appropriate profile
|
||||||
|
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
|
||||||
|
:param outMode: String, as a valid PIL mode that the appropriate profile
|
||||||
|
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
|
||||||
|
:param renderingIntent: Integer (0-3) specifying the rendering intent you
|
||||||
|
wish to use for the transform
|
||||||
|
|
||||||
|
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
|
||||||
|
ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1
|
||||||
|
ImageCms.INTENT_SATURATION = 2
|
||||||
|
ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
|
||||||
|
|
||||||
|
see the pyCMS documentation for details on rendering intents and what
|
||||||
|
they do.
|
||||||
|
:param flags: Integer (0-...) specifying additional flags
|
||||||
|
:returns: A CmsTransform class object.
|
||||||
|
:exception PyCMSError:
|
||||||
|
"""
|
||||||
|
|
||||||
|
if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
|
||||||
|
raise PyCMSError("renderingIntent must be an integer between 0 and 3")
|
||||||
|
|
||||||
|
if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
|
||||||
|
raise PyCMSError("flags must be an integer between 0 and %s" + _MAX_FLAG)
|
||||||
|
|
||||||
|
try:
|
||||||
|
if not isinstance(inputProfile, ImageCmsProfile):
|
||||||
|
inputProfile = ImageCmsProfile(inputProfile)
|
||||||
|
if not isinstance(outputProfile, ImageCmsProfile):
|
||||||
|
outputProfile = ImageCmsProfile(outputProfile)
|
||||||
|
return ImageCmsTransform(
|
||||||
|
inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags
|
||||||
|
)
|
||||||
|
except (OSError, TypeError, ValueError) as v:
|
||||||
|
raise PyCMSError(v) from v
|
||||||
|
|
||||||
|
|
||||||
|
def buildProofTransform(
|
||||||
|
inputProfile,
|
||||||
|
outputProfile,
|
||||||
|
proofProfile,
|
||||||
|
inMode,
|
||||||
|
outMode,
|
||||||
|
renderingIntent=INTENT_PERCEPTUAL,
|
||||||
|
proofRenderingIntent=INTENT_ABSOLUTE_COLORIMETRIC,
|
||||||
|
flags=FLAGS["SOFTPROOFING"],
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
|
||||||
|
``outputProfile``, but tries to simulate the result that would be
|
||||||
|
obtained on the ``proofProfile`` device.
|
||||||
|
|
||||||
|
If the input, output, or proof profiles specified are not valid
|
||||||
|
filenames, a :exc:`PyCMSError` will be raised.
|
||||||
|
|
||||||
|
If an error occurs during creation of the transform,
|
||||||
|
a :exc:`PyCMSError` will be raised.
|
||||||
|
|
||||||
|
If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
|
||||||
|
(or by pyCMS), a :exc:`PyCMSError` will be raised.
|
||||||
|
|
||||||
|
This function builds and returns an ICC transform from the ``inputProfile``
|
||||||
|
to the ``outputProfile``, but tries to simulate the result that would be
|
||||||
|
obtained on the ``proofProfile`` device using ``renderingIntent`` and
|
||||||
|
``proofRenderingIntent`` to determine what to do with out-of-gamut
|
||||||
|
colors. This is known as "soft-proofing". It will ONLY work for
|
||||||
|
converting images that are in ``inMode`` to images that are in outMode
|
||||||
|
color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.).
|
||||||
|
|
||||||
|
Usage of the resulting transform object is exactly the same as with
|
||||||
|
ImageCms.buildTransform().
|
||||||
|
|
||||||
|
Proof profiling is generally used when using an output device to get a
|
||||||
|
good idea of what the final printed/displayed image would look like on
|
||||||
|
the ``proofProfile`` device when it's quicker and easier to use the
|
||||||
|
output device for judging color. Generally, this means that the
|
||||||
|
output device is a monitor, or a dye-sub printer (etc.), and the simulated
|
||||||
|
device is something more expensive, complicated, or time consuming
|
||||||
|
(making it difficult to make a real print for color judgement purposes).
|
||||||
|
|
||||||
|
Soft-proofing basically functions by adjusting the colors on the
|
||||||
|
output device to match the colors of the device being simulated. However,
|
||||||
|
when the simulated device has a much wider gamut than the output
|
||||||
|
device, you may obtain marginal results.
|
||||||
|
|
||||||
|
:param inputProfile: String, as a valid filename path to the ICC input
|
||||||
|
profile you wish to use for this transform, or a profile object
|
||||||
|
:param outputProfile: String, as a valid filename path to the ICC output
|
||||||
|
(monitor, usually) profile you wish to use for this transform, or a
|
||||||
|
profile object
|
||||||
|
:param proofProfile: String, as a valid filename path to the ICC proof
|
||||||
|
profile you wish to use for this transform, or a profile object
|
||||||
|
:param inMode: String, as a valid PIL mode that the appropriate profile
|
||||||
|
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
|
||||||
|
:param outMode: String, as a valid PIL mode that the appropriate profile
|
||||||
|
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
|
||||||
|
:param renderingIntent: Integer (0-3) specifying the rendering intent you
|
||||||
|
wish to use for the input->proof (simulated) transform
|
||||||
|
|
||||||
|
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
|
||||||
|
ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1
|
||||||
|
ImageCms.INTENT_SATURATION = 2
|
||||||
|
ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
|
||||||
|
|
||||||
|
see the pyCMS documentation for details on rendering intents and what
|
||||||
|
they do.
|
||||||
|
:param proofRenderingIntent: Integer (0-3) specifying the rendering intent
|
||||||
|
you wish to use for proof->output transform
|
||||||
|
|
||||||
|
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
|
||||||
|
ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1
|
||||||
|
ImageCms.INTENT_SATURATION = 2
|
||||||
|
ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
|
||||||
|
|
||||||
|
see the pyCMS documentation for details on rendering intents and what
|
||||||
|
they do.
|
||||||
|
:param flags: Integer (0-...) specifying additional flags
|
||||||
|
:returns: A CmsTransform class object.
|
||||||
|
:exception PyCMSError:
|
||||||
|
"""
|
||||||
|
|
||||||
|
if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
|
||||||
|
raise PyCMSError("renderingIntent must be an integer between 0 and 3")
|
||||||
|
|
||||||
|
if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
|
||||||
|
raise PyCMSError("flags must be an integer between 0 and %s" + _MAX_FLAG)
|
||||||
|
|
||||||
|
try:
|
||||||
|
if not isinstance(inputProfile, ImageCmsProfile):
|
||||||
|
inputProfile = ImageCmsProfile(inputProfile)
|
||||||
|
if not isinstance(outputProfile, ImageCmsProfile):
|
||||||
|
outputProfile = ImageCmsProfile(outputProfile)
|
||||||
|
if not isinstance(proofProfile, ImageCmsProfile):
|
||||||
|
proofProfile = ImageCmsProfile(proofProfile)
|
||||||
|
return ImageCmsTransform(
|
||||||
|
inputProfile,
|
||||||
|
outputProfile,
|
||||||
|
inMode,
|
||||||
|
outMode,
|
||||||
|
renderingIntent,
|
||||||
|
proofProfile,
|
||||||
|
proofRenderingIntent,
|
||||||
|
flags,
|
||||||
|
)
|
||||||
|
except (OSError, TypeError, ValueError) as v:
|
||||||
|
raise PyCMSError(v) from v
|
||||||
|
|
||||||
|
|
||||||
|
buildTransformFromOpenProfiles = buildTransform
|
||||||
|
buildProofTransformFromOpenProfiles = buildProofTransform
|
||||||
|
|
||||||
|
|
||||||
|
def applyTransform(im, transform, inPlace=False):
|
||||||
|
"""
|
||||||
|
(pyCMS) Applies a transform to a given image.
|
||||||
|
|
||||||
|
If ``im.mode != transform.inMode``, a :exc:`PyCMSError` is raised.
|
||||||
|
|
||||||
|
If ``inPlace`` is ``True`` and ``transform.inMode != transform.outMode``, a
|
||||||
|
:exc:`PyCMSError` is raised.
|
||||||
|
|
||||||
|
If ``im.mode``, ``transform.inMode`` or ``transform.outMode`` is not
|
||||||
|
supported by pyCMSdll or the profiles you used for the transform, a
|
||||||
|
:exc:`PyCMSError` is raised.
|
||||||
|
|
||||||
|
If an error occurs while the transform is being applied,
|
||||||
|
a :exc:`PyCMSError` is raised.
|
||||||
|
|
||||||
|
This function applies a pre-calculated transform (from
|
||||||
|
ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles())
|
||||||
|
to an image. The transform can be used for multiple images, saving
|
||||||
|
considerable calculation time if doing the same conversion multiple times.
|
||||||
|
|
||||||
|
If you want to modify im in-place instead of receiving a new image as
|
||||||
|
the return value, set ``inPlace`` to ``True``. This can only be done if
|
||||||
|
``transform.inMode`` and ``transform.outMode`` are the same, because we can't
|
||||||
|
change the mode in-place (the buffer sizes for some modes are
|
||||||
|
different). The default behavior is to return a new :py:class:`~PIL.Image.Image`
|
||||||
|
object of the same dimensions in mode ``transform.outMode``.
|
||||||
|
|
||||||
|
:param im: An :py:class:`~PIL.Image.Image` object, and im.mode must be the same
|
||||||
|
as the ``inMode`` supported by the transform.
|
||||||
|
:param transform: A valid CmsTransform class object
|
||||||
|
:param inPlace: Bool. If ``True``, ``im`` is modified in place and ``None`` is
|
||||||
|
returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the
|
||||||
|
transform applied is returned (and ``im`` is not changed). The default is
|
||||||
|
``False``.
|
||||||
|
:returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object,
|
||||||
|
depending on the value of ``inPlace``. The profile will be returned in
|
||||||
|
the image's ``info['icc_profile']``.
|
||||||
|
:exception PyCMSError:
|
||||||
|
"""
|
||||||
|
|
||||||
|
try:
|
||||||
|
if inPlace:
|
||||||
|
transform.apply_in_place(im)
|
||||||
|
imOut = None
|
||||||
|
else:
|
||||||
|
imOut = transform.apply(im)
|
||||||
|
except (TypeError, ValueError) as v:
|
||||||
|
raise PyCMSError(v) from v
|
||||||
|
|
||||||
|
return imOut
|
||||||
|
|
||||||
|
|
||||||
|
def createProfile(colorSpace, colorTemp=-1):
|
||||||
|
"""
|
||||||
|
(pyCMS) Creates a profile.
|
||||||
|
|
||||||
|
If colorSpace not in ``["LAB", "XYZ", "sRGB"]``,
|
||||||
|
a :exc:`PyCMSError` is raised.
|
||||||
|
|
||||||
|
If using LAB and ``colorTemp`` is not a positive integer,
|
||||||
|
a :exc:`PyCMSError` is raised.
|
||||||
|
|
||||||
|
If an error occurs while creating the profile,
|
||||||
|
a :exc:`PyCMSError` is raised.
|
||||||
|
|
||||||
|
Use this function to create common profiles on-the-fly instead of
|
||||||
|
having to supply a profile on disk and knowing the path to it. It
|
||||||
|
returns a normal CmsProfile object that can be passed to
|
||||||
|
ImageCms.buildTransformFromOpenProfiles() to create a transform to apply
|
||||||
|
to images.
|
||||||
|
|
||||||
|
:param colorSpace: String, the color space of the profile you wish to
|
||||||
|
create.
|
||||||
|
Currently only "LAB", "XYZ", and "sRGB" are supported.
|
||||||
|
:param colorTemp: Positive integer for the white point for the profile, in
|
||||||
|
degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50
|
||||||
|
illuminant if omitted (5000k). colorTemp is ONLY applied to LAB
|
||||||
|
profiles, and is ignored for XYZ and sRGB.
|
||||||
|
:returns: A CmsProfile class object
|
||||||
|
:exception PyCMSError:
|
||||||
|
"""
|
||||||
|
|
||||||
|
if colorSpace not in ["LAB", "XYZ", "sRGB"]:
|
||||||
|
raise PyCMSError(
|
||||||
|
f"Color space not supported for on-the-fly profile creation ({colorSpace})"
|
||||||
|
)
|
||||||
|
|
||||||
|
if colorSpace == "LAB":
|
||||||
|
try:
|
||||||
|
colorTemp = float(colorTemp)
|
||||||
|
except (TypeError, ValueError) as e:
|
||||||
|
raise PyCMSError(
|
||||||
|
f'Color temperature must be numeric, "{colorTemp}" not valid'
|
||||||
|
) from e
|
||||||
|
|
||||||
|
try:
|
||||||
|
return core.createProfile(colorSpace, colorTemp)
|
||||||
|
except (TypeError, ValueError) as v:
|
||||||
|
raise PyCMSError(v) from v
|
||||||
|
|
||||||
|
|
||||||
|
def getProfileName(profile):
|
||||||
|
"""
|
||||||
|
|
||||||
|
(pyCMS) Gets the internal product name for the given profile.
|
||||||
|
|
||||||
|
If ``profile`` isn't a valid CmsProfile object or filename to a profile,
|
||||||
|
a :exc:`PyCMSError` is raised If an error occurs while trying
|
||||||
|
to obtain the name tag, a :exc:`PyCMSError` is raised.
|
||||||
|
|
||||||
|
Use this function to obtain the INTERNAL name of the profile (stored
|
||||||
|
in an ICC tag in the profile itself), usually the one used when the
|
||||||
|
profile was originally created. Sometimes this tag also contains
|
||||||
|
additional information supplied by the creator.
|
||||||
|
|
||||||
|
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
||||||
|
filename of an ICC profile.
|
||||||
|
:returns: A string containing the internal name of the profile as stored
|
||||||
|
in an ICC tag.
|
||||||
|
:exception PyCMSError:
|
||||||
|
"""
|
||||||
|
|
||||||
|
try:
|
||||||
|
# add an extra newline to preserve pyCMS compatibility
|
||||||
|
if not isinstance(profile, ImageCmsProfile):
|
||||||
|
profile = ImageCmsProfile(profile)
|
||||||
|
# do it in python, not c.
|
||||||
|
# // name was "%s - %s" (model, manufacturer) || Description ,
|
||||||
|
# // but if the Model and Manufacturer were the same or the model
|
||||||
|
# // was long, Just the model, in 1.x
|
||||||
|
model = profile.profile.model
|
||||||
|
manufacturer = profile.profile.manufacturer
|
||||||
|
|
||||||
|
if not (model or manufacturer):
|
||||||
|
return (profile.profile.profile_description or "") + "\n"
|
||||||
|
if not manufacturer or len(model) > 30:
|
||||||
|
return model + "\n"
|
||||||
|
return f"{model} - {manufacturer}\n"
|
||||||
|
|
||||||
|
except (AttributeError, OSError, TypeError, ValueError) as v:
|
||||||
|
raise PyCMSError(v) from v
|
||||||
|
|
||||||
|
|
||||||
|
def getProfileInfo(profile):
|
||||||
|
"""
|
||||||
|
(pyCMS) Gets the internal product information for the given profile.
|
||||||
|
|
||||||
|
If ``profile`` isn't a valid CmsProfile object or filename to a profile,
|
||||||
|
a :exc:`PyCMSError` is raised.
|
||||||
|
|
||||||
|
If an error occurs while trying to obtain the info tag,
|
||||||
|
a :exc:`PyCMSError` is raised.
|
||||||
|
|
||||||
|
Use this function to obtain the information stored in the profile's
|
||||||
|
info tag. This often contains details about the profile, and how it
|
||||||
|
was created, as supplied by the creator.
|
||||||
|
|
||||||
|
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
||||||
|
filename of an ICC profile.
|
||||||
|
:returns: A string containing the internal profile information stored in
|
||||||
|
an ICC tag.
|
||||||
|
:exception PyCMSError:
|
||||||
|
"""
|
||||||
|
|
||||||
|
try:
|
||||||
|
if not isinstance(profile, ImageCmsProfile):
|
||||||
|
profile = ImageCmsProfile(profile)
|
||||||
|
# add an extra newline to preserve pyCMS compatibility
|
||||||
|
# Python, not C. the white point bits weren't working well,
|
||||||
|
# so skipping.
|
||||||
|
# info was description \r\n\r\n copyright \r\n\r\n K007 tag \r\n\r\n whitepoint
|
||||||
|
description = profile.profile.profile_description
|
||||||
|
cpright = profile.profile.copyright
|
||||||
|
arr = []
|
||||||
|
for elt in (description, cpright):
|
||||||
|
if elt:
|
||||||
|
arr.append(elt)
|
||||||
|
return "\r\n\r\n".join(arr) + "\r\n\r\n"
|
||||||
|
|
||||||
|
except (AttributeError, OSError, TypeError, ValueError) as v:
|
||||||
|
raise PyCMSError(v) from v
|
||||||
|
|
||||||
|
|
||||||
|
def getProfileCopyright(profile):
|
||||||
|
"""
|
||||||
|
(pyCMS) Gets the copyright for the given profile.
|
||||||
|
|
||||||
|
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
||||||
|
:exc:`PyCMSError` is raised.
|
||||||
|
|
||||||
|
If an error occurs while trying to obtain the copyright tag,
|
||||||
|
a :exc:`PyCMSError` is raised.
|
||||||
|
|
||||||
|
Use this function to obtain the information stored in the profile's
|
||||||
|
copyright tag.
|
||||||
|
|
||||||
|
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
||||||
|
filename of an ICC profile.
|
||||||
|
:returns: A string containing the internal profile information stored in
|
||||||
|
an ICC tag.
|
||||||
|
:exception PyCMSError:
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# add an extra newline to preserve pyCMS compatibility
|
||||||
|
if not isinstance(profile, ImageCmsProfile):
|
||||||
|
profile = ImageCmsProfile(profile)
|
||||||
|
return (profile.profile.copyright or "") + "\n"
|
||||||
|
except (AttributeError, OSError, TypeError, ValueError) as v:
|
||||||
|
raise PyCMSError(v) from v
|
||||||
|
|
||||||
|
|
||||||
|
def getProfileManufacturer(profile):
|
||||||
|
"""
|
||||||
|
(pyCMS) Gets the manufacturer for the given profile.
|
||||||
|
|
||||||
|
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
||||||
|
:exc:`PyCMSError` is raised.
|
||||||
|
|
||||||
|
If an error occurs while trying to obtain the manufacturer tag, a
|
||||||
|
:exc:`PyCMSError` is raised.
|
||||||
|
|
||||||
|
Use this function to obtain the information stored in the profile's
|
||||||
|
manufacturer tag.
|
||||||
|
|
||||||
|
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
||||||
|
filename of an ICC profile.
|
||||||
|
:returns: A string containing the internal profile information stored in
|
||||||
|
an ICC tag.
|
||||||
|
:exception PyCMSError:
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# add an extra newline to preserve pyCMS compatibility
|
||||||
|
if not isinstance(profile, ImageCmsProfile):
|
||||||
|
profile = ImageCmsProfile(profile)
|
||||||
|
return (profile.profile.manufacturer or "") + "\n"
|
||||||
|
except (AttributeError, OSError, TypeError, ValueError) as v:
|
||||||
|
raise PyCMSError(v) from v
|
||||||
|
|
||||||
|
|
||||||
|
def getProfileModel(profile):
|
||||||
|
"""
|
||||||
|
(pyCMS) Gets the model for the given profile.
|
||||||
|
|
||||||
|
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
||||||
|
:exc:`PyCMSError` is raised.
|
||||||
|
|
||||||
|
If an error occurs while trying to obtain the model tag,
|
||||||
|
a :exc:`PyCMSError` is raised.
|
||||||
|
|
||||||
|
Use this function to obtain the information stored in the profile's
|
||||||
|
model tag.
|
||||||
|
|
||||||
|
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
||||||
|
filename of an ICC profile.
|
||||||
|
:returns: A string containing the internal profile information stored in
|
||||||
|
an ICC tag.
|
||||||
|
:exception PyCMSError:
|
||||||
|
"""
|
||||||
|
|
||||||
|
try:
|
||||||
|
# add an extra newline to preserve pyCMS compatibility
|
||||||
|
if not isinstance(profile, ImageCmsProfile):
|
||||||
|
profile = ImageCmsProfile(profile)
|
||||||
|
return (profile.profile.model or "") + "\n"
|
||||||
|
except (AttributeError, OSError, TypeError, ValueError) as v:
|
||||||
|
raise PyCMSError(v) from v
|
||||||
|
|
||||||
|
|
||||||
|
def getProfileDescription(profile):
|
||||||
|
"""
|
||||||
|
(pyCMS) Gets the description for the given profile.
|
||||||
|
|
||||||
|
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
||||||
|
:exc:`PyCMSError` is raised.
|
||||||
|
|
||||||
|
If an error occurs while trying to obtain the description tag,
|
||||||
|
a :exc:`PyCMSError` is raised.
|
||||||
|
|
||||||
|
Use this function to obtain the information stored in the profile's
|
||||||
|
description tag.
|
||||||
|
|
||||||
|
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
||||||
|
filename of an ICC profile.
|
||||||
|
:returns: A string containing the internal profile information stored in an
|
||||||
|
ICC tag.
|
||||||
|
:exception PyCMSError:
|
||||||
|
"""
|
||||||
|
|
||||||
|
try:
|
||||||
|
# add an extra newline to preserve pyCMS compatibility
|
||||||
|
if not isinstance(profile, ImageCmsProfile):
|
||||||
|
profile = ImageCmsProfile(profile)
|
||||||
|
return (profile.profile.profile_description or "") + "\n"
|
||||||
|
except (AttributeError, OSError, TypeError, ValueError) as v:
|
||||||
|
raise PyCMSError(v) from v
|
||||||
|
|
||||||
|
|
||||||
|
def getDefaultIntent(profile):
|
||||||
|
"""
|
||||||
|
(pyCMS) Gets the default intent name for the given profile.
|
||||||
|
|
||||||
|
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
||||||
|
:exc:`PyCMSError` is raised.
|
||||||
|
|
||||||
|
If an error occurs while trying to obtain the default intent, a
|
||||||
|
:exc:`PyCMSError` is raised.
|
||||||
|
|
||||||
|
Use this function to determine the default (and usually best optimized)
|
||||||
|
rendering intent for this profile. Most profiles support multiple
|
||||||
|
rendering intents, but are intended mostly for one type of conversion.
|
||||||
|
If you wish to use a different intent than returned, use
|
||||||
|
ImageCms.isIntentSupported() to verify it will work first.
|
||||||
|
|
||||||
|
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
||||||
|
filename of an ICC profile.
|
||||||
|
:returns: Integer 0-3 specifying the default rendering intent for this
|
||||||
|
profile.
|
||||||
|
|
||||||
|
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
|
||||||
|
ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1
|
||||||
|
ImageCms.INTENT_SATURATION = 2
|
||||||
|
ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
|
||||||
|
|
||||||
|
see the pyCMS documentation for details on rendering intents and what
|
||||||
|
they do.
|
||||||
|
:exception PyCMSError:
|
||||||
|
"""
|
||||||
|
|
||||||
|
try:
|
||||||
|
if not isinstance(profile, ImageCmsProfile):
|
||||||
|
profile = ImageCmsProfile(profile)
|
||||||
|
return profile.profile.rendering_intent
|
||||||
|
except (AttributeError, OSError, TypeError, ValueError) as v:
|
||||||
|
raise PyCMSError(v) from v
|
||||||
|
|
||||||
|
|
||||||
|
def isIntentSupported(profile, intent, direction):
|
||||||
|
"""
|
||||||
|
(pyCMS) Checks if a given intent is supported.
|
||||||
|
|
||||||
|
Use this function to verify that you can use your desired
|
||||||
|
``intent`` with ``profile``, and that ``profile`` can be used for the
|
||||||
|
input/output/proof profile as you desire.
|
||||||
|
|
||||||
|
Some profiles are created specifically for one "direction", can cannot
|
||||||
|
be used for others. Some profiles can only be used for certain
|
||||||
|
rendering intents, so it's best to either verify this before trying
|
||||||
|
to create a transform with them (using this function), or catch the
|
||||||
|
potential :exc:`PyCMSError` that will occur if they don't
|
||||||
|
support the modes you select.
|
||||||
|
|
||||||
|
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
||||||
|
filename of an ICC profile.
|
||||||
|
:param intent: Integer (0-3) specifying the rendering intent you wish to
|
||||||
|
use with this profile
|
||||||
|
|
||||||
|
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
|
||||||
|
ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1
|
||||||
|
ImageCms.INTENT_SATURATION = 2
|
||||||
|
ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
|
||||||
|
|
||||||
|
see the pyCMS documentation for details on rendering intents and what
|
||||||
|
they do.
|
||||||
|
:param direction: Integer specifying if the profile is to be used for
|
||||||
|
input, output, or proof
|
||||||
|
|
||||||
|
INPUT = 0 (or use ImageCms.DIRECTION_INPUT)
|
||||||
|
OUTPUT = 1 (or use ImageCms.DIRECTION_OUTPUT)
|
||||||
|
PROOF = 2 (or use ImageCms.DIRECTION_PROOF)
|
||||||
|
|
||||||
|
:returns: 1 if the intent/direction are supported, -1 if they are not.
|
||||||
|
:exception PyCMSError:
|
||||||
|
"""
|
||||||
|
|
||||||
|
try:
|
||||||
|
if not isinstance(profile, ImageCmsProfile):
|
||||||
|
profile = ImageCmsProfile(profile)
|
||||||
|
# FIXME: I get different results for the same data w. different
|
||||||
|
# compilers. Bug in LittleCMS or in the binding?
|
||||||
|
if profile.profile.is_intent_supported(intent, direction):
|
||||||
|
return 1
|
||||||
|
else:
|
||||||
|
return -1
|
||||||
|
except (AttributeError, OSError, TypeError, ValueError) as v:
|
||||||
|
raise PyCMSError(v) from v
|
||||||
|
|
||||||
|
|
||||||
|
def versions():
|
||||||
|
"""
|
||||||
|
(pyCMS) Fetches versions.
|
||||||
|
"""
|
||||||
|
|
||||||
|
return (VERSION, core.littlecms_version, sys.version.split()[0], Image.__version__)
|
||||||
300
venv/lib/python3.9/site-packages/PIL/ImageColor.py
Normal file
|
|
@ -0,0 +1,300 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# map CSS3-style colour description strings to RGB
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 2002-10-24 fl Added support for CSS-style color strings
|
||||||
|
# 2002-12-15 fl Added RGBA support
|
||||||
|
# 2004-03-27 fl Fixed remaining int() problems for Python 1.5.2
|
||||||
|
# 2004-07-19 fl Fixed gray/grey spelling issues
|
||||||
|
# 2009-03-05 fl Fixed rounding error in grayscale calculation
|
||||||
|
#
|
||||||
|
# Copyright (c) 2002-2004 by Secret Labs AB
|
||||||
|
# Copyright (c) 2002-2004 by Fredrik Lundh
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
|
from . import Image
|
||||||
|
|
||||||
|
|
||||||
|
def getrgb(color):
|
||||||
|
"""
|
||||||
|
Convert a color string to an RGB tuple. If the string cannot be parsed,
|
||||||
|
this function raises a :py:exc:`ValueError` exception.
|
||||||
|
|
||||||
|
.. versionadded:: 1.1.4
|
||||||
|
|
||||||
|
:param color: A color string
|
||||||
|
:return: ``(red, green, blue[, alpha])``
|
||||||
|
"""
|
||||||
|
color = color.lower()
|
||||||
|
|
||||||
|
rgb = colormap.get(color, None)
|
||||||
|
if rgb:
|
||||||
|
if isinstance(rgb, tuple):
|
||||||
|
return rgb
|
||||||
|
colormap[color] = rgb = getrgb(rgb)
|
||||||
|
return rgb
|
||||||
|
|
||||||
|
# check for known string formats
|
||||||
|
if re.match("#[a-f0-9]{3}$", color):
|
||||||
|
return (int(color[1] * 2, 16), int(color[2] * 2, 16), int(color[3] * 2, 16))
|
||||||
|
|
||||||
|
if re.match("#[a-f0-9]{4}$", color):
|
||||||
|
return (
|
||||||
|
int(color[1] * 2, 16),
|
||||||
|
int(color[2] * 2, 16),
|
||||||
|
int(color[3] * 2, 16),
|
||||||
|
int(color[4] * 2, 16),
|
||||||
|
)
|
||||||
|
|
||||||
|
if re.match("#[a-f0-9]{6}$", color):
|
||||||
|
return (int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16))
|
||||||
|
|
||||||
|
if re.match("#[a-f0-9]{8}$", color):
|
||||||
|
return (
|
||||||
|
int(color[1:3], 16),
|
||||||
|
int(color[3:5], 16),
|
||||||
|
int(color[5:7], 16),
|
||||||
|
int(color[7:9], 16),
|
||||||
|
)
|
||||||
|
|
||||||
|
m = re.match(r"rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
|
||||||
|
if m:
|
||||||
|
return (int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||||
|
|
||||||
|
m = re.match(r"rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)$", color)
|
||||||
|
if m:
|
||||||
|
return (
|
||||||
|
int((int(m.group(1)) * 255) / 100.0 + 0.5),
|
||||||
|
int((int(m.group(2)) * 255) / 100.0 + 0.5),
|
||||||
|
int((int(m.group(3)) * 255) / 100.0 + 0.5),
|
||||||
|
)
|
||||||
|
|
||||||
|
m = re.match(
|
||||||
|
r"hsl\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
|
||||||
|
)
|
||||||
|
if m:
|
||||||
|
from colorsys import hls_to_rgb
|
||||||
|
|
||||||
|
rgb = hls_to_rgb(
|
||||||
|
float(m.group(1)) / 360.0,
|
||||||
|
float(m.group(3)) / 100.0,
|
||||||
|
float(m.group(2)) / 100.0,
|
||||||
|
)
|
||||||
|
return (
|
||||||
|
int(rgb[0] * 255 + 0.5),
|
||||||
|
int(rgb[1] * 255 + 0.5),
|
||||||
|
int(rgb[2] * 255 + 0.5),
|
||||||
|
)
|
||||||
|
|
||||||
|
m = re.match(
|
||||||
|
r"hs[bv]\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
|
||||||
|
)
|
||||||
|
if m:
|
||||||
|
from colorsys import hsv_to_rgb
|
||||||
|
|
||||||
|
rgb = hsv_to_rgb(
|
||||||
|
float(m.group(1)) / 360.0,
|
||||||
|
float(m.group(2)) / 100.0,
|
||||||
|
float(m.group(3)) / 100.0,
|
||||||
|
)
|
||||||
|
return (
|
||||||
|
int(rgb[0] * 255 + 0.5),
|
||||||
|
int(rgb[1] * 255 + 0.5),
|
||||||
|
int(rgb[2] * 255 + 0.5),
|
||||||
|
)
|
||||||
|
|
||||||
|
m = re.match(r"rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
|
||||||
|
if m:
|
||||||
|
return (int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)))
|
||||||
|
raise ValueError(f"unknown color specifier: {repr(color)}")
|
||||||
|
|
||||||
|
|
||||||
|
def getcolor(color, mode):
|
||||||
|
"""
|
||||||
|
Same as :py:func:`~PIL.ImageColor.getrgb`, but converts the RGB value to a
|
||||||
|
greyscale value if the mode is not color or a palette image. If the string
|
||||||
|
cannot be parsed, this function raises a :py:exc:`ValueError` exception.
|
||||||
|
|
||||||
|
.. versionadded:: 1.1.4
|
||||||
|
|
||||||
|
:param color: A color string
|
||||||
|
:return: ``(graylevel [, alpha]) or (red, green, blue[, alpha])``
|
||||||
|
"""
|
||||||
|
# same as getrgb, but converts the result to the given mode
|
||||||
|
color, alpha = getrgb(color), 255
|
||||||
|
if len(color) == 4:
|
||||||
|
color, alpha = color[0:3], color[3]
|
||||||
|
|
||||||
|
if Image.getmodebase(mode) == "L":
|
||||||
|
r, g, b = color
|
||||||
|
# ITU-R Recommendation 601-2 for nonlinear RGB
|
||||||
|
# scaled to 24 bits to match the convert's implementation.
|
||||||
|
color = (r * 19595 + g * 38470 + b * 7471 + 0x8000) >> 16
|
||||||
|
if mode[-1] == "A":
|
||||||
|
return (color, alpha)
|
||||||
|
else:
|
||||||
|
if mode[-1] == "A":
|
||||||
|
return color + (alpha,)
|
||||||
|
return color
|
||||||
|
|
||||||
|
|
||||||
|
colormap = {
|
||||||
|
# X11 colour table from https://drafts.csswg.org/css-color-4/, with
|
||||||
|
# gray/grey spelling issues fixed. This is a superset of HTML 4.0
|
||||||
|
# colour names used in CSS 1.
|
||||||
|
"aliceblue": "#f0f8ff",
|
||||||
|
"antiquewhite": "#faebd7",
|
||||||
|
"aqua": "#00ffff",
|
||||||
|
"aquamarine": "#7fffd4",
|
||||||
|
"azure": "#f0ffff",
|
||||||
|
"beige": "#f5f5dc",
|
||||||
|
"bisque": "#ffe4c4",
|
||||||
|
"black": "#000000",
|
||||||
|
"blanchedalmond": "#ffebcd",
|
||||||
|
"blue": "#0000ff",
|
||||||
|
"blueviolet": "#8a2be2",
|
||||||
|
"brown": "#a52a2a",
|
||||||
|
"burlywood": "#deb887",
|
||||||
|
"cadetblue": "#5f9ea0",
|
||||||
|
"chartreuse": "#7fff00",
|
||||||
|
"chocolate": "#d2691e",
|
||||||
|
"coral": "#ff7f50",
|
||||||
|
"cornflowerblue": "#6495ed",
|
||||||
|
"cornsilk": "#fff8dc",
|
||||||
|
"crimson": "#dc143c",
|
||||||
|
"cyan": "#00ffff",
|
||||||
|
"darkblue": "#00008b",
|
||||||
|
"darkcyan": "#008b8b",
|
||||||
|
"darkgoldenrod": "#b8860b",
|
||||||
|
"darkgray": "#a9a9a9",
|
||||||
|
"darkgrey": "#a9a9a9",
|
||||||
|
"darkgreen": "#006400",
|
||||||
|
"darkkhaki": "#bdb76b",
|
||||||
|
"darkmagenta": "#8b008b",
|
||||||
|
"darkolivegreen": "#556b2f",
|
||||||
|
"darkorange": "#ff8c00",
|
||||||
|
"darkorchid": "#9932cc",
|
||||||
|
"darkred": "#8b0000",
|
||||||
|
"darksalmon": "#e9967a",
|
||||||
|
"darkseagreen": "#8fbc8f",
|
||||||
|
"darkslateblue": "#483d8b",
|
||||||
|
"darkslategray": "#2f4f4f",
|
||||||
|
"darkslategrey": "#2f4f4f",
|
||||||
|
"darkturquoise": "#00ced1",
|
||||||
|
"darkviolet": "#9400d3",
|
||||||
|
"deeppink": "#ff1493",
|
||||||
|
"deepskyblue": "#00bfff",
|
||||||
|
"dimgray": "#696969",
|
||||||
|
"dimgrey": "#696969",
|
||||||
|
"dodgerblue": "#1e90ff",
|
||||||
|
"firebrick": "#b22222",
|
||||||
|
"floralwhite": "#fffaf0",
|
||||||
|
"forestgreen": "#228b22",
|
||||||
|
"fuchsia": "#ff00ff",
|
||||||
|
"gainsboro": "#dcdcdc",
|
||||||
|
"ghostwhite": "#f8f8ff",
|
||||||
|
"gold": "#ffd700",
|
||||||
|
"goldenrod": "#daa520",
|
||||||
|
"gray": "#808080",
|
||||||
|
"grey": "#808080",
|
||||||
|
"green": "#008000",
|
||||||
|
"greenyellow": "#adff2f",
|
||||||
|
"honeydew": "#f0fff0",
|
||||||
|
"hotpink": "#ff69b4",
|
||||||
|
"indianred": "#cd5c5c",
|
||||||
|
"indigo": "#4b0082",
|
||||||
|
"ivory": "#fffff0",
|
||||||
|
"khaki": "#f0e68c",
|
||||||
|
"lavender": "#e6e6fa",
|
||||||
|
"lavenderblush": "#fff0f5",
|
||||||
|
"lawngreen": "#7cfc00",
|
||||||
|
"lemonchiffon": "#fffacd",
|
||||||
|
"lightblue": "#add8e6",
|
||||||
|
"lightcoral": "#f08080",
|
||||||
|
"lightcyan": "#e0ffff",
|
||||||
|
"lightgoldenrodyellow": "#fafad2",
|
||||||
|
"lightgreen": "#90ee90",
|
||||||
|
"lightgray": "#d3d3d3",
|
||||||
|
"lightgrey": "#d3d3d3",
|
||||||
|
"lightpink": "#ffb6c1",
|
||||||
|
"lightsalmon": "#ffa07a",
|
||||||
|
"lightseagreen": "#20b2aa",
|
||||||
|
"lightskyblue": "#87cefa",
|
||||||
|
"lightslategray": "#778899",
|
||||||
|
"lightslategrey": "#778899",
|
||||||
|
"lightsteelblue": "#b0c4de",
|
||||||
|
"lightyellow": "#ffffe0",
|
||||||
|
"lime": "#00ff00",
|
||||||
|
"limegreen": "#32cd32",
|
||||||
|
"linen": "#faf0e6",
|
||||||
|
"magenta": "#ff00ff",
|
||||||
|
"maroon": "#800000",
|
||||||
|
"mediumaquamarine": "#66cdaa",
|
||||||
|
"mediumblue": "#0000cd",
|
||||||
|
"mediumorchid": "#ba55d3",
|
||||||
|
"mediumpurple": "#9370db",
|
||||||
|
"mediumseagreen": "#3cb371",
|
||||||
|
"mediumslateblue": "#7b68ee",
|
||||||
|
"mediumspringgreen": "#00fa9a",
|
||||||
|
"mediumturquoise": "#48d1cc",
|
||||||
|
"mediumvioletred": "#c71585",
|
||||||
|
"midnightblue": "#191970",
|
||||||
|
"mintcream": "#f5fffa",
|
||||||
|
"mistyrose": "#ffe4e1",
|
||||||
|
"moccasin": "#ffe4b5",
|
||||||
|
"navajowhite": "#ffdead",
|
||||||
|
"navy": "#000080",
|
||||||
|
"oldlace": "#fdf5e6",
|
||||||
|
"olive": "#808000",
|
||||||
|
"olivedrab": "#6b8e23",
|
||||||
|
"orange": "#ffa500",
|
||||||
|
"orangered": "#ff4500",
|
||||||
|
"orchid": "#da70d6",
|
||||||
|
"palegoldenrod": "#eee8aa",
|
||||||
|
"palegreen": "#98fb98",
|
||||||
|
"paleturquoise": "#afeeee",
|
||||||
|
"palevioletred": "#db7093",
|
||||||
|
"papayawhip": "#ffefd5",
|
||||||
|
"peachpuff": "#ffdab9",
|
||||||
|
"peru": "#cd853f",
|
||||||
|
"pink": "#ffc0cb",
|
||||||
|
"plum": "#dda0dd",
|
||||||
|
"powderblue": "#b0e0e6",
|
||||||
|
"purple": "#800080",
|
||||||
|
"rebeccapurple": "#663399",
|
||||||
|
"red": "#ff0000",
|
||||||
|
"rosybrown": "#bc8f8f",
|
||||||
|
"royalblue": "#4169e1",
|
||||||
|
"saddlebrown": "#8b4513",
|
||||||
|
"salmon": "#fa8072",
|
||||||
|
"sandybrown": "#f4a460",
|
||||||
|
"seagreen": "#2e8b57",
|
||||||
|
"seashell": "#fff5ee",
|
||||||
|
"sienna": "#a0522d",
|
||||||
|
"silver": "#c0c0c0",
|
||||||
|
"skyblue": "#87ceeb",
|
||||||
|
"slateblue": "#6a5acd",
|
||||||
|
"slategray": "#708090",
|
||||||
|
"slategrey": "#708090",
|
||||||
|
"snow": "#fffafa",
|
||||||
|
"springgreen": "#00ff7f",
|
||||||
|
"steelblue": "#4682b4",
|
||||||
|
"tan": "#d2b48c",
|
||||||
|
"teal": "#008080",
|
||||||
|
"thistle": "#d8bfd8",
|
||||||
|
"tomato": "#ff6347",
|
||||||
|
"turquoise": "#40e0d0",
|
||||||
|
"violet": "#ee82ee",
|
||||||
|
"wheat": "#f5deb3",
|
||||||
|
"white": "#ffffff",
|
||||||
|
"whitesmoke": "#f5f5f5",
|
||||||
|
"yellow": "#ffff00",
|
||||||
|
"yellowgreen": "#9acd32",
|
||||||
|
}
|
||||||
898
venv/lib/python3.9/site-packages/PIL/ImageDraw.py
Normal file
|
|
@ -0,0 +1,898 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# drawing interface operations
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 1996-04-13 fl Created (experimental)
|
||||||
|
# 1996-08-07 fl Filled polygons, ellipses.
|
||||||
|
# 1996-08-13 fl Added text support
|
||||||
|
# 1998-06-28 fl Handle I and F images
|
||||||
|
# 1998-12-29 fl Added arc; use arc primitive to draw ellipses
|
||||||
|
# 1999-01-10 fl Added shape stuff (experimental)
|
||||||
|
# 1999-02-06 fl Added bitmap support
|
||||||
|
# 1999-02-11 fl Changed all primitives to take options
|
||||||
|
# 1999-02-20 fl Fixed backwards compatibility
|
||||||
|
# 2000-10-12 fl Copy on write, when necessary
|
||||||
|
# 2001-02-18 fl Use default ink for bitmap/text also in fill mode
|
||||||
|
# 2002-10-24 fl Added support for CSS-style color strings
|
||||||
|
# 2002-12-10 fl Added experimental support for RGBA-on-RGB drawing
|
||||||
|
# 2002-12-11 fl Refactored low-level drawing API (work in progress)
|
||||||
|
# 2004-08-26 fl Made Draw() a factory function, added getdraw() support
|
||||||
|
# 2004-09-04 fl Added width support to line primitive
|
||||||
|
# 2004-09-10 fl Added font mode handling
|
||||||
|
# 2006-06-19 fl Added font bearing support (getmask2)
|
||||||
|
#
|
||||||
|
# Copyright (c) 1997-2006 by Secret Labs AB
|
||||||
|
# Copyright (c) 1996-2006 by Fredrik Lundh
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
import math
|
||||||
|
import numbers
|
||||||
|
|
||||||
|
from . import Image, ImageColor
|
||||||
|
|
||||||
|
"""
|
||||||
|
A simple 2D drawing interface for PIL images.
|
||||||
|
<p>
|
||||||
|
Application code should use the <b>Draw</b> factory, instead of
|
||||||
|
directly.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class ImageDraw:
|
||||||
|
def __init__(self, im, mode=None):
|
||||||
|
"""
|
||||||
|
Create a drawing instance.
|
||||||
|
|
||||||
|
:param im: The image to draw in.
|
||||||
|
:param mode: Optional mode to use for color values. For RGB
|
||||||
|
images, this argument can be RGB or RGBA (to blend the
|
||||||
|
drawing into the image). For all other modes, this argument
|
||||||
|
must be the same as the image mode. If omitted, the mode
|
||||||
|
defaults to the mode of the image.
|
||||||
|
"""
|
||||||
|
im.load()
|
||||||
|
if im.readonly:
|
||||||
|
im._copy() # make it writeable
|
||||||
|
blend = 0
|
||||||
|
if mode is None:
|
||||||
|
mode = im.mode
|
||||||
|
if mode != im.mode:
|
||||||
|
if mode == "RGBA" and im.mode == "RGB":
|
||||||
|
blend = 1
|
||||||
|
else:
|
||||||
|
raise ValueError("mode mismatch")
|
||||||
|
if mode == "P":
|
||||||
|
self.palette = im.palette
|
||||||
|
else:
|
||||||
|
self.palette = None
|
||||||
|
self.im = im.im
|
||||||
|
self.draw = Image.core.draw(self.im, blend)
|
||||||
|
self.mode = mode
|
||||||
|
if mode in ("I", "F"):
|
||||||
|
self.ink = self.draw.draw_ink(1)
|
||||||
|
else:
|
||||||
|
self.ink = self.draw.draw_ink(-1)
|
||||||
|
if mode in ("1", "P", "I", "F"):
|
||||||
|
# FIXME: fix Fill2 to properly support matte for I+F images
|
||||||
|
self.fontmode = "1"
|
||||||
|
else:
|
||||||
|
self.fontmode = "L" # aliasing is okay for other modes
|
||||||
|
self.fill = 0
|
||||||
|
self.font = None
|
||||||
|
|
||||||
|
def getfont(self):
|
||||||
|
"""
|
||||||
|
Get the current default font.
|
||||||
|
|
||||||
|
:returns: An image font."""
|
||||||
|
if not self.font:
|
||||||
|
# FIXME: should add a font repository
|
||||||
|
from . import ImageFont
|
||||||
|
|
||||||
|
self.font = ImageFont.load_default()
|
||||||
|
return self.font
|
||||||
|
|
||||||
|
def _getink(self, ink, fill=None):
|
||||||
|
if ink is None and fill is None:
|
||||||
|
if self.fill:
|
||||||
|
fill = self.ink
|
||||||
|
else:
|
||||||
|
ink = self.ink
|
||||||
|
else:
|
||||||
|
if ink is not None:
|
||||||
|
if isinstance(ink, str):
|
||||||
|
ink = ImageColor.getcolor(ink, self.mode)
|
||||||
|
if self.palette and not isinstance(ink, numbers.Number):
|
||||||
|
ink = self.palette.getcolor(ink)
|
||||||
|
ink = self.draw.draw_ink(ink)
|
||||||
|
if fill is not None:
|
||||||
|
if isinstance(fill, str):
|
||||||
|
fill = ImageColor.getcolor(fill, self.mode)
|
||||||
|
if self.palette and not isinstance(fill, numbers.Number):
|
||||||
|
fill = self.palette.getcolor(fill)
|
||||||
|
fill = self.draw.draw_ink(fill)
|
||||||
|
return ink, fill
|
||||||
|
|
||||||
|
def arc(self, xy, start, end, fill=None, width=1):
|
||||||
|
"""Draw an arc."""
|
||||||
|
ink, fill = self._getink(fill)
|
||||||
|
if ink is not None:
|
||||||
|
self.draw.draw_arc(xy, start, end, ink, width)
|
||||||
|
|
||||||
|
def bitmap(self, xy, bitmap, fill=None):
|
||||||
|
"""Draw a bitmap."""
|
||||||
|
bitmap.load()
|
||||||
|
ink, fill = self._getink(fill)
|
||||||
|
if ink is None:
|
||||||
|
ink = fill
|
||||||
|
if ink is not None:
|
||||||
|
self.draw.draw_bitmap(xy, bitmap.im, ink)
|
||||||
|
|
||||||
|
def chord(self, xy, start, end, fill=None, outline=None, width=1):
|
||||||
|
"""Draw a chord."""
|
||||||
|
ink, fill = self._getink(outline, fill)
|
||||||
|
if fill is not None:
|
||||||
|
self.draw.draw_chord(xy, start, end, fill, 1)
|
||||||
|
if ink is not None and ink != fill and width != 0:
|
||||||
|
self.draw.draw_chord(xy, start, end, ink, 0, width)
|
||||||
|
|
||||||
|
def ellipse(self, xy, fill=None, outline=None, width=1):
|
||||||
|
"""Draw an ellipse."""
|
||||||
|
ink, fill = self._getink(outline, fill)
|
||||||
|
if fill is not None:
|
||||||
|
self.draw.draw_ellipse(xy, fill, 1)
|
||||||
|
if ink is not None and ink != fill and width != 0:
|
||||||
|
self.draw.draw_ellipse(xy, ink, 0, width)
|
||||||
|
|
||||||
|
def line(self, xy, fill=None, width=0, joint=None):
|
||||||
|
"""Draw a line, or a connected sequence of line segments."""
|
||||||
|
ink = self._getink(fill)[0]
|
||||||
|
if ink is not None:
|
||||||
|
self.draw.draw_lines(xy, ink, width)
|
||||||
|
if joint == "curve" and width > 4:
|
||||||
|
if not isinstance(xy[0], (list, tuple)):
|
||||||
|
xy = [tuple(xy[i : i + 2]) for i in range(0, len(xy), 2)]
|
||||||
|
for i in range(1, len(xy) - 1):
|
||||||
|
point = xy[i]
|
||||||
|
angles = [
|
||||||
|
math.degrees(math.atan2(end[0] - start[0], start[1] - end[1]))
|
||||||
|
% 360
|
||||||
|
for start, end in ((xy[i - 1], point), (point, xy[i + 1]))
|
||||||
|
]
|
||||||
|
if angles[0] == angles[1]:
|
||||||
|
# This is a straight line, so no joint is required
|
||||||
|
continue
|
||||||
|
|
||||||
|
def coord_at_angle(coord, angle):
|
||||||
|
x, y = coord
|
||||||
|
angle -= 90
|
||||||
|
distance = width / 2 - 1
|
||||||
|
return tuple(
|
||||||
|
[
|
||||||
|
p + (math.floor(p_d) if p_d > 0 else math.ceil(p_d))
|
||||||
|
for p, p_d in (
|
||||||
|
(x, distance * math.cos(math.radians(angle))),
|
||||||
|
(y, distance * math.sin(math.radians(angle))),
|
||||||
|
)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
flipped = (
|
||||||
|
angles[1] > angles[0] and angles[1] - 180 > angles[0]
|
||||||
|
) or (angles[1] < angles[0] and angles[1] + 180 > angles[0])
|
||||||
|
coords = [
|
||||||
|
(point[0] - width / 2 + 1, point[1] - width / 2 + 1),
|
||||||
|
(point[0] + width / 2 - 1, point[1] + width / 2 - 1),
|
||||||
|
]
|
||||||
|
if flipped:
|
||||||
|
start, end = (angles[1] + 90, angles[0] + 90)
|
||||||
|
else:
|
||||||
|
start, end = (angles[0] - 90, angles[1] - 90)
|
||||||
|
self.pieslice(coords, start - 90, end - 90, fill)
|
||||||
|
|
||||||
|
if width > 8:
|
||||||
|
# Cover potential gaps between the line and the joint
|
||||||
|
if flipped:
|
||||||
|
gapCoords = [
|
||||||
|
coord_at_angle(point, angles[0] + 90),
|
||||||
|
point,
|
||||||
|
coord_at_angle(point, angles[1] + 90),
|
||||||
|
]
|
||||||
|
else:
|
||||||
|
gapCoords = [
|
||||||
|
coord_at_angle(point, angles[0] - 90),
|
||||||
|
point,
|
||||||
|
coord_at_angle(point, angles[1] - 90),
|
||||||
|
]
|
||||||
|
self.line(gapCoords, fill, width=3)
|
||||||
|
|
||||||
|
def shape(self, shape, fill=None, outline=None):
|
||||||
|
"""(Experimental) Draw a shape."""
|
||||||
|
shape.close()
|
||||||
|
ink, fill = self._getink(outline, fill)
|
||||||
|
if fill is not None:
|
||||||
|
self.draw.draw_outline(shape, fill, 1)
|
||||||
|
if ink is not None and ink != fill:
|
||||||
|
self.draw.draw_outline(shape, ink, 0)
|
||||||
|
|
||||||
|
def pieslice(self, xy, start, end, fill=None, outline=None, width=1):
|
||||||
|
"""Draw a pieslice."""
|
||||||
|
ink, fill = self._getink(outline, fill)
|
||||||
|
if fill is not None:
|
||||||
|
self.draw.draw_pieslice(xy, start, end, fill, 1)
|
||||||
|
if ink is not None and ink != fill and width != 0:
|
||||||
|
self.draw.draw_pieslice(xy, start, end, ink, 0, width)
|
||||||
|
|
||||||
|
def point(self, xy, fill=None):
|
||||||
|
"""Draw one or more individual pixels."""
|
||||||
|
ink, fill = self._getink(fill)
|
||||||
|
if ink is not None:
|
||||||
|
self.draw.draw_points(xy, ink)
|
||||||
|
|
||||||
|
def polygon(self, xy, fill=None, outline=None):
|
||||||
|
"""Draw a polygon."""
|
||||||
|
ink, fill = self._getink(outline, fill)
|
||||||
|
if fill is not None:
|
||||||
|
self.draw.draw_polygon(xy, fill, 1)
|
||||||
|
if ink is not None and ink != fill:
|
||||||
|
self.draw.draw_polygon(xy, ink, 0)
|
||||||
|
|
||||||
|
def regular_polygon(
|
||||||
|
self, bounding_circle, n_sides, rotation=0, fill=None, outline=None
|
||||||
|
):
|
||||||
|
"""Draw a regular polygon."""
|
||||||
|
xy = _compute_regular_polygon_vertices(bounding_circle, n_sides, rotation)
|
||||||
|
self.polygon(xy, fill, outline)
|
||||||
|
|
||||||
|
def rectangle(self, xy, fill=None, outline=None, width=1):
|
||||||
|
"""Draw a rectangle."""
|
||||||
|
ink, fill = self._getink(outline, fill)
|
||||||
|
if fill is not None:
|
||||||
|
self.draw.draw_rectangle(xy, fill, 1)
|
||||||
|
if ink is not None and ink != fill and width != 0:
|
||||||
|
self.draw.draw_rectangle(xy, ink, 0, width)
|
||||||
|
|
||||||
|
def _multiline_check(self, text):
|
||||||
|
"""Draw text."""
|
||||||
|
split_character = "\n" if isinstance(text, str) else b"\n"
|
||||||
|
|
||||||
|
return split_character in text
|
||||||
|
|
||||||
|
def _multiline_split(self, text):
|
||||||
|
split_character = "\n" if isinstance(text, str) else b"\n"
|
||||||
|
|
||||||
|
return text.split(split_character)
|
||||||
|
|
||||||
|
def text(
|
||||||
|
self,
|
||||||
|
xy,
|
||||||
|
text,
|
||||||
|
fill=None,
|
||||||
|
font=None,
|
||||||
|
anchor=None,
|
||||||
|
spacing=4,
|
||||||
|
align="left",
|
||||||
|
direction=None,
|
||||||
|
features=None,
|
||||||
|
language=None,
|
||||||
|
stroke_width=0,
|
||||||
|
stroke_fill=None,
|
||||||
|
embedded_color=False,
|
||||||
|
*args,
|
||||||
|
**kwargs,
|
||||||
|
):
|
||||||
|
if self._multiline_check(text):
|
||||||
|
return self.multiline_text(
|
||||||
|
xy,
|
||||||
|
text,
|
||||||
|
fill,
|
||||||
|
font,
|
||||||
|
anchor,
|
||||||
|
spacing,
|
||||||
|
align,
|
||||||
|
direction,
|
||||||
|
features,
|
||||||
|
language,
|
||||||
|
stroke_width,
|
||||||
|
stroke_fill,
|
||||||
|
embedded_color,
|
||||||
|
)
|
||||||
|
|
||||||
|
if embedded_color and self.mode not in ("RGB", "RGBA"):
|
||||||
|
raise ValueError("Embedded color supported only in RGB and RGBA modes")
|
||||||
|
|
||||||
|
if font is None:
|
||||||
|
font = self.getfont()
|
||||||
|
|
||||||
|
def getink(fill):
|
||||||
|
ink, fill = self._getink(fill)
|
||||||
|
if ink is None:
|
||||||
|
return fill
|
||||||
|
return ink
|
||||||
|
|
||||||
|
def draw_text(ink, stroke_width=0, stroke_offset=None):
|
||||||
|
mode = self.fontmode
|
||||||
|
if stroke_width == 0 and embedded_color:
|
||||||
|
mode = "RGBA"
|
||||||
|
coord = xy
|
||||||
|
try:
|
||||||
|
mask, offset = font.getmask2(
|
||||||
|
text,
|
||||||
|
mode,
|
||||||
|
direction=direction,
|
||||||
|
features=features,
|
||||||
|
language=language,
|
||||||
|
stroke_width=stroke_width,
|
||||||
|
anchor=anchor,
|
||||||
|
ink=ink,
|
||||||
|
*args,
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
coord = coord[0] + offset[0], coord[1] + offset[1]
|
||||||
|
except AttributeError:
|
||||||
|
try:
|
||||||
|
mask = font.getmask(
|
||||||
|
text,
|
||||||
|
mode,
|
||||||
|
direction,
|
||||||
|
features,
|
||||||
|
language,
|
||||||
|
stroke_width,
|
||||||
|
anchor,
|
||||||
|
ink,
|
||||||
|
*args,
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
except TypeError:
|
||||||
|
mask = font.getmask(text)
|
||||||
|
if stroke_offset:
|
||||||
|
coord = coord[0] + stroke_offset[0], coord[1] + stroke_offset[1]
|
||||||
|
if mode == "RGBA":
|
||||||
|
# font.getmask2(mode="RGBA") returns color in RGB bands and mask in A
|
||||||
|
# extract mask and set text alpha
|
||||||
|
color, mask = mask, mask.getband(3)
|
||||||
|
color.fillband(3, (ink >> 24) & 0xFF)
|
||||||
|
coord2 = coord[0] + mask.size[0], coord[1] + mask.size[1]
|
||||||
|
self.im.paste(color, coord + coord2, mask)
|
||||||
|
else:
|
||||||
|
self.draw.draw_bitmap(coord, mask, ink)
|
||||||
|
|
||||||
|
ink = getink(fill)
|
||||||
|
if ink is not None:
|
||||||
|
stroke_ink = None
|
||||||
|
if stroke_width:
|
||||||
|
stroke_ink = getink(stroke_fill) if stroke_fill is not None else ink
|
||||||
|
|
||||||
|
if stroke_ink is not None:
|
||||||
|
# Draw stroked text
|
||||||
|
draw_text(stroke_ink, stroke_width)
|
||||||
|
|
||||||
|
# Draw normal text
|
||||||
|
draw_text(ink, 0)
|
||||||
|
else:
|
||||||
|
# Only draw normal text
|
||||||
|
draw_text(ink)
|
||||||
|
|
||||||
|
def multiline_text(
|
||||||
|
self,
|
||||||
|
xy,
|
||||||
|
text,
|
||||||
|
fill=None,
|
||||||
|
font=None,
|
||||||
|
anchor=None,
|
||||||
|
spacing=4,
|
||||||
|
align="left",
|
||||||
|
direction=None,
|
||||||
|
features=None,
|
||||||
|
language=None,
|
||||||
|
stroke_width=0,
|
||||||
|
stroke_fill=None,
|
||||||
|
embedded_color=False,
|
||||||
|
):
|
||||||
|
if direction == "ttb":
|
||||||
|
raise ValueError("ttb direction is unsupported for multiline text")
|
||||||
|
|
||||||
|
if anchor is None:
|
||||||
|
anchor = "la"
|
||||||
|
elif len(anchor) != 2:
|
||||||
|
raise ValueError("anchor must be a 2 character string")
|
||||||
|
elif anchor[1] in "tb":
|
||||||
|
raise ValueError("anchor not supported for multiline text")
|
||||||
|
|
||||||
|
widths = []
|
||||||
|
max_width = 0
|
||||||
|
lines = self._multiline_split(text)
|
||||||
|
line_spacing = (
|
||||||
|
self.textsize("A", font=font, stroke_width=stroke_width)[1] + spacing
|
||||||
|
)
|
||||||
|
for line in lines:
|
||||||
|
line_width = self.textlength(
|
||||||
|
line, font, direction=direction, features=features, language=language
|
||||||
|
)
|
||||||
|
widths.append(line_width)
|
||||||
|
max_width = max(max_width, line_width)
|
||||||
|
|
||||||
|
top = xy[1]
|
||||||
|
if anchor[1] == "m":
|
||||||
|
top -= (len(lines) - 1) * line_spacing / 2.0
|
||||||
|
elif anchor[1] == "d":
|
||||||
|
top -= (len(lines) - 1) * line_spacing
|
||||||
|
|
||||||
|
for idx, line in enumerate(lines):
|
||||||
|
left = xy[0]
|
||||||
|
width_difference = max_width - widths[idx]
|
||||||
|
|
||||||
|
# first align left by anchor
|
||||||
|
if anchor[0] == "m":
|
||||||
|
left -= width_difference / 2.0
|
||||||
|
elif anchor[0] == "r":
|
||||||
|
left -= width_difference
|
||||||
|
|
||||||
|
# then align by align parameter
|
||||||
|
if align == "left":
|
||||||
|
pass
|
||||||
|
elif align == "center":
|
||||||
|
left += width_difference / 2.0
|
||||||
|
elif align == "right":
|
||||||
|
left += width_difference
|
||||||
|
else:
|
||||||
|
raise ValueError('align must be "left", "center" or "right"')
|
||||||
|
|
||||||
|
self.text(
|
||||||
|
(left, top),
|
||||||
|
line,
|
||||||
|
fill,
|
||||||
|
font,
|
||||||
|
anchor,
|
||||||
|
direction=direction,
|
||||||
|
features=features,
|
||||||
|
language=language,
|
||||||
|
stroke_width=stroke_width,
|
||||||
|
stroke_fill=stroke_fill,
|
||||||
|
embedded_color=embedded_color,
|
||||||
|
)
|
||||||
|
top += line_spacing
|
||||||
|
|
||||||
|
def textsize(
|
||||||
|
self,
|
||||||
|
text,
|
||||||
|
font=None,
|
||||||
|
spacing=4,
|
||||||
|
direction=None,
|
||||||
|
features=None,
|
||||||
|
language=None,
|
||||||
|
stroke_width=0,
|
||||||
|
):
|
||||||
|
"""Get the size of a given string, in pixels."""
|
||||||
|
if self._multiline_check(text):
|
||||||
|
return self.multiline_textsize(
|
||||||
|
text, font, spacing, direction, features, language, stroke_width
|
||||||
|
)
|
||||||
|
|
||||||
|
if font is None:
|
||||||
|
font = self.getfont()
|
||||||
|
return font.getsize(text, direction, features, language, stroke_width)
|
||||||
|
|
||||||
|
def multiline_textsize(
|
||||||
|
self,
|
||||||
|
text,
|
||||||
|
font=None,
|
||||||
|
spacing=4,
|
||||||
|
direction=None,
|
||||||
|
features=None,
|
||||||
|
language=None,
|
||||||
|
stroke_width=0,
|
||||||
|
):
|
||||||
|
max_width = 0
|
||||||
|
lines = self._multiline_split(text)
|
||||||
|
line_spacing = (
|
||||||
|
self.textsize("A", font=font, stroke_width=stroke_width)[1] + spacing
|
||||||
|
)
|
||||||
|
for line in lines:
|
||||||
|
line_width, line_height = self.textsize(
|
||||||
|
line, font, spacing, direction, features, language, stroke_width
|
||||||
|
)
|
||||||
|
max_width = max(max_width, line_width)
|
||||||
|
return max_width, len(lines) * line_spacing - spacing
|
||||||
|
|
||||||
|
def textlength(
|
||||||
|
self,
|
||||||
|
text,
|
||||||
|
font=None,
|
||||||
|
direction=None,
|
||||||
|
features=None,
|
||||||
|
language=None,
|
||||||
|
embedded_color=False,
|
||||||
|
):
|
||||||
|
"""Get the length of a given string, in pixels with 1/64 precision."""
|
||||||
|
if self._multiline_check(text):
|
||||||
|
raise ValueError("can't measure length of multiline text")
|
||||||
|
if embedded_color and self.mode not in ("RGB", "RGBA"):
|
||||||
|
raise ValueError("Embedded color supported only in RGB and RGBA modes")
|
||||||
|
|
||||||
|
if font is None:
|
||||||
|
font = self.getfont()
|
||||||
|
mode = "RGBA" if embedded_color else self.fontmode
|
||||||
|
try:
|
||||||
|
return font.getlength(text, mode, direction, features, language)
|
||||||
|
except AttributeError:
|
||||||
|
size = self.textsize(
|
||||||
|
text, font, direction=direction, features=features, language=language
|
||||||
|
)
|
||||||
|
if direction == "ttb":
|
||||||
|
return size[1]
|
||||||
|
return size[0]
|
||||||
|
|
||||||
|
def textbbox(
|
||||||
|
self,
|
||||||
|
xy,
|
||||||
|
text,
|
||||||
|
font=None,
|
||||||
|
anchor=None,
|
||||||
|
spacing=4,
|
||||||
|
align="left",
|
||||||
|
direction=None,
|
||||||
|
features=None,
|
||||||
|
language=None,
|
||||||
|
stroke_width=0,
|
||||||
|
embedded_color=False,
|
||||||
|
):
|
||||||
|
"""Get the bounding box of a given string, in pixels."""
|
||||||
|
if embedded_color and self.mode not in ("RGB", "RGBA"):
|
||||||
|
raise ValueError("Embedded color supported only in RGB and RGBA modes")
|
||||||
|
|
||||||
|
if self._multiline_check(text):
|
||||||
|
return self.multiline_textbbox(
|
||||||
|
xy,
|
||||||
|
text,
|
||||||
|
font,
|
||||||
|
anchor,
|
||||||
|
spacing,
|
||||||
|
align,
|
||||||
|
direction,
|
||||||
|
features,
|
||||||
|
language,
|
||||||
|
stroke_width,
|
||||||
|
embedded_color,
|
||||||
|
)
|
||||||
|
|
||||||
|
if font is None:
|
||||||
|
font = self.getfont()
|
||||||
|
mode = "RGBA" if embedded_color else self.fontmode
|
||||||
|
bbox = font.getbbox(
|
||||||
|
text, mode, direction, features, language, stroke_width, anchor
|
||||||
|
)
|
||||||
|
return bbox[0] + xy[0], bbox[1] + xy[1], bbox[2] + xy[0], bbox[3] + xy[1]
|
||||||
|
|
||||||
|
def multiline_textbbox(
|
||||||
|
self,
|
||||||
|
xy,
|
||||||
|
text,
|
||||||
|
font=None,
|
||||||
|
anchor=None,
|
||||||
|
spacing=4,
|
||||||
|
align="left",
|
||||||
|
direction=None,
|
||||||
|
features=None,
|
||||||
|
language=None,
|
||||||
|
stroke_width=0,
|
||||||
|
embedded_color=False,
|
||||||
|
):
|
||||||
|
if direction == "ttb":
|
||||||
|
raise ValueError("ttb direction is unsupported for multiline text")
|
||||||
|
|
||||||
|
if anchor is None:
|
||||||
|
anchor = "la"
|
||||||
|
elif len(anchor) != 2:
|
||||||
|
raise ValueError("anchor must be a 2 character string")
|
||||||
|
elif anchor[1] in "tb":
|
||||||
|
raise ValueError("anchor not supported for multiline text")
|
||||||
|
|
||||||
|
widths = []
|
||||||
|
max_width = 0
|
||||||
|
lines = self._multiline_split(text)
|
||||||
|
line_spacing = (
|
||||||
|
self.textsize("A", font=font, stroke_width=stroke_width)[1] + spacing
|
||||||
|
)
|
||||||
|
for line in lines:
|
||||||
|
line_width = self.textlength(
|
||||||
|
line,
|
||||||
|
font,
|
||||||
|
direction=direction,
|
||||||
|
features=features,
|
||||||
|
language=language,
|
||||||
|
embedded_color=embedded_color,
|
||||||
|
)
|
||||||
|
widths.append(line_width)
|
||||||
|
max_width = max(max_width, line_width)
|
||||||
|
|
||||||
|
top = xy[1]
|
||||||
|
if anchor[1] == "m":
|
||||||
|
top -= (len(lines) - 1) * line_spacing / 2.0
|
||||||
|
elif anchor[1] == "d":
|
||||||
|
top -= (len(lines) - 1) * line_spacing
|
||||||
|
|
||||||
|
bbox = None
|
||||||
|
|
||||||
|
for idx, line in enumerate(lines):
|
||||||
|
left = xy[0]
|
||||||
|
width_difference = max_width - widths[idx]
|
||||||
|
|
||||||
|
# first align left by anchor
|
||||||
|
if anchor[0] == "m":
|
||||||
|
left -= width_difference / 2.0
|
||||||
|
elif anchor[0] == "r":
|
||||||
|
left -= width_difference
|
||||||
|
|
||||||
|
# then align by align parameter
|
||||||
|
if align == "left":
|
||||||
|
pass
|
||||||
|
elif align == "center":
|
||||||
|
left += width_difference / 2.0
|
||||||
|
elif align == "right":
|
||||||
|
left += width_difference
|
||||||
|
else:
|
||||||
|
raise ValueError('align must be "left", "center" or "right"')
|
||||||
|
|
||||||
|
bbox_line = self.textbbox(
|
||||||
|
(left, top),
|
||||||
|
line,
|
||||||
|
font,
|
||||||
|
anchor,
|
||||||
|
direction=direction,
|
||||||
|
features=features,
|
||||||
|
language=language,
|
||||||
|
stroke_width=stroke_width,
|
||||||
|
embedded_color=embedded_color,
|
||||||
|
)
|
||||||
|
if bbox is None:
|
||||||
|
bbox = bbox_line
|
||||||
|
else:
|
||||||
|
bbox = (
|
||||||
|
min(bbox[0], bbox_line[0]),
|
||||||
|
min(bbox[1], bbox_line[1]),
|
||||||
|
max(bbox[2], bbox_line[2]),
|
||||||
|
max(bbox[3], bbox_line[3]),
|
||||||
|
)
|
||||||
|
|
||||||
|
top += line_spacing
|
||||||
|
|
||||||
|
if bbox is None:
|
||||||
|
return xy[0], xy[1], xy[0], xy[1]
|
||||||
|
return bbox
|
||||||
|
|
||||||
|
|
||||||
|
def Draw(im, mode=None):
|
||||||
|
"""
|
||||||
|
A simple 2D drawing interface for PIL images.
|
||||||
|
|
||||||
|
:param im: The image to draw in.
|
||||||
|
:param mode: Optional mode to use for color values. For RGB
|
||||||
|
images, this argument can be RGB or RGBA (to blend the
|
||||||
|
drawing into the image). For all other modes, this argument
|
||||||
|
must be the same as the image mode. If omitted, the mode
|
||||||
|
defaults to the mode of the image.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
return im.getdraw(mode)
|
||||||
|
except AttributeError:
|
||||||
|
return ImageDraw(im, mode)
|
||||||
|
|
||||||
|
|
||||||
|
# experimental access to the outline API
|
||||||
|
try:
|
||||||
|
Outline = Image.core.outline
|
||||||
|
except AttributeError:
|
||||||
|
Outline = None
|
||||||
|
|
||||||
|
|
||||||
|
def getdraw(im=None, hints=None):
|
||||||
|
"""
|
||||||
|
(Experimental) A more advanced 2D drawing interface for PIL images,
|
||||||
|
based on the WCK interface.
|
||||||
|
|
||||||
|
:param im: The image to draw in.
|
||||||
|
:param hints: An optional list of hints.
|
||||||
|
:returns: A (drawing context, drawing resource factory) tuple.
|
||||||
|
"""
|
||||||
|
# FIXME: this needs more work!
|
||||||
|
# FIXME: come up with a better 'hints' scheme.
|
||||||
|
handler = None
|
||||||
|
if not hints or "nicest" in hints:
|
||||||
|
try:
|
||||||
|
from . import _imagingagg as handler
|
||||||
|
except ImportError:
|
||||||
|
pass
|
||||||
|
if handler is None:
|
||||||
|
from . import ImageDraw2 as handler
|
||||||
|
if im:
|
||||||
|
im = handler.Draw(im)
|
||||||
|
return im, handler
|
||||||
|
|
||||||
|
|
||||||
|
def floodfill(image, xy, value, border=None, thresh=0):
|
||||||
|
"""
|
||||||
|
(experimental) Fills a bounded region with a given color.
|
||||||
|
|
||||||
|
:param image: Target image.
|
||||||
|
:param xy: Seed position (a 2-item coordinate tuple). See
|
||||||
|
:ref:`coordinate-system`.
|
||||||
|
:param value: Fill color.
|
||||||
|
:param border: Optional border value. If given, the region consists of
|
||||||
|
pixels with a color different from the border color. If not given,
|
||||||
|
the region consists of pixels having the same color as the seed
|
||||||
|
pixel.
|
||||||
|
:param thresh: Optional threshold value which specifies a maximum
|
||||||
|
tolerable difference of a pixel value from the 'background' in
|
||||||
|
order for it to be replaced. Useful for filling regions of
|
||||||
|
non-homogeneous, but similar, colors.
|
||||||
|
"""
|
||||||
|
# based on an implementation by Eric S. Raymond
|
||||||
|
# amended by yo1995 @20180806
|
||||||
|
pixel = image.load()
|
||||||
|
x, y = xy
|
||||||
|
try:
|
||||||
|
background = pixel[x, y]
|
||||||
|
if _color_diff(value, background) <= thresh:
|
||||||
|
return # seed point already has fill color
|
||||||
|
pixel[x, y] = value
|
||||||
|
except (ValueError, IndexError):
|
||||||
|
return # seed point outside image
|
||||||
|
edge = {(x, y)}
|
||||||
|
# use a set to keep record of current and previous edge pixels
|
||||||
|
# to reduce memory consumption
|
||||||
|
full_edge = set()
|
||||||
|
while edge:
|
||||||
|
new_edge = set()
|
||||||
|
for (x, y) in edge: # 4 adjacent method
|
||||||
|
for (s, t) in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
|
||||||
|
# If already processed, or if a coordinate is negative, skip
|
||||||
|
if (s, t) in full_edge or s < 0 or t < 0:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
p = pixel[s, t]
|
||||||
|
except (ValueError, IndexError):
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
full_edge.add((s, t))
|
||||||
|
if border is None:
|
||||||
|
fill = _color_diff(p, background) <= thresh
|
||||||
|
else:
|
||||||
|
fill = p != value and p != border
|
||||||
|
if fill:
|
||||||
|
pixel[s, t] = value
|
||||||
|
new_edge.add((s, t))
|
||||||
|
full_edge = edge # discard pixels processed
|
||||||
|
edge = new_edge
|
||||||
|
|
||||||
|
|
||||||
|
def _compute_regular_polygon_vertices(bounding_circle, n_sides, rotation):
|
||||||
|
"""
|
||||||
|
Generate a list of vertices for a 2D regular polygon.
|
||||||
|
|
||||||
|
:param bounding_circle: The bounding circle is a tuple defined
|
||||||
|
by a point and radius. The polygon is inscribed in this circle.
|
||||||
|
(e.g. ``bounding_circle=(x, y, r)`` or ``((x, y), r)``)
|
||||||
|
:param n_sides: Number of sides
|
||||||
|
(e.g. ``n_sides=3`` for a triangle, ``6`` for a hexagon)
|
||||||
|
:param rotation: Apply an arbitrary rotation to the polygon
|
||||||
|
(e.g. ``rotation=90``, applies a 90 degree rotation)
|
||||||
|
:return: List of regular polygon vertices
|
||||||
|
(e.g. ``[(25, 50), (50, 50), (50, 25), (25, 25)]``)
|
||||||
|
|
||||||
|
How are the vertices computed?
|
||||||
|
1. Compute the following variables
|
||||||
|
- theta: Angle between the apothem & the nearest polygon vertex
|
||||||
|
- side_length: Length of each polygon edge
|
||||||
|
- centroid: Center of bounding circle (1st, 2nd elements of bounding_circle)
|
||||||
|
- polygon_radius: Polygon radius (last element of bounding_circle)
|
||||||
|
- angles: Location of each polygon vertex in polar grid
|
||||||
|
(e.g. A square with 0 degree rotation => [225.0, 315.0, 45.0, 135.0])
|
||||||
|
|
||||||
|
2. For each angle in angles, get the polygon vertex at that angle
|
||||||
|
The vertex is computed using the equation below.
|
||||||
|
X= xcos(φ) + ysin(φ)
|
||||||
|
Y= −xsin(φ) + ycos(φ)
|
||||||
|
|
||||||
|
Note:
|
||||||
|
φ = angle in degrees
|
||||||
|
x = 0
|
||||||
|
y = polygon_radius
|
||||||
|
|
||||||
|
The formula above assumes rotation around the origin.
|
||||||
|
In our case, we are rotating around the centroid.
|
||||||
|
To account for this, we use the formula below
|
||||||
|
X = xcos(φ) + ysin(φ) + centroid_x
|
||||||
|
Y = −xsin(φ) + ycos(φ) + centroid_y
|
||||||
|
"""
|
||||||
|
# 1. Error Handling
|
||||||
|
# 1.1 Check `n_sides` has an appropriate value
|
||||||
|
if not isinstance(n_sides, int):
|
||||||
|
raise TypeError("n_sides should be an int")
|
||||||
|
if n_sides < 3:
|
||||||
|
raise ValueError("n_sides should be an int > 2")
|
||||||
|
|
||||||
|
# 1.2 Check `bounding_circle` has an appropriate value
|
||||||
|
if not isinstance(bounding_circle, (list, tuple)):
|
||||||
|
raise TypeError("bounding_circle should be a tuple")
|
||||||
|
|
||||||
|
if len(bounding_circle) == 3:
|
||||||
|
*centroid, polygon_radius = bounding_circle
|
||||||
|
elif len(bounding_circle) == 2:
|
||||||
|
centroid, polygon_radius = bounding_circle
|
||||||
|
else:
|
||||||
|
raise ValueError(
|
||||||
|
"bounding_circle should contain 2D coordinates "
|
||||||
|
"and a radius (e.g. (x, y, r) or ((x, y), r) )"
|
||||||
|
)
|
||||||
|
|
||||||
|
if not all(isinstance(i, (int, float)) for i in (*centroid, polygon_radius)):
|
||||||
|
raise ValueError("bounding_circle should only contain numeric data")
|
||||||
|
|
||||||
|
if not len(centroid) == 2:
|
||||||
|
raise ValueError(
|
||||||
|
"bounding_circle centre should contain 2D coordinates (e.g. (x, y))"
|
||||||
|
)
|
||||||
|
|
||||||
|
if polygon_radius <= 0:
|
||||||
|
raise ValueError("bounding_circle radius should be > 0")
|
||||||
|
|
||||||
|
# 1.3 Check `rotation` has an appropriate value
|
||||||
|
if not isinstance(rotation, (int, float)):
|
||||||
|
raise ValueError("rotation should be an int or float")
|
||||||
|
|
||||||
|
# 2. Define Helper Functions
|
||||||
|
def _apply_rotation(point, degrees, centroid):
|
||||||
|
return (
|
||||||
|
round(
|
||||||
|
point[0] * math.cos(math.radians(360 - degrees))
|
||||||
|
- point[1] * math.sin(math.radians(360 - degrees))
|
||||||
|
+ centroid[0],
|
||||||
|
2,
|
||||||
|
),
|
||||||
|
round(
|
||||||
|
point[1] * math.cos(math.radians(360 - degrees))
|
||||||
|
+ point[0] * math.sin(math.radians(360 - degrees))
|
||||||
|
+ centroid[1],
|
||||||
|
2,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
def _compute_polygon_vertex(centroid, polygon_radius, angle):
|
||||||
|
start_point = [polygon_radius, 0]
|
||||||
|
return _apply_rotation(start_point, angle, centroid)
|
||||||
|
|
||||||
|
def _get_angles(n_sides, rotation):
|
||||||
|
angles = []
|
||||||
|
degrees = 360 / n_sides
|
||||||
|
# Start with the bottom left polygon vertex
|
||||||
|
current_angle = (270 - 0.5 * degrees) + rotation
|
||||||
|
for _ in range(0, n_sides):
|
||||||
|
angles.append(current_angle)
|
||||||
|
current_angle += degrees
|
||||||
|
if current_angle > 360:
|
||||||
|
current_angle -= 360
|
||||||
|
return angles
|
||||||
|
|
||||||
|
# 3. Variable Declarations
|
||||||
|
angles = _get_angles(n_sides, rotation)
|
||||||
|
|
||||||
|
# 4. Compute Vertices
|
||||||
|
return [
|
||||||
|
_compute_polygon_vertex(centroid, polygon_radius, angle) for angle in angles
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _color_diff(color1, color2):
|
||||||
|
"""
|
||||||
|
Uses 1-norm distance to calculate difference between two values.
|
||||||
|
"""
|
||||||
|
if isinstance(color2, tuple):
|
||||||
|
return sum([abs(color1[i] - color2[i]) for i in range(0, len(color2))])
|
||||||
|
else:
|
||||||
|
return abs(color1 - color2)
|
||||||
179
venv/lib/python3.9/site-packages/PIL/ImageDraw2.py
Normal file
|
|
@ -0,0 +1,179 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# WCK-style drawing interface operations
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 2003-12-07 fl created
|
||||||
|
# 2005-05-15 fl updated; added to PIL as ImageDraw2
|
||||||
|
# 2005-05-15 fl added text support
|
||||||
|
# 2005-05-20 fl added arc/chord/pieslice support
|
||||||
|
#
|
||||||
|
# Copyright (c) 2003-2005 by Secret Labs AB
|
||||||
|
# Copyright (c) 2003-2005 by Fredrik Lundh
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
|
||||||
|
"""
|
||||||
|
(Experimental) WCK-style drawing interface operations
|
||||||
|
|
||||||
|
.. seealso:: :py:mod:`PIL.ImageDraw`
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
from . import Image, ImageColor, ImageDraw, ImageFont, ImagePath
|
||||||
|
|
||||||
|
|
||||||
|
class Pen:
|
||||||
|
"""Stores an outline color and width."""
|
||||||
|
|
||||||
|
def __init__(self, color, width=1, opacity=255):
|
||||||
|
self.color = ImageColor.getrgb(color)
|
||||||
|
self.width = width
|
||||||
|
|
||||||
|
|
||||||
|
class Brush:
|
||||||
|
"""Stores a fill color"""
|
||||||
|
|
||||||
|
def __init__(self, color, opacity=255):
|
||||||
|
self.color = ImageColor.getrgb(color)
|
||||||
|
|
||||||
|
|
||||||
|
class Font:
|
||||||
|
"""Stores a TrueType font and color"""
|
||||||
|
|
||||||
|
def __init__(self, color, file, size=12):
|
||||||
|
# FIXME: add support for bitmap fonts
|
||||||
|
self.color = ImageColor.getrgb(color)
|
||||||
|
self.font = ImageFont.truetype(file, size)
|
||||||
|
|
||||||
|
|
||||||
|
class Draw:
|
||||||
|
"""
|
||||||
|
(Experimental) WCK-style drawing interface
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, image, size=None, color=None):
|
||||||
|
if not hasattr(image, "im"):
|
||||||
|
image = Image.new(image, size, color)
|
||||||
|
self.draw = ImageDraw.Draw(image)
|
||||||
|
self.image = image
|
||||||
|
self.transform = None
|
||||||
|
|
||||||
|
def flush(self):
|
||||||
|
return self.image
|
||||||
|
|
||||||
|
def render(self, op, xy, pen, brush=None):
|
||||||
|
# handle color arguments
|
||||||
|
outline = fill = None
|
||||||
|
width = 1
|
||||||
|
if isinstance(pen, Pen):
|
||||||
|
outline = pen.color
|
||||||
|
width = pen.width
|
||||||
|
elif isinstance(brush, Pen):
|
||||||
|
outline = brush.color
|
||||||
|
width = brush.width
|
||||||
|
if isinstance(brush, Brush):
|
||||||
|
fill = brush.color
|
||||||
|
elif isinstance(pen, Brush):
|
||||||
|
fill = pen.color
|
||||||
|
# handle transformation
|
||||||
|
if self.transform:
|
||||||
|
xy = ImagePath.Path(xy)
|
||||||
|
xy.transform(self.transform)
|
||||||
|
# render the item
|
||||||
|
if op == "line":
|
||||||
|
self.draw.line(xy, fill=outline, width=width)
|
||||||
|
else:
|
||||||
|
getattr(self.draw, op)(xy, fill=fill, outline=outline)
|
||||||
|
|
||||||
|
def settransform(self, offset):
|
||||||
|
"""Sets a transformation offset."""
|
||||||
|
(xoffset, yoffset) = offset
|
||||||
|
self.transform = (1, 0, xoffset, 0, 1, yoffset)
|
||||||
|
|
||||||
|
def arc(self, xy, start, end, *options):
|
||||||
|
"""
|
||||||
|
Draws an arc (a portion of a circle outline) between the start and end
|
||||||
|
angles, inside the given bounding box.
|
||||||
|
|
||||||
|
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.arc`
|
||||||
|
"""
|
||||||
|
self.render("arc", xy, start, end, *options)
|
||||||
|
|
||||||
|
def chord(self, xy, start, end, *options):
|
||||||
|
"""
|
||||||
|
Same as :py:meth:`~PIL.ImageDraw2.Draw.arc`, but connects the end points
|
||||||
|
with a straight line.
|
||||||
|
|
||||||
|
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.chord`
|
||||||
|
"""
|
||||||
|
self.render("chord", xy, start, end, *options)
|
||||||
|
|
||||||
|
def ellipse(self, xy, *options):
|
||||||
|
"""
|
||||||
|
Draws an ellipse inside the given bounding box.
|
||||||
|
|
||||||
|
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.ellipse`
|
||||||
|
"""
|
||||||
|
self.render("ellipse", xy, *options)
|
||||||
|
|
||||||
|
def line(self, xy, *options):
|
||||||
|
"""
|
||||||
|
Draws a line between the coordinates in the ``xy`` list.
|
||||||
|
|
||||||
|
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.line`
|
||||||
|
"""
|
||||||
|
self.render("line", xy, *options)
|
||||||
|
|
||||||
|
def pieslice(self, xy, start, end, *options):
|
||||||
|
"""
|
||||||
|
Same as arc, but also draws straight lines between the end points and the
|
||||||
|
center of the bounding box.
|
||||||
|
|
||||||
|
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.pieslice`
|
||||||
|
"""
|
||||||
|
self.render("pieslice", xy, start, end, *options)
|
||||||
|
|
||||||
|
def polygon(self, xy, *options):
|
||||||
|
"""
|
||||||
|
Draws a polygon.
|
||||||
|
|
||||||
|
The polygon outline consists of straight lines between the given
|
||||||
|
coordinates, plus a straight line between the last and the first
|
||||||
|
coordinate.
|
||||||
|
|
||||||
|
|
||||||
|
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.polygon`
|
||||||
|
"""
|
||||||
|
self.render("polygon", xy, *options)
|
||||||
|
|
||||||
|
def rectangle(self, xy, *options):
|
||||||
|
"""
|
||||||
|
Draws a rectangle.
|
||||||
|
|
||||||
|
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.rectangle`
|
||||||
|
"""
|
||||||
|
self.render("rectangle", xy, *options)
|
||||||
|
|
||||||
|
def text(self, xy, text, font):
|
||||||
|
"""
|
||||||
|
Draws the string at the given position.
|
||||||
|
|
||||||
|
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.text`
|
||||||
|
"""
|
||||||
|
if self.transform:
|
||||||
|
xy = ImagePath.Path(xy)
|
||||||
|
xy.transform(self.transform)
|
||||||
|
self.draw.text(xy, text, font=font.font, fill=font.color)
|
||||||
|
|
||||||
|
def textsize(self, text, font):
|
||||||
|
"""
|
||||||
|
Return the size of the given string, in pixels.
|
||||||
|
|
||||||
|
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textsize`
|
||||||
|
"""
|
||||||
|
return self.draw.textsize(text, font=font.font)
|
||||||
103
venv/lib/python3.9/site-packages/PIL/ImageEnhance.py
Normal file
|
|
@ -0,0 +1,103 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library.
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# image enhancement classes
|
||||||
|
#
|
||||||
|
# For a background, see "Image Processing By Interpolation and
|
||||||
|
# Extrapolation", Paul Haeberli and Douglas Voorhies. Available
|
||||||
|
# at http://www.graficaobscura.com/interp/index.html
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 1996-03-23 fl Created
|
||||||
|
# 2009-06-16 fl Fixed mean calculation
|
||||||
|
#
|
||||||
|
# Copyright (c) Secret Labs AB 1997.
|
||||||
|
# Copyright (c) Fredrik Lundh 1996.
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
from . import Image, ImageFilter, ImageStat
|
||||||
|
|
||||||
|
|
||||||
|
class _Enhance:
|
||||||
|
def enhance(self, factor):
|
||||||
|
"""
|
||||||
|
Returns an enhanced image.
|
||||||
|
|
||||||
|
:param factor: A floating point value controlling the enhancement.
|
||||||
|
Factor 1.0 always returns a copy of the original image,
|
||||||
|
lower factors mean less color (brightness, contrast,
|
||||||
|
etc), and higher values more. There are no restrictions
|
||||||
|
on this value.
|
||||||
|
:rtype: :py:class:`~PIL.Image.Image`
|
||||||
|
"""
|
||||||
|
return Image.blend(self.degenerate, self.image, factor)
|
||||||
|
|
||||||
|
|
||||||
|
class Color(_Enhance):
|
||||||
|
"""Adjust image color balance.
|
||||||
|
|
||||||
|
This class can be used to adjust the colour balance of an image, in
|
||||||
|
a manner similar to the controls on a colour TV set. An enhancement
|
||||||
|
factor of 0.0 gives a black and white image. A factor of 1.0 gives
|
||||||
|
the original image.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, image):
|
||||||
|
self.image = image
|
||||||
|
self.intermediate_mode = "L"
|
||||||
|
if "A" in image.getbands():
|
||||||
|
self.intermediate_mode = "LA"
|
||||||
|
|
||||||
|
self.degenerate = image.convert(self.intermediate_mode).convert(image.mode)
|
||||||
|
|
||||||
|
|
||||||
|
class Contrast(_Enhance):
|
||||||
|
"""Adjust image contrast.
|
||||||
|
|
||||||
|
This class can be used to control the contrast of an image, similar
|
||||||
|
to the contrast control on a TV set. An enhancement factor of 0.0
|
||||||
|
gives a solid grey image. A factor of 1.0 gives the original image.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, image):
|
||||||
|
self.image = image
|
||||||
|
mean = int(ImageStat.Stat(image.convert("L")).mean[0] + 0.5)
|
||||||
|
self.degenerate = Image.new("L", image.size, mean).convert(image.mode)
|
||||||
|
|
||||||
|
if "A" in image.getbands():
|
||||||
|
self.degenerate.putalpha(image.getchannel("A"))
|
||||||
|
|
||||||
|
|
||||||
|
class Brightness(_Enhance):
|
||||||
|
"""Adjust image brightness.
|
||||||
|
|
||||||
|
This class can be used to control the brightness of an image. An
|
||||||
|
enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the
|
||||||
|
original image.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, image):
|
||||||
|
self.image = image
|
||||||
|
self.degenerate = Image.new(image.mode, image.size, 0)
|
||||||
|
|
||||||
|
if "A" in image.getbands():
|
||||||
|
self.degenerate.putalpha(image.getchannel("A"))
|
||||||
|
|
||||||
|
|
||||||
|
class Sharpness(_Enhance):
|
||||||
|
"""Adjust image sharpness.
|
||||||
|
|
||||||
|
This class can be used to adjust the sharpness of an image. An
|
||||||
|
enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the
|
||||||
|
original image, and a factor of 2.0 gives a sharpened image.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, image):
|
||||||
|
self.image = image
|
||||||
|
self.degenerate = image.filter(ImageFilter.SMOOTH)
|
||||||
|
|
||||||
|
if "A" in image.getbands():
|
||||||
|
self.degenerate.putalpha(image.getchannel("A"))
|
||||||
697
venv/lib/python3.9/site-packages/PIL/ImageFile.py
Normal file
|
|
@ -0,0 +1,697 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library.
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# base class for image file handlers
|
||||||
|
#
|
||||||
|
# history:
|
||||||
|
# 1995-09-09 fl Created
|
||||||
|
# 1996-03-11 fl Fixed load mechanism.
|
||||||
|
# 1996-04-15 fl Added pcx/xbm decoders.
|
||||||
|
# 1996-04-30 fl Added encoders.
|
||||||
|
# 1996-12-14 fl Added load helpers
|
||||||
|
# 1997-01-11 fl Use encode_to_file where possible
|
||||||
|
# 1997-08-27 fl Flush output in _save
|
||||||
|
# 1998-03-05 fl Use memory mapping for some modes
|
||||||
|
# 1999-02-04 fl Use memory mapping also for "I;16" and "I;16B"
|
||||||
|
# 1999-05-31 fl Added image parser
|
||||||
|
# 2000-10-12 fl Set readonly flag on memory-mapped images
|
||||||
|
# 2002-03-20 fl Use better messages for common decoder errors
|
||||||
|
# 2003-04-21 fl Fall back on mmap/map_buffer if map is not available
|
||||||
|
# 2003-10-30 fl Added StubImageFile class
|
||||||
|
# 2004-02-25 fl Made incremental parser more robust
|
||||||
|
#
|
||||||
|
# Copyright (c) 1997-2004 by Secret Labs AB
|
||||||
|
# Copyright (c) 1995-2004 by Fredrik Lundh
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
import io
|
||||||
|
import struct
|
||||||
|
import sys
|
||||||
|
import warnings
|
||||||
|
|
||||||
|
from . import Image
|
||||||
|
from ._util import isPath
|
||||||
|
|
||||||
|
MAXBLOCK = 65536
|
||||||
|
|
||||||
|
SAFEBLOCK = 1024 * 1024
|
||||||
|
|
||||||
|
LOAD_TRUNCATED_IMAGES = False
|
||||||
|
"""Whether or not to load truncated image files. User code may change this."""
|
||||||
|
|
||||||
|
ERRORS = {
|
||||||
|
-1: "image buffer overrun error",
|
||||||
|
-2: "decoding error",
|
||||||
|
-3: "unknown error",
|
||||||
|
-8: "bad configuration",
|
||||||
|
-9: "out of memory error",
|
||||||
|
}
|
||||||
|
"""Dict of known error codes returned from :meth:`.PyDecoder.decode`."""
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# Helpers
|
||||||
|
|
||||||
|
|
||||||
|
def raise_oserror(error):
|
||||||
|
try:
|
||||||
|
message = Image.core.getcodecstatus(error)
|
||||||
|
except AttributeError:
|
||||||
|
message = ERRORS.get(error)
|
||||||
|
if not message:
|
||||||
|
message = f"decoder error {error}"
|
||||||
|
raise OSError(message + " when reading image file")
|
||||||
|
|
||||||
|
|
||||||
|
def raise_ioerror(error):
|
||||||
|
warnings.warn(
|
||||||
|
"raise_ioerror is deprecated and will be removed in a future release. "
|
||||||
|
"Use raise_oserror instead.",
|
||||||
|
DeprecationWarning,
|
||||||
|
)
|
||||||
|
return raise_oserror(error)
|
||||||
|
|
||||||
|
|
||||||
|
def _tilesort(t):
|
||||||
|
# sort on offset
|
||||||
|
return t[2]
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# ImageFile base class
|
||||||
|
|
||||||
|
|
||||||
|
class ImageFile(Image.Image):
|
||||||
|
"""Base class for image file format handlers."""
|
||||||
|
|
||||||
|
def __init__(self, fp=None, filename=None):
|
||||||
|
super().__init__()
|
||||||
|
|
||||||
|
self._min_frame = 0
|
||||||
|
|
||||||
|
self.custom_mimetype = None
|
||||||
|
|
||||||
|
self.tile = None
|
||||||
|
""" A list of tile descriptors, or ``None`` """
|
||||||
|
|
||||||
|
self.readonly = 1 # until we know better
|
||||||
|
|
||||||
|
self.decoderconfig = ()
|
||||||
|
self.decodermaxblock = MAXBLOCK
|
||||||
|
|
||||||
|
if isPath(fp):
|
||||||
|
# filename
|
||||||
|
self.fp = open(fp, "rb")
|
||||||
|
self.filename = fp
|
||||||
|
self._exclusive_fp = True
|
||||||
|
else:
|
||||||
|
# stream
|
||||||
|
self.fp = fp
|
||||||
|
self.filename = filename
|
||||||
|
# can be overridden
|
||||||
|
self._exclusive_fp = None
|
||||||
|
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
self._open()
|
||||||
|
except (
|
||||||
|
IndexError, # end of data
|
||||||
|
TypeError, # end of data (ord)
|
||||||
|
KeyError, # unsupported mode
|
||||||
|
EOFError, # got header but not the first frame
|
||||||
|
struct.error,
|
||||||
|
) as v:
|
||||||
|
raise SyntaxError(v) from v
|
||||||
|
|
||||||
|
if not self.mode or self.size[0] <= 0:
|
||||||
|
raise SyntaxError("not identified by this driver")
|
||||||
|
except BaseException:
|
||||||
|
# close the file only if we have opened it this constructor
|
||||||
|
if self._exclusive_fp:
|
||||||
|
self.fp.close()
|
||||||
|
raise
|
||||||
|
|
||||||
|
def get_format_mimetype(self):
|
||||||
|
if self.custom_mimetype:
|
||||||
|
return self.custom_mimetype
|
||||||
|
if self.format is not None:
|
||||||
|
return Image.MIME.get(self.format.upper())
|
||||||
|
|
||||||
|
def verify(self):
|
||||||
|
"""Check file integrity"""
|
||||||
|
|
||||||
|
# raise exception if something's wrong. must be called
|
||||||
|
# directly after open, and closes file when finished.
|
||||||
|
if self._exclusive_fp:
|
||||||
|
self.fp.close()
|
||||||
|
self.fp = None
|
||||||
|
|
||||||
|
def load(self):
|
||||||
|
"""Load image data based on tile list"""
|
||||||
|
|
||||||
|
if self.tile is None:
|
||||||
|
raise OSError("cannot load this image")
|
||||||
|
|
||||||
|
pixel = Image.Image.load(self)
|
||||||
|
if not self.tile:
|
||||||
|
return pixel
|
||||||
|
|
||||||
|
self.map = None
|
||||||
|
use_mmap = self.filename and len(self.tile) == 1
|
||||||
|
# As of pypy 2.1.0, memory mapping was failing here.
|
||||||
|
use_mmap = use_mmap and not hasattr(sys, "pypy_version_info")
|
||||||
|
|
||||||
|
readonly = 0
|
||||||
|
|
||||||
|
# look for read/seek overrides
|
||||||
|
try:
|
||||||
|
read = self.load_read
|
||||||
|
# don't use mmap if there are custom read/seek functions
|
||||||
|
use_mmap = False
|
||||||
|
except AttributeError:
|
||||||
|
read = self.fp.read
|
||||||
|
|
||||||
|
try:
|
||||||
|
seek = self.load_seek
|
||||||
|
use_mmap = False
|
||||||
|
except AttributeError:
|
||||||
|
seek = self.fp.seek
|
||||||
|
|
||||||
|
if use_mmap:
|
||||||
|
# try memory mapping
|
||||||
|
decoder_name, extents, offset, args = self.tile[0]
|
||||||
|
if (
|
||||||
|
decoder_name == "raw"
|
||||||
|
and len(args) >= 3
|
||||||
|
and args[0] == self.mode
|
||||||
|
and args[0] in Image._MAPMODES
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
if hasattr(Image.core, "map"):
|
||||||
|
# use built-in mapper WIN32 only
|
||||||
|
self.map = Image.core.map(self.filename)
|
||||||
|
self.map.seek(offset)
|
||||||
|
self.im = self.map.readimage(
|
||||||
|
self.mode, self.size, args[1], args[2]
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# use mmap, if possible
|
||||||
|
import mmap
|
||||||
|
|
||||||
|
with open(self.filename) as fp:
|
||||||
|
self.map = mmap.mmap(
|
||||||
|
fp.fileno(), 0, access=mmap.ACCESS_READ
|
||||||
|
)
|
||||||
|
self.im = Image.core.map_buffer(
|
||||||
|
self.map, self.size, decoder_name, offset, args
|
||||||
|
)
|
||||||
|
readonly = 1
|
||||||
|
# After trashing self.im,
|
||||||
|
# we might need to reload the palette data.
|
||||||
|
if self.palette:
|
||||||
|
self.palette.dirty = 1
|
||||||
|
except (AttributeError, OSError, ImportError):
|
||||||
|
self.map = None
|
||||||
|
|
||||||
|
self.load_prepare()
|
||||||
|
err_code = -3 # initialize to unknown error
|
||||||
|
if not self.map:
|
||||||
|
# sort tiles in file order
|
||||||
|
self.tile.sort(key=_tilesort)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# FIXME: This is a hack to handle TIFF's JpegTables tag.
|
||||||
|
prefix = self.tile_prefix
|
||||||
|
except AttributeError:
|
||||||
|
prefix = b""
|
||||||
|
|
||||||
|
for decoder_name, extents, offset, args in self.tile:
|
||||||
|
decoder = Image._getdecoder(
|
||||||
|
self.mode, decoder_name, args, self.decoderconfig
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
seek(offset)
|
||||||
|
decoder.setimage(self.im, extents)
|
||||||
|
if decoder.pulls_fd:
|
||||||
|
decoder.setfd(self.fp)
|
||||||
|
status, err_code = decoder.decode(b"")
|
||||||
|
else:
|
||||||
|
b = prefix
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
s = read(self.decodermaxblock)
|
||||||
|
except (IndexError, struct.error) as e:
|
||||||
|
# truncated png/gif
|
||||||
|
if LOAD_TRUNCATED_IMAGES:
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
raise OSError("image file is truncated") from e
|
||||||
|
|
||||||
|
if not s: # truncated jpeg
|
||||||
|
if LOAD_TRUNCATED_IMAGES:
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
raise OSError(
|
||||||
|
"image file is truncated "
|
||||||
|
f"({len(b)} bytes not processed)"
|
||||||
|
)
|
||||||
|
|
||||||
|
b = b + s
|
||||||
|
n, err_code = decoder.decode(b)
|
||||||
|
if n < 0:
|
||||||
|
break
|
||||||
|
b = b[n:]
|
||||||
|
finally:
|
||||||
|
# Need to cleanup here to prevent leaks
|
||||||
|
decoder.cleanup()
|
||||||
|
|
||||||
|
self.tile = []
|
||||||
|
self.readonly = readonly
|
||||||
|
|
||||||
|
self.load_end()
|
||||||
|
|
||||||
|
if self._exclusive_fp and self._close_exclusive_fp_after_loading:
|
||||||
|
self.fp.close()
|
||||||
|
self.fp = None
|
||||||
|
|
||||||
|
if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0:
|
||||||
|
# still raised if decoder fails to return anything
|
||||||
|
raise_oserror(err_code)
|
||||||
|
|
||||||
|
return Image.Image.load(self)
|
||||||
|
|
||||||
|
def load_prepare(self):
|
||||||
|
# create image memory if necessary
|
||||||
|
if not self.im or self.im.mode != self.mode or self.im.size != self.size:
|
||||||
|
self.im = Image.core.new(self.mode, self.size)
|
||||||
|
# create palette (optional)
|
||||||
|
if self.mode == "P":
|
||||||
|
Image.Image.load(self)
|
||||||
|
|
||||||
|
def load_end(self):
|
||||||
|
# may be overridden
|
||||||
|
pass
|
||||||
|
|
||||||
|
# may be defined for contained formats
|
||||||
|
# def load_seek(self, pos):
|
||||||
|
# pass
|
||||||
|
|
||||||
|
# may be defined for blocked formats (e.g. PNG)
|
||||||
|
# def load_read(self, bytes):
|
||||||
|
# pass
|
||||||
|
|
||||||
|
def _seek_check(self, frame):
|
||||||
|
if (
|
||||||
|
frame < self._min_frame
|
||||||
|
# Only check upper limit on frames if additional seek operations
|
||||||
|
# are not required to do so
|
||||||
|
or (
|
||||||
|
not (hasattr(self, "_n_frames") and self._n_frames is None)
|
||||||
|
and frame >= self.n_frames + self._min_frame
|
||||||
|
)
|
||||||
|
):
|
||||||
|
raise EOFError("attempt to seek outside sequence")
|
||||||
|
|
||||||
|
return self.tell() != frame
|
||||||
|
|
||||||
|
|
||||||
|
class StubImageFile(ImageFile):
|
||||||
|
"""
|
||||||
|
Base class for stub image loaders.
|
||||||
|
|
||||||
|
A stub loader is an image loader that can identify files of a
|
||||||
|
certain format, but relies on external code to load the file.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def _open(self):
|
||||||
|
raise NotImplementedError("StubImageFile subclass must implement _open")
|
||||||
|
|
||||||
|
def load(self):
|
||||||
|
loader = self._load()
|
||||||
|
if loader is None:
|
||||||
|
raise OSError(f"cannot find loader for this {self.format} file")
|
||||||
|
image = loader.load(self)
|
||||||
|
assert image is not None
|
||||||
|
# become the other object (!)
|
||||||
|
self.__class__ = image.__class__
|
||||||
|
self.__dict__ = image.__dict__
|
||||||
|
|
||||||
|
def _load(self):
|
||||||
|
"""(Hook) Find actual image loader."""
|
||||||
|
raise NotImplementedError("StubImageFile subclass must implement _load")
|
||||||
|
|
||||||
|
|
||||||
|
class Parser:
|
||||||
|
"""
|
||||||
|
Incremental image parser. This class implements the standard
|
||||||
|
feed/close consumer interface.
|
||||||
|
"""
|
||||||
|
|
||||||
|
incremental = None
|
||||||
|
image = None
|
||||||
|
data = None
|
||||||
|
decoder = None
|
||||||
|
offset = 0
|
||||||
|
finished = 0
|
||||||
|
|
||||||
|
def reset(self):
|
||||||
|
"""
|
||||||
|
(Consumer) Reset the parser. Note that you can only call this
|
||||||
|
method immediately after you've created a parser; parser
|
||||||
|
instances cannot be reused.
|
||||||
|
"""
|
||||||
|
assert self.data is None, "cannot reuse parsers"
|
||||||
|
|
||||||
|
def feed(self, data):
|
||||||
|
"""
|
||||||
|
(Consumer) Feed data to the parser.
|
||||||
|
|
||||||
|
:param data: A string buffer.
|
||||||
|
:exception OSError: If the parser failed to parse the image file.
|
||||||
|
"""
|
||||||
|
# collect data
|
||||||
|
|
||||||
|
if self.finished:
|
||||||
|
return
|
||||||
|
|
||||||
|
if self.data is None:
|
||||||
|
self.data = data
|
||||||
|
else:
|
||||||
|
self.data = self.data + data
|
||||||
|
|
||||||
|
# parse what we have
|
||||||
|
if self.decoder:
|
||||||
|
|
||||||
|
if self.offset > 0:
|
||||||
|
# skip header
|
||||||
|
skip = min(len(self.data), self.offset)
|
||||||
|
self.data = self.data[skip:]
|
||||||
|
self.offset = self.offset - skip
|
||||||
|
if self.offset > 0 or not self.data:
|
||||||
|
return
|
||||||
|
|
||||||
|
n, e = self.decoder.decode(self.data)
|
||||||
|
|
||||||
|
if n < 0:
|
||||||
|
# end of stream
|
||||||
|
self.data = None
|
||||||
|
self.finished = 1
|
||||||
|
if e < 0:
|
||||||
|
# decoding error
|
||||||
|
self.image = None
|
||||||
|
raise_oserror(e)
|
||||||
|
else:
|
||||||
|
# end of image
|
||||||
|
return
|
||||||
|
self.data = self.data[n:]
|
||||||
|
|
||||||
|
elif self.image:
|
||||||
|
|
||||||
|
# if we end up here with no decoder, this file cannot
|
||||||
|
# be incrementally parsed. wait until we've gotten all
|
||||||
|
# available data
|
||||||
|
pass
|
||||||
|
|
||||||
|
else:
|
||||||
|
|
||||||
|
# attempt to open this file
|
||||||
|
try:
|
||||||
|
with io.BytesIO(self.data) as fp:
|
||||||
|
im = Image.open(fp)
|
||||||
|
except OSError:
|
||||||
|
# traceback.print_exc()
|
||||||
|
pass # not enough data
|
||||||
|
else:
|
||||||
|
flag = hasattr(im, "load_seek") or hasattr(im, "load_read")
|
||||||
|
if flag or len(im.tile) != 1:
|
||||||
|
# custom load code, or multiple tiles
|
||||||
|
self.decode = None
|
||||||
|
else:
|
||||||
|
# initialize decoder
|
||||||
|
im.load_prepare()
|
||||||
|
d, e, o, a = im.tile[0]
|
||||||
|
im.tile = []
|
||||||
|
self.decoder = Image._getdecoder(im.mode, d, a, im.decoderconfig)
|
||||||
|
self.decoder.setimage(im.im, e)
|
||||||
|
|
||||||
|
# calculate decoder offset
|
||||||
|
self.offset = o
|
||||||
|
if self.offset <= len(self.data):
|
||||||
|
self.data = self.data[self.offset :]
|
||||||
|
self.offset = 0
|
||||||
|
|
||||||
|
self.image = im
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *args):
|
||||||
|
self.close()
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
"""
|
||||||
|
(Consumer) Close the stream.
|
||||||
|
|
||||||
|
:returns: An image object.
|
||||||
|
:exception OSError: If the parser failed to parse the image file either
|
||||||
|
because it cannot be identified or cannot be
|
||||||
|
decoded.
|
||||||
|
"""
|
||||||
|
# finish decoding
|
||||||
|
if self.decoder:
|
||||||
|
# get rid of what's left in the buffers
|
||||||
|
self.feed(b"")
|
||||||
|
self.data = self.decoder = None
|
||||||
|
if not self.finished:
|
||||||
|
raise OSError("image was incomplete")
|
||||||
|
if not self.image:
|
||||||
|
raise OSError("cannot parse this image")
|
||||||
|
if self.data:
|
||||||
|
# incremental parsing not possible; reopen the file
|
||||||
|
# not that we have all data
|
||||||
|
with io.BytesIO(self.data) as fp:
|
||||||
|
try:
|
||||||
|
self.image = Image.open(fp)
|
||||||
|
finally:
|
||||||
|
self.image.load()
|
||||||
|
return self.image
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _save(im, fp, tile, bufsize=0):
|
||||||
|
"""Helper to save image based on tile list
|
||||||
|
|
||||||
|
:param im: Image object.
|
||||||
|
:param fp: File object.
|
||||||
|
:param tile: Tile list.
|
||||||
|
:param bufsize: Optional buffer size
|
||||||
|
"""
|
||||||
|
|
||||||
|
im.load()
|
||||||
|
if not hasattr(im, "encoderconfig"):
|
||||||
|
im.encoderconfig = ()
|
||||||
|
tile.sort(key=_tilesort)
|
||||||
|
# FIXME: make MAXBLOCK a configuration parameter
|
||||||
|
# It would be great if we could have the encoder specify what it needs
|
||||||
|
# But, it would need at least the image size in most cases. RawEncode is
|
||||||
|
# a tricky case.
|
||||||
|
bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4) # see RawEncode.c
|
||||||
|
if fp == sys.stdout:
|
||||||
|
fp.flush()
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
fh = fp.fileno()
|
||||||
|
fp.flush()
|
||||||
|
except (AttributeError, io.UnsupportedOperation) as exc:
|
||||||
|
# compress to Python file-compatible object
|
||||||
|
for e, b, o, a in tile:
|
||||||
|
e = Image._getencoder(im.mode, e, a, im.encoderconfig)
|
||||||
|
if o > 0:
|
||||||
|
fp.seek(o)
|
||||||
|
e.setimage(im.im, b)
|
||||||
|
if e.pushes_fd:
|
||||||
|
e.setfd(fp)
|
||||||
|
l, s = e.encode_to_pyfd()
|
||||||
|
else:
|
||||||
|
while True:
|
||||||
|
l, s, d = e.encode(bufsize)
|
||||||
|
fp.write(d)
|
||||||
|
if s:
|
||||||
|
break
|
||||||
|
if s < 0:
|
||||||
|
raise OSError(f"encoder error {s} when writing image file") from exc
|
||||||
|
e.cleanup()
|
||||||
|
else:
|
||||||
|
# slight speedup: compress to real file object
|
||||||
|
for e, b, o, a in tile:
|
||||||
|
e = Image._getencoder(im.mode, e, a, im.encoderconfig)
|
||||||
|
if o > 0:
|
||||||
|
fp.seek(o)
|
||||||
|
e.setimage(im.im, b)
|
||||||
|
if e.pushes_fd:
|
||||||
|
e.setfd(fp)
|
||||||
|
l, s = e.encode_to_pyfd()
|
||||||
|
else:
|
||||||
|
s = e.encode_to_file(fh, bufsize)
|
||||||
|
if s < 0:
|
||||||
|
raise OSError(f"encoder error {s} when writing image file")
|
||||||
|
e.cleanup()
|
||||||
|
if hasattr(fp, "flush"):
|
||||||
|
fp.flush()
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_read(fp, size):
|
||||||
|
"""
|
||||||
|
Reads large blocks in a safe way. Unlike fp.read(n), this function
|
||||||
|
doesn't trust the user. If the requested size is larger than
|
||||||
|
SAFEBLOCK, the file is read block by block.
|
||||||
|
|
||||||
|
:param fp: File handle. Must implement a <b>read</b> method.
|
||||||
|
:param size: Number of bytes to read.
|
||||||
|
:returns: A string containing up to <i>size</i> bytes of data.
|
||||||
|
"""
|
||||||
|
if size <= 0:
|
||||||
|
return b""
|
||||||
|
if size <= SAFEBLOCK:
|
||||||
|
return fp.read(size)
|
||||||
|
data = []
|
||||||
|
while size > 0:
|
||||||
|
block = fp.read(min(size, SAFEBLOCK))
|
||||||
|
if not block:
|
||||||
|
break
|
||||||
|
data.append(block)
|
||||||
|
size -= len(block)
|
||||||
|
return b"".join(data)
|
||||||
|
|
||||||
|
|
||||||
|
class PyCodecState:
|
||||||
|
def __init__(self):
|
||||||
|
self.xsize = 0
|
||||||
|
self.ysize = 0
|
||||||
|
self.xoff = 0
|
||||||
|
self.yoff = 0
|
||||||
|
|
||||||
|
def extents(self):
|
||||||
|
return (self.xoff, self.yoff, self.xoff + self.xsize, self.yoff + self.ysize)
|
||||||
|
|
||||||
|
|
||||||
|
class PyDecoder:
|
||||||
|
"""
|
||||||
|
Python implementation of a format decoder. Override this class and
|
||||||
|
add the decoding logic in the :meth:`decode` method.
|
||||||
|
|
||||||
|
See :ref:`Writing Your Own File Decoder in Python<file-decoders-py>`
|
||||||
|
"""
|
||||||
|
|
||||||
|
_pulls_fd = False
|
||||||
|
|
||||||
|
def __init__(self, mode, *args):
|
||||||
|
self.im = None
|
||||||
|
self.state = PyCodecState()
|
||||||
|
self.fd = None
|
||||||
|
self.mode = mode
|
||||||
|
self.init(args)
|
||||||
|
|
||||||
|
def init(self, args):
|
||||||
|
"""
|
||||||
|
Override to perform decoder specific initialization
|
||||||
|
|
||||||
|
:param args: Array of args items from the tile entry
|
||||||
|
:returns: None
|
||||||
|
"""
|
||||||
|
self.args = args
|
||||||
|
|
||||||
|
@property
|
||||||
|
def pulls_fd(self):
|
||||||
|
return self._pulls_fd
|
||||||
|
|
||||||
|
def decode(self, buffer):
|
||||||
|
"""
|
||||||
|
Override to perform the decoding process.
|
||||||
|
|
||||||
|
:param buffer: A bytes object with the data to be decoded.
|
||||||
|
:returns: A tuple of ``(bytes consumed, errcode)``.
|
||||||
|
If finished with decoding return <0 for the bytes consumed.
|
||||||
|
Err codes are from :data:`.ImageFile.ERRORS`.
|
||||||
|
"""
|
||||||
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
def cleanup(self):
|
||||||
|
"""
|
||||||
|
Override to perform decoder specific cleanup
|
||||||
|
|
||||||
|
:returns: None
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def setfd(self, fd):
|
||||||
|
"""
|
||||||
|
Called from ImageFile to set the python file-like object
|
||||||
|
|
||||||
|
:param fd: A python file-like object
|
||||||
|
:returns: None
|
||||||
|
"""
|
||||||
|
self.fd = fd
|
||||||
|
|
||||||
|
def setimage(self, im, extents=None):
|
||||||
|
"""
|
||||||
|
Called from ImageFile to set the core output image for the decoder
|
||||||
|
|
||||||
|
:param im: A core image object
|
||||||
|
:param extents: a 4 tuple of (x0, y0, x1, y1) defining the rectangle
|
||||||
|
for this tile
|
||||||
|
:returns: None
|
||||||
|
"""
|
||||||
|
|
||||||
|
# following c code
|
||||||
|
self.im = im
|
||||||
|
|
||||||
|
if extents:
|
||||||
|
(x0, y0, x1, y1) = extents
|
||||||
|
else:
|
||||||
|
(x0, y0, x1, y1) = (0, 0, 0, 0)
|
||||||
|
|
||||||
|
if x0 == 0 and x1 == 0:
|
||||||
|
self.state.xsize, self.state.ysize = self.im.size
|
||||||
|
else:
|
||||||
|
self.state.xoff = x0
|
||||||
|
self.state.yoff = y0
|
||||||
|
self.state.xsize = x1 - x0
|
||||||
|
self.state.ysize = y1 - y0
|
||||||
|
|
||||||
|
if self.state.xsize <= 0 or self.state.ysize <= 0:
|
||||||
|
raise ValueError("Size cannot be negative")
|
||||||
|
|
||||||
|
if (
|
||||||
|
self.state.xsize + self.state.xoff > self.im.size[0]
|
||||||
|
or self.state.ysize + self.state.yoff > self.im.size[1]
|
||||||
|
):
|
||||||
|
raise ValueError("Tile cannot extend outside image")
|
||||||
|
|
||||||
|
def set_as_raw(self, data, rawmode=None):
|
||||||
|
"""
|
||||||
|
Convenience method to set the internal image from a stream of raw data
|
||||||
|
|
||||||
|
:param data: Bytes to be set
|
||||||
|
:param rawmode: The rawmode to be used for the decoder.
|
||||||
|
If not specified, it will default to the mode of the image
|
||||||
|
:returns: None
|
||||||
|
"""
|
||||||
|
|
||||||
|
if not rawmode:
|
||||||
|
rawmode = self.mode
|
||||||
|
d = Image._getdecoder(self.mode, "raw", (rawmode))
|
||||||
|
d.setimage(self.im, self.state.extents())
|
||||||
|
s = d.decode(data)
|
||||||
|
|
||||||
|
if s[0] >= 0:
|
||||||
|
raise ValueError("not enough image data")
|
||||||
|
if s[1] != 0:
|
||||||
|
raise ValueError("cannot decode image data")
|
||||||
534
venv/lib/python3.9/site-packages/PIL/ImageFilter.py
Normal file
|
|
@ -0,0 +1,534 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library.
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# standard filters
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 1995-11-27 fl Created
|
||||||
|
# 2002-06-08 fl Added rank and mode filters
|
||||||
|
# 2003-09-15 fl Fixed rank calculation in rank filter; added expand call
|
||||||
|
#
|
||||||
|
# Copyright (c) 1997-2003 by Secret Labs AB.
|
||||||
|
# Copyright (c) 1995-2002 by Fredrik Lundh.
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
import functools
|
||||||
|
|
||||||
|
try:
|
||||||
|
import numpy
|
||||||
|
except ImportError: # pragma: no cover
|
||||||
|
numpy = None
|
||||||
|
|
||||||
|
|
||||||
|
class Filter:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class MultibandFilter(Filter):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class BuiltinFilter(MultibandFilter):
|
||||||
|
def filter(self, image):
|
||||||
|
if image.mode == "P":
|
||||||
|
raise ValueError("cannot filter palette images")
|
||||||
|
return image.filter(*self.filterargs)
|
||||||
|
|
||||||
|
|
||||||
|
class Kernel(BuiltinFilter):
|
||||||
|
"""
|
||||||
|
Create a convolution kernel. The current version only
|
||||||
|
supports 3x3 and 5x5 integer and floating point kernels.
|
||||||
|
|
||||||
|
In the current version, kernels can only be applied to
|
||||||
|
"L" and "RGB" images.
|
||||||
|
|
||||||
|
:param size: Kernel size, given as (width, height). In the current
|
||||||
|
version, this must be (3,3) or (5,5).
|
||||||
|
:param kernel: A sequence containing kernel weights.
|
||||||
|
:param scale: Scale factor. If given, the result for each pixel is
|
||||||
|
divided by this value. The default is the sum of the
|
||||||
|
kernel weights.
|
||||||
|
:param offset: Offset. If given, this value is added to the result,
|
||||||
|
after it has been divided by the scale factor.
|
||||||
|
"""
|
||||||
|
|
||||||
|
name = "Kernel"
|
||||||
|
|
||||||
|
def __init__(self, size, kernel, scale=None, offset=0):
|
||||||
|
if scale is None:
|
||||||
|
# default scale is sum of kernel
|
||||||
|
scale = functools.reduce(lambda a, b: a + b, kernel)
|
||||||
|
if size[0] * size[1] != len(kernel):
|
||||||
|
raise ValueError("not enough coefficients in kernel")
|
||||||
|
self.filterargs = size, scale, offset, kernel
|
||||||
|
|
||||||
|
|
||||||
|
class RankFilter(Filter):
|
||||||
|
"""
|
||||||
|
Create a rank filter. The rank filter sorts all pixels in
|
||||||
|
a window of the given size, and returns the ``rank``'th value.
|
||||||
|
|
||||||
|
:param size: The kernel size, in pixels.
|
||||||
|
:param rank: What pixel value to pick. Use 0 for a min filter,
|
||||||
|
``size * size / 2`` for a median filter, ``size * size - 1``
|
||||||
|
for a max filter, etc.
|
||||||
|
"""
|
||||||
|
|
||||||
|
name = "Rank"
|
||||||
|
|
||||||
|
def __init__(self, size, rank):
|
||||||
|
self.size = size
|
||||||
|
self.rank = rank
|
||||||
|
|
||||||
|
def filter(self, image):
|
||||||
|
if image.mode == "P":
|
||||||
|
raise ValueError("cannot filter palette images")
|
||||||
|
image = image.expand(self.size // 2, self.size // 2)
|
||||||
|
return image.rankfilter(self.size, self.rank)
|
||||||
|
|
||||||
|
|
||||||
|
class MedianFilter(RankFilter):
|
||||||
|
"""
|
||||||
|
Create a median filter. Picks the median pixel value in a window with the
|
||||||
|
given size.
|
||||||
|
|
||||||
|
:param size: The kernel size, in pixels.
|
||||||
|
"""
|
||||||
|
|
||||||
|
name = "Median"
|
||||||
|
|
||||||
|
def __init__(self, size=3):
|
||||||
|
self.size = size
|
||||||
|
self.rank = size * size // 2
|
||||||
|
|
||||||
|
|
||||||
|
class MinFilter(RankFilter):
|
||||||
|
"""
|
||||||
|
Create a min filter. Picks the lowest pixel value in a window with the
|
||||||
|
given size.
|
||||||
|
|
||||||
|
:param size: The kernel size, in pixels.
|
||||||
|
"""
|
||||||
|
|
||||||
|
name = "Min"
|
||||||
|
|
||||||
|
def __init__(self, size=3):
|
||||||
|
self.size = size
|
||||||
|
self.rank = 0
|
||||||
|
|
||||||
|
|
||||||
|
class MaxFilter(RankFilter):
|
||||||
|
"""
|
||||||
|
Create a max filter. Picks the largest pixel value in a window with the
|
||||||
|
given size.
|
||||||
|
|
||||||
|
:param size: The kernel size, in pixels.
|
||||||
|
"""
|
||||||
|
|
||||||
|
name = "Max"
|
||||||
|
|
||||||
|
def __init__(self, size=3):
|
||||||
|
self.size = size
|
||||||
|
self.rank = size * size - 1
|
||||||
|
|
||||||
|
|
||||||
|
class ModeFilter(Filter):
|
||||||
|
"""
|
||||||
|
Create a mode filter. Picks the most frequent pixel value in a box with the
|
||||||
|
given size. Pixel values that occur only once or twice are ignored; if no
|
||||||
|
pixel value occurs more than twice, the original pixel value is preserved.
|
||||||
|
|
||||||
|
:param size: The kernel size, in pixels.
|
||||||
|
"""
|
||||||
|
|
||||||
|
name = "Mode"
|
||||||
|
|
||||||
|
def __init__(self, size=3):
|
||||||
|
self.size = size
|
||||||
|
|
||||||
|
def filter(self, image):
|
||||||
|
return image.modefilter(self.size)
|
||||||
|
|
||||||
|
|
||||||
|
class GaussianBlur(MultibandFilter):
|
||||||
|
"""Gaussian blur filter.
|
||||||
|
|
||||||
|
:param radius: Blur radius.
|
||||||
|
"""
|
||||||
|
|
||||||
|
name = "GaussianBlur"
|
||||||
|
|
||||||
|
def __init__(self, radius=2):
|
||||||
|
self.radius = radius
|
||||||
|
|
||||||
|
def filter(self, image):
|
||||||
|
return image.gaussian_blur(self.radius)
|
||||||
|
|
||||||
|
|
||||||
|
class BoxBlur(MultibandFilter):
|
||||||
|
"""Blurs the image by setting each pixel to the average value of the pixels
|
||||||
|
in a square box extending radius pixels in each direction.
|
||||||
|
Supports float radius of arbitrary size. Uses an optimized implementation
|
||||||
|
which runs in linear time relative to the size of the image
|
||||||
|
for any radius value.
|
||||||
|
|
||||||
|
:param radius: Size of the box in one direction. Radius 0 does not blur,
|
||||||
|
returns an identical image. Radius 1 takes 1 pixel
|
||||||
|
in each direction, i.e. 9 pixels in total.
|
||||||
|
"""
|
||||||
|
|
||||||
|
name = "BoxBlur"
|
||||||
|
|
||||||
|
def __init__(self, radius):
|
||||||
|
self.radius = radius
|
||||||
|
|
||||||
|
def filter(self, image):
|
||||||
|
return image.box_blur(self.radius)
|
||||||
|
|
||||||
|
|
||||||
|
class UnsharpMask(MultibandFilter):
|
||||||
|
"""Unsharp mask filter.
|
||||||
|
|
||||||
|
See Wikipedia's entry on `digital unsharp masking`_ for an explanation of
|
||||||
|
the parameters.
|
||||||
|
|
||||||
|
:param radius: Blur Radius
|
||||||
|
:param percent: Unsharp strength, in percent
|
||||||
|
:param threshold: Threshold controls the minimum brightness change that
|
||||||
|
will be sharpened
|
||||||
|
|
||||||
|
.. _digital unsharp masking: https://en.wikipedia.org/wiki/Unsharp_masking#Digital_unsharp_masking
|
||||||
|
|
||||||
|
""" # noqa: E501
|
||||||
|
|
||||||
|
name = "UnsharpMask"
|
||||||
|
|
||||||
|
def __init__(self, radius=2, percent=150, threshold=3):
|
||||||
|
self.radius = radius
|
||||||
|
self.percent = percent
|
||||||
|
self.threshold = threshold
|
||||||
|
|
||||||
|
def filter(self, image):
|
||||||
|
return image.unsharp_mask(self.radius, self.percent, self.threshold)
|
||||||
|
|
||||||
|
|
||||||
|
class BLUR(BuiltinFilter):
|
||||||
|
name = "Blur"
|
||||||
|
# fmt: off
|
||||||
|
filterargs = (5, 5), 16, 0, (
|
||||||
|
1, 1, 1, 1, 1,
|
||||||
|
1, 0, 0, 0, 1,
|
||||||
|
1, 0, 0, 0, 1,
|
||||||
|
1, 0, 0, 0, 1,
|
||||||
|
1, 1, 1, 1, 1,
|
||||||
|
)
|
||||||
|
# fmt: on
|
||||||
|
|
||||||
|
|
||||||
|
class CONTOUR(BuiltinFilter):
|
||||||
|
name = "Contour"
|
||||||
|
# fmt: off
|
||||||
|
filterargs = (3, 3), 1, 255, (
|
||||||
|
-1, -1, -1,
|
||||||
|
-1, 8, -1,
|
||||||
|
-1, -1, -1,
|
||||||
|
)
|
||||||
|
# fmt: on
|
||||||
|
|
||||||
|
|
||||||
|
class DETAIL(BuiltinFilter):
|
||||||
|
name = "Detail"
|
||||||
|
# fmt: off
|
||||||
|
filterargs = (3, 3), 6, 0, (
|
||||||
|
0, -1, 0,
|
||||||
|
-1, 10, -1,
|
||||||
|
0, -1, 0,
|
||||||
|
)
|
||||||
|
# fmt: on
|
||||||
|
|
||||||
|
|
||||||
|
class EDGE_ENHANCE(BuiltinFilter):
|
||||||
|
name = "Edge-enhance"
|
||||||
|
# fmt: off
|
||||||
|
filterargs = (3, 3), 2, 0, (
|
||||||
|
-1, -1, -1,
|
||||||
|
-1, 10, -1,
|
||||||
|
-1, -1, -1,
|
||||||
|
)
|
||||||
|
# fmt: on
|
||||||
|
|
||||||
|
|
||||||
|
class EDGE_ENHANCE_MORE(BuiltinFilter):
|
||||||
|
name = "Edge-enhance More"
|
||||||
|
# fmt: off
|
||||||
|
filterargs = (3, 3), 1, 0, (
|
||||||
|
-1, -1, -1,
|
||||||
|
-1, 9, -1,
|
||||||
|
-1, -1, -1,
|
||||||
|
)
|
||||||
|
# fmt: on
|
||||||
|
|
||||||
|
|
||||||
|
class EMBOSS(BuiltinFilter):
|
||||||
|
name = "Emboss"
|
||||||
|
# fmt: off
|
||||||
|
filterargs = (3, 3), 1, 128, (
|
||||||
|
-1, 0, 0,
|
||||||
|
0, 1, 0,
|
||||||
|
0, 0, 0,
|
||||||
|
)
|
||||||
|
# fmt: on
|
||||||
|
|
||||||
|
|
||||||
|
class FIND_EDGES(BuiltinFilter):
|
||||||
|
name = "Find Edges"
|
||||||
|
# fmt: off
|
||||||
|
filterargs = (3, 3), 1, 0, (
|
||||||
|
-1, -1, -1,
|
||||||
|
-1, 8, -1,
|
||||||
|
-1, -1, -1,
|
||||||
|
)
|
||||||
|
# fmt: on
|
||||||
|
|
||||||
|
|
||||||
|
class SHARPEN(BuiltinFilter):
|
||||||
|
name = "Sharpen"
|
||||||
|
# fmt: off
|
||||||
|
filterargs = (3, 3), 16, 0, (
|
||||||
|
-2, -2, -2,
|
||||||
|
-2, 32, -2,
|
||||||
|
-2, -2, -2,
|
||||||
|
)
|
||||||
|
# fmt: on
|
||||||
|
|
||||||
|
|
||||||
|
class SMOOTH(BuiltinFilter):
|
||||||
|
name = "Smooth"
|
||||||
|
# fmt: off
|
||||||
|
filterargs = (3, 3), 13, 0, (
|
||||||
|
1, 1, 1,
|
||||||
|
1, 5, 1,
|
||||||
|
1, 1, 1,
|
||||||
|
)
|
||||||
|
# fmt: on
|
||||||
|
|
||||||
|
|
||||||
|
class SMOOTH_MORE(BuiltinFilter):
|
||||||
|
name = "Smooth More"
|
||||||
|
# fmt: off
|
||||||
|
filterargs = (5, 5), 100, 0, (
|
||||||
|
1, 1, 1, 1, 1,
|
||||||
|
1, 5, 5, 5, 1,
|
||||||
|
1, 5, 44, 5, 1,
|
||||||
|
1, 5, 5, 5, 1,
|
||||||
|
1, 1, 1, 1, 1,
|
||||||
|
)
|
||||||
|
# fmt: on
|
||||||
|
|
||||||
|
|
||||||
|
class Color3DLUT(MultibandFilter):
|
||||||
|
"""Three-dimensional color lookup table.
|
||||||
|
|
||||||
|
Transforms 3-channel pixels using the values of the channels as coordinates
|
||||||
|
in the 3D lookup table and interpolating the nearest elements.
|
||||||
|
|
||||||
|
This method allows you to apply almost any color transformation
|
||||||
|
in constant time by using pre-calculated decimated tables.
|
||||||
|
|
||||||
|
.. versionadded:: 5.2.0
|
||||||
|
|
||||||
|
:param size: Size of the table. One int or tuple of (int, int, int).
|
||||||
|
Minimal size in any dimension is 2, maximum is 65.
|
||||||
|
:param table: Flat lookup table. A list of ``channels * size**3``
|
||||||
|
float elements or a list of ``size**3`` channels-sized
|
||||||
|
tuples with floats. Channels are changed first,
|
||||||
|
then first dimension, then second, then third.
|
||||||
|
Value 0.0 corresponds lowest value of output, 1.0 highest.
|
||||||
|
:param channels: Number of channels in the table. Could be 3 or 4.
|
||||||
|
Default is 3.
|
||||||
|
:param target_mode: A mode for the result image. Should have not less
|
||||||
|
than ``channels`` channels. Default is ``None``,
|
||||||
|
which means that mode wouldn't be changed.
|
||||||
|
"""
|
||||||
|
|
||||||
|
name = "Color 3D LUT"
|
||||||
|
|
||||||
|
def __init__(self, size, table, channels=3, target_mode=None, **kwargs):
|
||||||
|
if channels not in (3, 4):
|
||||||
|
raise ValueError("Only 3 or 4 output channels are supported")
|
||||||
|
self.size = size = self._check_size(size)
|
||||||
|
self.channels = channels
|
||||||
|
self.mode = target_mode
|
||||||
|
|
||||||
|
# Hidden flag `_copy_table=False` could be used to avoid extra copying
|
||||||
|
# of the table if the table is specially made for the constructor.
|
||||||
|
copy_table = kwargs.get("_copy_table", True)
|
||||||
|
items = size[0] * size[1] * size[2]
|
||||||
|
wrong_size = False
|
||||||
|
|
||||||
|
if numpy and isinstance(table, numpy.ndarray):
|
||||||
|
if copy_table:
|
||||||
|
table = table.copy()
|
||||||
|
|
||||||
|
if table.shape in [
|
||||||
|
(items * channels,),
|
||||||
|
(items, channels),
|
||||||
|
(size[2], size[1], size[0], channels),
|
||||||
|
]:
|
||||||
|
table = table.reshape(items * channels)
|
||||||
|
else:
|
||||||
|
wrong_size = True
|
||||||
|
|
||||||
|
else:
|
||||||
|
if copy_table:
|
||||||
|
table = list(table)
|
||||||
|
|
||||||
|
# Convert to a flat list
|
||||||
|
if table and isinstance(table[0], (list, tuple)):
|
||||||
|
table, raw_table = [], table
|
||||||
|
for pixel in raw_table:
|
||||||
|
if len(pixel) != channels:
|
||||||
|
raise ValueError(
|
||||||
|
"The elements of the table should "
|
||||||
|
"have a length of {}.".format(channels)
|
||||||
|
)
|
||||||
|
table.extend(pixel)
|
||||||
|
|
||||||
|
if wrong_size or len(table) != items * channels:
|
||||||
|
raise ValueError(
|
||||||
|
"The table should have either channels * size**3 float items "
|
||||||
|
"or size**3 items of channels-sized tuples with floats. "
|
||||||
|
f"Table should be: {channels}x{size[0]}x{size[1]}x{size[2]}. "
|
||||||
|
f"Actual length: {len(table)}"
|
||||||
|
)
|
||||||
|
self.table = table
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _check_size(size):
|
||||||
|
try:
|
||||||
|
_, _, _ = size
|
||||||
|
except ValueError as e:
|
||||||
|
raise ValueError(
|
||||||
|
"Size should be either an integer or a tuple of three integers."
|
||||||
|
) from e
|
||||||
|
except TypeError:
|
||||||
|
size = (size, size, size)
|
||||||
|
size = [int(x) for x in size]
|
||||||
|
for size1D in size:
|
||||||
|
if not 2 <= size1D <= 65:
|
||||||
|
raise ValueError("Size should be in [2, 65] range.")
|
||||||
|
return size
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def generate(cls, size, callback, channels=3, target_mode=None):
|
||||||
|
"""Generates new LUT using provided callback.
|
||||||
|
|
||||||
|
:param size: Size of the table. Passed to the constructor.
|
||||||
|
:param callback: Function with three parameters which correspond
|
||||||
|
three color channels. Will be called ``size**3``
|
||||||
|
times with values from 0.0 to 1.0 and should return
|
||||||
|
a tuple with ``channels`` elements.
|
||||||
|
:param channels: The number of channels which should return callback.
|
||||||
|
:param target_mode: Passed to the constructor of the resulting
|
||||||
|
lookup table.
|
||||||
|
"""
|
||||||
|
size1D, size2D, size3D = cls._check_size(size)
|
||||||
|
if channels not in (3, 4):
|
||||||
|
raise ValueError("Only 3 or 4 output channels are supported")
|
||||||
|
|
||||||
|
table = [0] * (size1D * size2D * size3D * channels)
|
||||||
|
idx_out = 0
|
||||||
|
for b in range(size3D):
|
||||||
|
for g in range(size2D):
|
||||||
|
for r in range(size1D):
|
||||||
|
table[idx_out : idx_out + channels] = callback(
|
||||||
|
r / (size1D - 1), g / (size2D - 1), b / (size3D - 1)
|
||||||
|
)
|
||||||
|
idx_out += channels
|
||||||
|
|
||||||
|
return cls(
|
||||||
|
(size1D, size2D, size3D),
|
||||||
|
table,
|
||||||
|
channels=channels,
|
||||||
|
target_mode=target_mode,
|
||||||
|
_copy_table=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
def transform(self, callback, with_normals=False, channels=None, target_mode=None):
|
||||||
|
"""Transforms the table values using provided callback and returns
|
||||||
|
a new LUT with altered values.
|
||||||
|
|
||||||
|
:param callback: A function which takes old lookup table values
|
||||||
|
and returns a new set of values. The number
|
||||||
|
of arguments which function should take is
|
||||||
|
``self.channels`` or ``3 + self.channels``
|
||||||
|
if ``with_normals`` flag is set.
|
||||||
|
Should return a tuple of ``self.channels`` or
|
||||||
|
``channels`` elements if it is set.
|
||||||
|
:param with_normals: If true, ``callback`` will be called with
|
||||||
|
coordinates in the color cube as the first
|
||||||
|
three arguments. Otherwise, ``callback``
|
||||||
|
will be called only with actual color values.
|
||||||
|
:param channels: The number of channels in the resulting lookup table.
|
||||||
|
:param target_mode: Passed to the constructor of the resulting
|
||||||
|
lookup table.
|
||||||
|
"""
|
||||||
|
if channels not in (None, 3, 4):
|
||||||
|
raise ValueError("Only 3 or 4 output channels are supported")
|
||||||
|
ch_in = self.channels
|
||||||
|
ch_out = channels or ch_in
|
||||||
|
size1D, size2D, size3D = self.size
|
||||||
|
|
||||||
|
table = [0] * (size1D * size2D * size3D * ch_out)
|
||||||
|
idx_in = 0
|
||||||
|
idx_out = 0
|
||||||
|
for b in range(size3D):
|
||||||
|
for g in range(size2D):
|
||||||
|
for r in range(size1D):
|
||||||
|
values = self.table[idx_in : idx_in + ch_in]
|
||||||
|
if with_normals:
|
||||||
|
values = callback(
|
||||||
|
r / (size1D - 1),
|
||||||
|
g / (size2D - 1),
|
||||||
|
b / (size3D - 1),
|
||||||
|
*values,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
values = callback(*values)
|
||||||
|
table[idx_out : idx_out + ch_out] = values
|
||||||
|
idx_in += ch_in
|
||||||
|
idx_out += ch_out
|
||||||
|
|
||||||
|
return type(self)(
|
||||||
|
self.size,
|
||||||
|
table,
|
||||||
|
channels=ch_out,
|
||||||
|
target_mode=target_mode or self.mode,
|
||||||
|
_copy_table=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
r = [
|
||||||
|
f"{self.__class__.__name__} from {self.table.__class__.__name__}",
|
||||||
|
"size={:d}x{:d}x{:d}".format(*self.size),
|
||||||
|
f"channels={self.channels:d}",
|
||||||
|
]
|
||||||
|
if self.mode:
|
||||||
|
r.append(f"target_mode={self.mode}")
|
||||||
|
return "<{}>".format(" ".join(r))
|
||||||
|
|
||||||
|
def filter(self, image):
|
||||||
|
from . import Image
|
||||||
|
|
||||||
|
return image.color_lut_3d(
|
||||||
|
self.mode or image.mode,
|
||||||
|
Image.LINEAR,
|
||||||
|
self.channels,
|
||||||
|
self.size[0],
|
||||||
|
self.size[1],
|
||||||
|
self.size[2],
|
||||||
|
self.table,
|
||||||
|
)
|
||||||
1041
venv/lib/python3.9/site-packages/PIL/ImageFont.py
Normal file
120
venv/lib/python3.9/site-packages/PIL/ImageGrab.py
Normal file
|
|
@ -0,0 +1,120 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# screen grabber
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 2001-04-26 fl created
|
||||||
|
# 2001-09-17 fl use builtin driver, if present
|
||||||
|
# 2002-11-19 fl added grabclipboard support
|
||||||
|
#
|
||||||
|
# Copyright (c) 2001-2002 by Secret Labs AB
|
||||||
|
# Copyright (c) 2001-2002 by Fredrik Lundh
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from . import Image
|
||||||
|
|
||||||
|
if sys.platform == "darwin":
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
|
||||||
|
def grab(bbox=None, include_layered_windows=False, all_screens=False, xdisplay=None):
|
||||||
|
if xdisplay is None:
|
||||||
|
if sys.platform == "darwin":
|
||||||
|
fh, filepath = tempfile.mkstemp(".png")
|
||||||
|
os.close(fh)
|
||||||
|
subprocess.call(["screencapture", "-x", filepath])
|
||||||
|
im = Image.open(filepath)
|
||||||
|
im.load()
|
||||||
|
os.unlink(filepath)
|
||||||
|
if bbox:
|
||||||
|
im_cropped = im.crop(bbox)
|
||||||
|
im.close()
|
||||||
|
return im_cropped
|
||||||
|
return im
|
||||||
|
elif sys.platform == "win32":
|
||||||
|
offset, size, data = Image.core.grabscreen_win32(
|
||||||
|
include_layered_windows, all_screens
|
||||||
|
)
|
||||||
|
im = Image.frombytes(
|
||||||
|
"RGB",
|
||||||
|
size,
|
||||||
|
data,
|
||||||
|
# RGB, 32-bit line padding, origin lower left corner
|
||||||
|
"raw",
|
||||||
|
"BGR",
|
||||||
|
(size[0] * 3 + 3) & -4,
|
||||||
|
-1,
|
||||||
|
)
|
||||||
|
if bbox:
|
||||||
|
x0, y0 = offset
|
||||||
|
left, top, right, bottom = bbox
|
||||||
|
im = im.crop((left - x0, top - y0, right - x0, bottom - y0))
|
||||||
|
return im
|
||||||
|
# use xdisplay=None for default display on non-win32/macOS systems
|
||||||
|
if not Image.core.HAVE_XCB:
|
||||||
|
raise OSError("Pillow was built without XCB support")
|
||||||
|
size, data = Image.core.grabscreen_x11(xdisplay)
|
||||||
|
im = Image.frombytes("RGB", size, data, "raw", "BGRX", size[0] * 4, 1)
|
||||||
|
if bbox:
|
||||||
|
im = im.crop(bbox)
|
||||||
|
return im
|
||||||
|
|
||||||
|
|
||||||
|
def grabclipboard():
|
||||||
|
if sys.platform == "darwin":
|
||||||
|
fh, filepath = tempfile.mkstemp(".jpg")
|
||||||
|
os.close(fh)
|
||||||
|
commands = [
|
||||||
|
'set theFile to (open for access POSIX file "'
|
||||||
|
+ filepath
|
||||||
|
+ '" with write permission)',
|
||||||
|
"try",
|
||||||
|
" write (the clipboard as JPEG picture) to theFile",
|
||||||
|
"end try",
|
||||||
|
"close access theFile",
|
||||||
|
]
|
||||||
|
script = ["osascript"]
|
||||||
|
for command in commands:
|
||||||
|
script += ["-e", command]
|
||||||
|
subprocess.call(script)
|
||||||
|
|
||||||
|
im = None
|
||||||
|
if os.stat(filepath).st_size != 0:
|
||||||
|
im = Image.open(filepath)
|
||||||
|
im.load()
|
||||||
|
os.unlink(filepath)
|
||||||
|
return im
|
||||||
|
elif sys.platform == "win32":
|
||||||
|
fmt, data = Image.core.grabclipboard_win32()
|
||||||
|
if fmt == "file": # CF_HDROP
|
||||||
|
import struct
|
||||||
|
|
||||||
|
o = struct.unpack_from("I", data)[0]
|
||||||
|
if data[16] != 0:
|
||||||
|
files = data[o:].decode("utf-16le").split("\0")
|
||||||
|
else:
|
||||||
|
files = data[o:].decode("mbcs").split("\0")
|
||||||
|
return files[: files.index("")]
|
||||||
|
if isinstance(data, bytes):
|
||||||
|
import io
|
||||||
|
|
||||||
|
data = io.BytesIO(data)
|
||||||
|
if fmt == "png":
|
||||||
|
from . import PngImagePlugin
|
||||||
|
|
||||||
|
return PngImagePlugin.PngImageFile(data)
|
||||||
|
elif fmt == "DIB":
|
||||||
|
from . import BmpImagePlugin
|
||||||
|
|
||||||
|
return BmpImagePlugin.DibImageFile(data)
|
||||||
|
return None
|
||||||
|
else:
|
||||||
|
raise NotImplementedError("ImageGrab.grabclipboard() is macOS and Windows only")
|
||||||
253
venv/lib/python3.9/site-packages/PIL/ImageMath.py
Normal file
|
|
@ -0,0 +1,253 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# a simple math add-on for the Python Imaging Library
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 1999-02-15 fl Original PIL Plus release
|
||||||
|
# 2005-05-05 fl Simplified and cleaned up for PIL 1.1.6
|
||||||
|
# 2005-09-12 fl Fixed int() and float() for Python 2.4.1
|
||||||
|
#
|
||||||
|
# Copyright (c) 1999-2005 by Secret Labs AB
|
||||||
|
# Copyright (c) 2005 by Fredrik Lundh
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
import builtins
|
||||||
|
|
||||||
|
from . import Image, _imagingmath
|
||||||
|
|
||||||
|
VERBOSE = 0
|
||||||
|
|
||||||
|
|
||||||
|
def _isconstant(v):
|
||||||
|
return isinstance(v, (int, float))
|
||||||
|
|
||||||
|
|
||||||
|
class _Operand:
|
||||||
|
"""Wraps an image operand, providing standard operators"""
|
||||||
|
|
||||||
|
def __init__(self, im):
|
||||||
|
self.im = im
|
||||||
|
|
||||||
|
def __fixup(self, im1):
|
||||||
|
# convert image to suitable mode
|
||||||
|
if isinstance(im1, _Operand):
|
||||||
|
# argument was an image.
|
||||||
|
if im1.im.mode in ("1", "L"):
|
||||||
|
return im1.im.convert("I")
|
||||||
|
elif im1.im.mode in ("I", "F"):
|
||||||
|
return im1.im
|
||||||
|
else:
|
||||||
|
raise ValueError(f"unsupported mode: {im1.im.mode}")
|
||||||
|
else:
|
||||||
|
# argument was a constant
|
||||||
|
if _isconstant(im1) and self.im.mode in ("1", "L", "I"):
|
||||||
|
return Image.new("I", self.im.size, im1)
|
||||||
|
else:
|
||||||
|
return Image.new("F", self.im.size, im1)
|
||||||
|
|
||||||
|
def apply(self, op, im1, im2=None, mode=None):
|
||||||
|
im1 = self.__fixup(im1)
|
||||||
|
if im2 is None:
|
||||||
|
# unary operation
|
||||||
|
out = Image.new(mode or im1.mode, im1.size, None)
|
||||||
|
im1.load()
|
||||||
|
try:
|
||||||
|
op = getattr(_imagingmath, op + "_" + im1.mode)
|
||||||
|
except AttributeError as e:
|
||||||
|
raise TypeError(f"bad operand type for '{op}'") from e
|
||||||
|
_imagingmath.unop(op, out.im.id, im1.im.id)
|
||||||
|
else:
|
||||||
|
# binary operation
|
||||||
|
im2 = self.__fixup(im2)
|
||||||
|
if im1.mode != im2.mode:
|
||||||
|
# convert both arguments to floating point
|
||||||
|
if im1.mode != "F":
|
||||||
|
im1 = im1.convert("F")
|
||||||
|
if im2.mode != "F":
|
||||||
|
im2 = im2.convert("F")
|
||||||
|
if im1.mode != im2.mode:
|
||||||
|
raise ValueError("mode mismatch")
|
||||||
|
if im1.size != im2.size:
|
||||||
|
# crop both arguments to a common size
|
||||||
|
size = (min(im1.size[0], im2.size[0]), min(im1.size[1], im2.size[1]))
|
||||||
|
if im1.size != size:
|
||||||
|
im1 = im1.crop((0, 0) + size)
|
||||||
|
if im2.size != size:
|
||||||
|
im2 = im2.crop((0, 0) + size)
|
||||||
|
out = Image.new(mode or im1.mode, size, None)
|
||||||
|
else:
|
||||||
|
out = Image.new(mode or im1.mode, im1.size, None)
|
||||||
|
im1.load()
|
||||||
|
im2.load()
|
||||||
|
try:
|
||||||
|
op = getattr(_imagingmath, op + "_" + im1.mode)
|
||||||
|
except AttributeError as e:
|
||||||
|
raise TypeError(f"bad operand type for '{op}'") from e
|
||||||
|
_imagingmath.binop(op, out.im.id, im1.im.id, im2.im.id)
|
||||||
|
return _Operand(out)
|
||||||
|
|
||||||
|
# unary operators
|
||||||
|
def __bool__(self):
|
||||||
|
# an image is "true" if it contains at least one non-zero pixel
|
||||||
|
return self.im.getbbox() is not None
|
||||||
|
|
||||||
|
def __abs__(self):
|
||||||
|
return self.apply("abs", self)
|
||||||
|
|
||||||
|
def __pos__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __neg__(self):
|
||||||
|
return self.apply("neg", self)
|
||||||
|
|
||||||
|
# binary operators
|
||||||
|
def __add__(self, other):
|
||||||
|
return self.apply("add", self, other)
|
||||||
|
|
||||||
|
def __radd__(self, other):
|
||||||
|
return self.apply("add", other, self)
|
||||||
|
|
||||||
|
def __sub__(self, other):
|
||||||
|
return self.apply("sub", self, other)
|
||||||
|
|
||||||
|
def __rsub__(self, other):
|
||||||
|
return self.apply("sub", other, self)
|
||||||
|
|
||||||
|
def __mul__(self, other):
|
||||||
|
return self.apply("mul", self, other)
|
||||||
|
|
||||||
|
def __rmul__(self, other):
|
||||||
|
return self.apply("mul", other, self)
|
||||||
|
|
||||||
|
def __truediv__(self, other):
|
||||||
|
return self.apply("div", self, other)
|
||||||
|
|
||||||
|
def __rtruediv__(self, other):
|
||||||
|
return self.apply("div", other, self)
|
||||||
|
|
||||||
|
def __mod__(self, other):
|
||||||
|
return self.apply("mod", self, other)
|
||||||
|
|
||||||
|
def __rmod__(self, other):
|
||||||
|
return self.apply("mod", other, self)
|
||||||
|
|
||||||
|
def __pow__(self, other):
|
||||||
|
return self.apply("pow", self, other)
|
||||||
|
|
||||||
|
def __rpow__(self, other):
|
||||||
|
return self.apply("pow", other, self)
|
||||||
|
|
||||||
|
# bitwise
|
||||||
|
def __invert__(self):
|
||||||
|
return self.apply("invert", self)
|
||||||
|
|
||||||
|
def __and__(self, other):
|
||||||
|
return self.apply("and", self, other)
|
||||||
|
|
||||||
|
def __rand__(self, other):
|
||||||
|
return self.apply("and", other, self)
|
||||||
|
|
||||||
|
def __or__(self, other):
|
||||||
|
return self.apply("or", self, other)
|
||||||
|
|
||||||
|
def __ror__(self, other):
|
||||||
|
return self.apply("or", other, self)
|
||||||
|
|
||||||
|
def __xor__(self, other):
|
||||||
|
return self.apply("xor", self, other)
|
||||||
|
|
||||||
|
def __rxor__(self, other):
|
||||||
|
return self.apply("xor", other, self)
|
||||||
|
|
||||||
|
def __lshift__(self, other):
|
||||||
|
return self.apply("lshift", self, other)
|
||||||
|
|
||||||
|
def __rshift__(self, other):
|
||||||
|
return self.apply("rshift", self, other)
|
||||||
|
|
||||||
|
# logical
|
||||||
|
def __eq__(self, other):
|
||||||
|
return self.apply("eq", self, other)
|
||||||
|
|
||||||
|
def __ne__(self, other):
|
||||||
|
return self.apply("ne", self, other)
|
||||||
|
|
||||||
|
def __lt__(self, other):
|
||||||
|
return self.apply("lt", self, other)
|
||||||
|
|
||||||
|
def __le__(self, other):
|
||||||
|
return self.apply("le", self, other)
|
||||||
|
|
||||||
|
def __gt__(self, other):
|
||||||
|
return self.apply("gt", self, other)
|
||||||
|
|
||||||
|
def __ge__(self, other):
|
||||||
|
return self.apply("ge", self, other)
|
||||||
|
|
||||||
|
|
||||||
|
# conversions
|
||||||
|
def imagemath_int(self):
|
||||||
|
return _Operand(self.im.convert("I"))
|
||||||
|
|
||||||
|
|
||||||
|
def imagemath_float(self):
|
||||||
|
return _Operand(self.im.convert("F"))
|
||||||
|
|
||||||
|
|
||||||
|
# logical
|
||||||
|
def imagemath_equal(self, other):
|
||||||
|
return self.apply("eq", self, other, mode="I")
|
||||||
|
|
||||||
|
|
||||||
|
def imagemath_notequal(self, other):
|
||||||
|
return self.apply("ne", self, other, mode="I")
|
||||||
|
|
||||||
|
|
||||||
|
def imagemath_min(self, other):
|
||||||
|
return self.apply("min", self, other)
|
||||||
|
|
||||||
|
|
||||||
|
def imagemath_max(self, other):
|
||||||
|
return self.apply("max", self, other)
|
||||||
|
|
||||||
|
|
||||||
|
def imagemath_convert(self, mode):
|
||||||
|
return _Operand(self.im.convert(mode))
|
||||||
|
|
||||||
|
|
||||||
|
ops = {}
|
||||||
|
for k, v in list(globals().items()):
|
||||||
|
if k[:10] == "imagemath_":
|
||||||
|
ops[k[10:]] = v
|
||||||
|
|
||||||
|
|
||||||
|
def eval(expression, _dict={}, **kw):
|
||||||
|
"""
|
||||||
|
Evaluates an image expression.
|
||||||
|
|
||||||
|
:param expression: A string containing a Python-style expression.
|
||||||
|
:param options: Values to add to the evaluation context. You
|
||||||
|
can either use a dictionary, or one or more keyword
|
||||||
|
arguments.
|
||||||
|
:return: The evaluated expression. This is usually an image object, but can
|
||||||
|
also be an integer, a floating point value, or a pixel tuple,
|
||||||
|
depending on the expression.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# build execution namespace
|
||||||
|
args = ops.copy()
|
||||||
|
args.update(_dict)
|
||||||
|
args.update(kw)
|
||||||
|
for k, v in list(args.items()):
|
||||||
|
if hasattr(v, "im"):
|
||||||
|
args[k] = _Operand(v)
|
||||||
|
|
||||||
|
out = builtins.eval(expression, args)
|
||||||
|
try:
|
||||||
|
return out.im
|
||||||
|
except AttributeError:
|
||||||
|
return out
|
||||||
64
venv/lib/python3.9/site-packages/PIL/ImageMode.py
Normal file
|
|
@ -0,0 +1,64 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library.
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# standard mode descriptors
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 2006-03-20 fl Added
|
||||||
|
#
|
||||||
|
# Copyright (c) 2006 by Secret Labs AB.
|
||||||
|
# Copyright (c) 2006 by Fredrik Lundh.
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
# mode descriptor cache
|
||||||
|
_modes = None
|
||||||
|
|
||||||
|
|
||||||
|
class ModeDescriptor:
|
||||||
|
"""Wrapper for mode strings."""
|
||||||
|
|
||||||
|
def __init__(self, mode, bands, basemode, basetype):
|
||||||
|
self.mode = mode
|
||||||
|
self.bands = bands
|
||||||
|
self.basemode = basemode
|
||||||
|
self.basetype = basetype
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return self.mode
|
||||||
|
|
||||||
|
|
||||||
|
def getmode(mode):
|
||||||
|
"""Gets a mode descriptor for the given mode."""
|
||||||
|
global _modes
|
||||||
|
if not _modes:
|
||||||
|
# initialize mode cache
|
||||||
|
|
||||||
|
from . import Image
|
||||||
|
|
||||||
|
modes = {}
|
||||||
|
# core modes
|
||||||
|
for m, (basemode, basetype, bands) in Image._MODEINFO.items():
|
||||||
|
modes[m] = ModeDescriptor(m, bands, basemode, basetype)
|
||||||
|
# extra experimental modes
|
||||||
|
modes["RGBa"] = ModeDescriptor("RGBa", ("R", "G", "B", "a"), "RGB", "L")
|
||||||
|
modes["LA"] = ModeDescriptor("LA", ("L", "A"), "L", "L")
|
||||||
|
modes["La"] = ModeDescriptor("La", ("L", "a"), "L", "L")
|
||||||
|
modes["PA"] = ModeDescriptor("PA", ("P", "A"), "RGB", "L")
|
||||||
|
# mapping modes
|
||||||
|
for i16mode in (
|
||||||
|
"I;16",
|
||||||
|
"I;16S",
|
||||||
|
"I;16L",
|
||||||
|
"I;16LS",
|
||||||
|
"I;16B",
|
||||||
|
"I;16BS",
|
||||||
|
"I;16N",
|
||||||
|
"I;16NS",
|
||||||
|
):
|
||||||
|
modes[i16mode] = ModeDescriptor(i16mode, ("I",), "L", "L")
|
||||||
|
# set global mode cache atomically
|
||||||
|
_modes = modes
|
||||||
|
return _modes[mode]
|
||||||
245
venv/lib/python3.9/site-packages/PIL/ImageMorph.py
Normal file
|
|
@ -0,0 +1,245 @@
|
||||||
|
# A binary morphology add-on for the Python Imaging Library
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 2014-06-04 Initial version.
|
||||||
|
#
|
||||||
|
# Copyright (c) 2014 Dov Grobgeld <dov.grobgeld@gmail.com>
|
||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
|
from . import Image, _imagingmorph
|
||||||
|
|
||||||
|
LUT_SIZE = 1 << 9
|
||||||
|
|
||||||
|
# fmt: off
|
||||||
|
ROTATION_MATRIX = [
|
||||||
|
6, 3, 0,
|
||||||
|
7, 4, 1,
|
||||||
|
8, 5, 2,
|
||||||
|
]
|
||||||
|
MIRROR_MATRIX = [
|
||||||
|
2, 1, 0,
|
||||||
|
5, 4, 3,
|
||||||
|
8, 7, 6,
|
||||||
|
]
|
||||||
|
# fmt: on
|
||||||
|
|
||||||
|
|
||||||
|
class LutBuilder:
|
||||||
|
"""A class for building a MorphLut from a descriptive language
|
||||||
|
|
||||||
|
The input patterns is a list of a strings sequences like these::
|
||||||
|
|
||||||
|
4:(...
|
||||||
|
.1.
|
||||||
|
111)->1
|
||||||
|
|
||||||
|
(whitespaces including linebreaks are ignored). The option 4
|
||||||
|
describes a series of symmetry operations (in this case a
|
||||||
|
4-rotation), the pattern is described by:
|
||||||
|
|
||||||
|
- . or X - Ignore
|
||||||
|
- 1 - Pixel is on
|
||||||
|
- 0 - Pixel is off
|
||||||
|
|
||||||
|
The result of the operation is described after "->" string.
|
||||||
|
|
||||||
|
The default is to return the current pixel value, which is
|
||||||
|
returned if no other match is found.
|
||||||
|
|
||||||
|
Operations:
|
||||||
|
|
||||||
|
- 4 - 4 way rotation
|
||||||
|
- N - Negate
|
||||||
|
- 1 - Dummy op for no other operation (an op must always be given)
|
||||||
|
- M - Mirroring
|
||||||
|
|
||||||
|
Example::
|
||||||
|
|
||||||
|
lb = LutBuilder(patterns = ["4:(... .1. 111)->1"])
|
||||||
|
lut = lb.build_lut()
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, patterns=None, op_name=None):
|
||||||
|
if patterns is not None:
|
||||||
|
self.patterns = patterns
|
||||||
|
else:
|
||||||
|
self.patterns = []
|
||||||
|
self.lut = None
|
||||||
|
if op_name is not None:
|
||||||
|
known_patterns = {
|
||||||
|
"corner": ["1:(... ... ...)->0", "4:(00. 01. ...)->1"],
|
||||||
|
"dilation4": ["4:(... .0. .1.)->1"],
|
||||||
|
"dilation8": ["4:(... .0. .1.)->1", "4:(... .0. ..1)->1"],
|
||||||
|
"erosion4": ["4:(... .1. .0.)->0"],
|
||||||
|
"erosion8": ["4:(... .1. .0.)->0", "4:(... .1. ..0)->0"],
|
||||||
|
"edge": [
|
||||||
|
"1:(... ... ...)->0",
|
||||||
|
"4:(.0. .1. ...)->1",
|
||||||
|
"4:(01. .1. ...)->1",
|
||||||
|
],
|
||||||
|
}
|
||||||
|
if op_name not in known_patterns:
|
||||||
|
raise Exception("Unknown pattern " + op_name + "!")
|
||||||
|
|
||||||
|
self.patterns = known_patterns[op_name]
|
||||||
|
|
||||||
|
def add_patterns(self, patterns):
|
||||||
|
self.patterns += patterns
|
||||||
|
|
||||||
|
def build_default_lut(self):
|
||||||
|
symbols = [0, 1]
|
||||||
|
m = 1 << 4 # pos of current pixel
|
||||||
|
self.lut = bytearray(symbols[(i & m) > 0] for i in range(LUT_SIZE))
|
||||||
|
|
||||||
|
def get_lut(self):
|
||||||
|
return self.lut
|
||||||
|
|
||||||
|
def _string_permute(self, pattern, permutation):
|
||||||
|
"""string_permute takes a pattern and a permutation and returns the
|
||||||
|
string permuted according to the permutation list.
|
||||||
|
"""
|
||||||
|
assert len(permutation) == 9
|
||||||
|
return "".join(pattern[p] for p in permutation)
|
||||||
|
|
||||||
|
def _pattern_permute(self, basic_pattern, options, basic_result):
|
||||||
|
"""pattern_permute takes a basic pattern and its result and clones
|
||||||
|
the pattern according to the modifications described in the $options
|
||||||
|
parameter. It returns a list of all cloned patterns."""
|
||||||
|
patterns = [(basic_pattern, basic_result)]
|
||||||
|
|
||||||
|
# rotations
|
||||||
|
if "4" in options:
|
||||||
|
res = patterns[-1][1]
|
||||||
|
for i in range(4):
|
||||||
|
patterns.append(
|
||||||
|
(self._string_permute(patterns[-1][0], ROTATION_MATRIX), res)
|
||||||
|
)
|
||||||
|
# mirror
|
||||||
|
if "M" in options:
|
||||||
|
n = len(patterns)
|
||||||
|
for pattern, res in patterns[0:n]:
|
||||||
|
patterns.append((self._string_permute(pattern, MIRROR_MATRIX), res))
|
||||||
|
|
||||||
|
# negate
|
||||||
|
if "N" in options:
|
||||||
|
n = len(patterns)
|
||||||
|
for pattern, res in patterns[0:n]:
|
||||||
|
# Swap 0 and 1
|
||||||
|
pattern = pattern.replace("0", "Z").replace("1", "0").replace("Z", "1")
|
||||||
|
res = 1 - int(res)
|
||||||
|
patterns.append((pattern, res))
|
||||||
|
|
||||||
|
return patterns
|
||||||
|
|
||||||
|
def build_lut(self):
|
||||||
|
"""Compile all patterns into a morphology lut.
|
||||||
|
|
||||||
|
TBD :Build based on (file) morphlut:modify_lut
|
||||||
|
"""
|
||||||
|
self.build_default_lut()
|
||||||
|
patterns = []
|
||||||
|
|
||||||
|
# Parse and create symmetries of the patterns strings
|
||||||
|
for p in self.patterns:
|
||||||
|
m = re.search(r"(\w*):?\s*\((.+?)\)\s*->\s*(\d)", p.replace("\n", ""))
|
||||||
|
if not m:
|
||||||
|
raise Exception('Syntax error in pattern "' + p + '"')
|
||||||
|
options = m.group(1)
|
||||||
|
pattern = m.group(2)
|
||||||
|
result = int(m.group(3))
|
||||||
|
|
||||||
|
# Get rid of spaces
|
||||||
|
pattern = pattern.replace(" ", "").replace("\n", "")
|
||||||
|
|
||||||
|
patterns += self._pattern_permute(pattern, options, result)
|
||||||
|
|
||||||
|
# compile the patterns into regular expressions for speed
|
||||||
|
for i, pattern in enumerate(patterns):
|
||||||
|
p = pattern[0].replace(".", "X").replace("X", "[01]")
|
||||||
|
p = re.compile(p)
|
||||||
|
patterns[i] = (p, pattern[1])
|
||||||
|
|
||||||
|
# Step through table and find patterns that match.
|
||||||
|
# Note that all the patterns are searched. The last one
|
||||||
|
# caught overrides
|
||||||
|
for i in range(LUT_SIZE):
|
||||||
|
# Build the bit pattern
|
||||||
|
bitpattern = bin(i)[2:]
|
||||||
|
bitpattern = ("0" * (9 - len(bitpattern)) + bitpattern)[::-1]
|
||||||
|
|
||||||
|
for p, r in patterns:
|
||||||
|
if p.match(bitpattern):
|
||||||
|
self.lut[i] = [0, 1][r]
|
||||||
|
|
||||||
|
return self.lut
|
||||||
|
|
||||||
|
|
||||||
|
class MorphOp:
|
||||||
|
"""A class for binary morphological operators"""
|
||||||
|
|
||||||
|
def __init__(self, lut=None, op_name=None, patterns=None):
|
||||||
|
"""Create a binary morphological operator"""
|
||||||
|
self.lut = lut
|
||||||
|
if op_name is not None:
|
||||||
|
self.lut = LutBuilder(op_name=op_name).build_lut()
|
||||||
|
elif patterns is not None:
|
||||||
|
self.lut = LutBuilder(patterns=patterns).build_lut()
|
||||||
|
|
||||||
|
def apply(self, image):
|
||||||
|
"""Run a single morphological operation on an image
|
||||||
|
|
||||||
|
Returns a tuple of the number of changed pixels and the
|
||||||
|
morphed image"""
|
||||||
|
if self.lut is None:
|
||||||
|
raise Exception("No operator loaded")
|
||||||
|
|
||||||
|
if image.mode != "L":
|
||||||
|
raise Exception("Image must be binary, meaning it must use mode L")
|
||||||
|
outimage = Image.new(image.mode, image.size, None)
|
||||||
|
count = _imagingmorph.apply(bytes(self.lut), image.im.id, outimage.im.id)
|
||||||
|
return count, outimage
|
||||||
|
|
||||||
|
def match(self, image):
|
||||||
|
"""Get a list of coordinates matching the morphological operation on
|
||||||
|
an image.
|
||||||
|
|
||||||
|
Returns a list of tuples of (x,y) coordinates
|
||||||
|
of all matching pixels. See :ref:`coordinate-system`."""
|
||||||
|
if self.lut is None:
|
||||||
|
raise Exception("No operator loaded")
|
||||||
|
|
||||||
|
if image.mode != "L":
|
||||||
|
raise Exception("Image must be binary, meaning it must use mode L")
|
||||||
|
return _imagingmorph.match(bytes(self.lut), image.im.id)
|
||||||
|
|
||||||
|
def get_on_pixels(self, image):
|
||||||
|
"""Get a list of all turned on pixels in a binary image
|
||||||
|
|
||||||
|
Returns a list of tuples of (x,y) coordinates
|
||||||
|
of all matching pixels. See :ref:`coordinate-system`."""
|
||||||
|
|
||||||
|
if image.mode != "L":
|
||||||
|
raise Exception("Image must be binary, meaning it must use mode L")
|
||||||
|
return _imagingmorph.get_on_pixels(image.im.id)
|
||||||
|
|
||||||
|
def load_lut(self, filename):
|
||||||
|
"""Load an operator from an mrl file"""
|
||||||
|
with open(filename, "rb") as f:
|
||||||
|
self.lut = bytearray(f.read())
|
||||||
|
|
||||||
|
if len(self.lut) != LUT_SIZE:
|
||||||
|
self.lut = None
|
||||||
|
raise Exception("Wrong size operator file!")
|
||||||
|
|
||||||
|
def save_lut(self, filename):
|
||||||
|
"""Save an operator to an mrl file"""
|
||||||
|
if self.lut is None:
|
||||||
|
raise Exception("No operator loaded")
|
||||||
|
with open(filename, "wb") as f:
|
||||||
|
f.write(self.lut)
|
||||||
|
|
||||||
|
def set_lut(self, lut):
|
||||||
|
"""Set the lut from an external source"""
|
||||||
|
self.lut = lut
|
||||||
558
venv/lib/python3.9/site-packages/PIL/ImageOps.py
Normal file
|
|
@ -0,0 +1,558 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library.
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# standard image operations
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 2001-10-20 fl Created
|
||||||
|
# 2001-10-23 fl Added autocontrast operator
|
||||||
|
# 2001-12-18 fl Added Kevin's fit operator
|
||||||
|
# 2004-03-14 fl Fixed potential division by zero in equalize
|
||||||
|
# 2005-05-05 fl Fixed equalize for low number of values
|
||||||
|
#
|
||||||
|
# Copyright (c) 2001-2004 by Secret Labs AB
|
||||||
|
# Copyright (c) 2001-2004 by Fredrik Lundh
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
import functools
|
||||||
|
import operator
|
||||||
|
|
||||||
|
from . import Image
|
||||||
|
|
||||||
|
#
|
||||||
|
# helpers
|
||||||
|
|
||||||
|
|
||||||
|
def _border(border):
|
||||||
|
if isinstance(border, tuple):
|
||||||
|
if len(border) == 2:
|
||||||
|
left, top = right, bottom = border
|
||||||
|
elif len(border) == 4:
|
||||||
|
left, top, right, bottom = border
|
||||||
|
else:
|
||||||
|
left = top = right = bottom = border
|
||||||
|
return left, top, right, bottom
|
||||||
|
|
||||||
|
|
||||||
|
def _color(color, mode):
|
||||||
|
if isinstance(color, str):
|
||||||
|
from . import ImageColor
|
||||||
|
|
||||||
|
color = ImageColor.getcolor(color, mode)
|
||||||
|
return color
|
||||||
|
|
||||||
|
|
||||||
|
def _lut(image, lut):
|
||||||
|
if image.mode == "P":
|
||||||
|
# FIXME: apply to lookup table, not image data
|
||||||
|
raise NotImplementedError("mode P support coming soon")
|
||||||
|
elif image.mode in ("L", "RGB"):
|
||||||
|
if image.mode == "RGB" and len(lut) == 256:
|
||||||
|
lut = lut + lut + lut
|
||||||
|
return image.point(lut)
|
||||||
|
else:
|
||||||
|
raise OSError("not supported for this image mode")
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# actions
|
||||||
|
|
||||||
|
|
||||||
|
def autocontrast(image, cutoff=0, ignore=None, mask=None):
|
||||||
|
"""
|
||||||
|
Maximize (normalize) image contrast. This function calculates a
|
||||||
|
histogram of the input image (or mask region), removes ``cutoff`` percent of the
|
||||||
|
lightest and darkest pixels from the histogram, and remaps the image
|
||||||
|
so that the darkest pixel becomes black (0), and the lightest
|
||||||
|
becomes white (255).
|
||||||
|
|
||||||
|
:param image: The image to process.
|
||||||
|
:param cutoff: The percent to cut off from the histogram on the low and
|
||||||
|
high ends. Either a tuple of (low, high), or a single
|
||||||
|
number for both.
|
||||||
|
:param ignore: The background pixel value (use None for no background).
|
||||||
|
:param mask: Histogram used in contrast operation is computed using pixels
|
||||||
|
within the mask. If no mask is given the entire image is used
|
||||||
|
for histogram computation.
|
||||||
|
:return: An image.
|
||||||
|
"""
|
||||||
|
histogram = image.histogram(mask)
|
||||||
|
lut = []
|
||||||
|
for layer in range(0, len(histogram), 256):
|
||||||
|
h = histogram[layer : layer + 256]
|
||||||
|
if ignore is not None:
|
||||||
|
# get rid of outliers
|
||||||
|
try:
|
||||||
|
h[ignore] = 0
|
||||||
|
except TypeError:
|
||||||
|
# assume sequence
|
||||||
|
for ix in ignore:
|
||||||
|
h[ix] = 0
|
||||||
|
if cutoff:
|
||||||
|
# cut off pixels from both ends of the histogram
|
||||||
|
if not isinstance(cutoff, tuple):
|
||||||
|
cutoff = (cutoff, cutoff)
|
||||||
|
# get number of pixels
|
||||||
|
n = 0
|
||||||
|
for ix in range(256):
|
||||||
|
n = n + h[ix]
|
||||||
|
# remove cutoff% pixels from the low end
|
||||||
|
cut = n * cutoff[0] // 100
|
||||||
|
for lo in range(256):
|
||||||
|
if cut > h[lo]:
|
||||||
|
cut = cut - h[lo]
|
||||||
|
h[lo] = 0
|
||||||
|
else:
|
||||||
|
h[lo] -= cut
|
||||||
|
cut = 0
|
||||||
|
if cut <= 0:
|
||||||
|
break
|
||||||
|
# remove cutoff% samples from the high end
|
||||||
|
cut = n * cutoff[1] // 100
|
||||||
|
for hi in range(255, -1, -1):
|
||||||
|
if cut > h[hi]:
|
||||||
|
cut = cut - h[hi]
|
||||||
|
h[hi] = 0
|
||||||
|
else:
|
||||||
|
h[hi] -= cut
|
||||||
|
cut = 0
|
||||||
|
if cut <= 0:
|
||||||
|
break
|
||||||
|
# find lowest/highest samples after preprocessing
|
||||||
|
for lo in range(256):
|
||||||
|
if h[lo]:
|
||||||
|
break
|
||||||
|
for hi in range(255, -1, -1):
|
||||||
|
if h[hi]:
|
||||||
|
break
|
||||||
|
if hi <= lo:
|
||||||
|
# don't bother
|
||||||
|
lut.extend(list(range(256)))
|
||||||
|
else:
|
||||||
|
scale = 255.0 / (hi - lo)
|
||||||
|
offset = -lo * scale
|
||||||
|
for ix in range(256):
|
||||||
|
ix = int(ix * scale + offset)
|
||||||
|
if ix < 0:
|
||||||
|
ix = 0
|
||||||
|
elif ix > 255:
|
||||||
|
ix = 255
|
||||||
|
lut.append(ix)
|
||||||
|
return _lut(image, lut)
|
||||||
|
|
||||||
|
|
||||||
|
def colorize(image, black, white, mid=None, blackpoint=0, whitepoint=255, midpoint=127):
|
||||||
|
"""
|
||||||
|
Colorize grayscale image.
|
||||||
|
This function calculates a color wedge which maps all black pixels in
|
||||||
|
the source image to the first color and all white pixels to the
|
||||||
|
second color. If ``mid`` is specified, it uses three-color mapping.
|
||||||
|
The ``black`` and ``white`` arguments should be RGB tuples or color names;
|
||||||
|
optionally you can use three-color mapping by also specifying ``mid``.
|
||||||
|
Mapping positions for any of the colors can be specified
|
||||||
|
(e.g. ``blackpoint``), where these parameters are the integer
|
||||||
|
value corresponding to where the corresponding color should be mapped.
|
||||||
|
These parameters must have logical order, such that
|
||||||
|
``blackpoint <= midpoint <= whitepoint`` (if ``mid`` is specified).
|
||||||
|
|
||||||
|
:param image: The image to colorize.
|
||||||
|
:param black: The color to use for black input pixels.
|
||||||
|
:param white: The color to use for white input pixels.
|
||||||
|
:param mid: The color to use for midtone input pixels.
|
||||||
|
:param blackpoint: an int value [0, 255] for the black mapping.
|
||||||
|
:param whitepoint: an int value [0, 255] for the white mapping.
|
||||||
|
:param midpoint: an int value [0, 255] for the midtone mapping.
|
||||||
|
:return: An image.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Initial asserts
|
||||||
|
assert image.mode == "L"
|
||||||
|
if mid is None:
|
||||||
|
assert 0 <= blackpoint <= whitepoint <= 255
|
||||||
|
else:
|
||||||
|
assert 0 <= blackpoint <= midpoint <= whitepoint <= 255
|
||||||
|
|
||||||
|
# Define colors from arguments
|
||||||
|
black = _color(black, "RGB")
|
||||||
|
white = _color(white, "RGB")
|
||||||
|
if mid is not None:
|
||||||
|
mid = _color(mid, "RGB")
|
||||||
|
|
||||||
|
# Empty lists for the mapping
|
||||||
|
red = []
|
||||||
|
green = []
|
||||||
|
blue = []
|
||||||
|
|
||||||
|
# Create the low-end values
|
||||||
|
for i in range(0, blackpoint):
|
||||||
|
red.append(black[0])
|
||||||
|
green.append(black[1])
|
||||||
|
blue.append(black[2])
|
||||||
|
|
||||||
|
# Create the mapping (2-color)
|
||||||
|
if mid is None:
|
||||||
|
|
||||||
|
range_map = range(0, whitepoint - blackpoint)
|
||||||
|
|
||||||
|
for i in range_map:
|
||||||
|
red.append(black[0] + i * (white[0] - black[0]) // len(range_map))
|
||||||
|
green.append(black[1] + i * (white[1] - black[1]) // len(range_map))
|
||||||
|
blue.append(black[2] + i * (white[2] - black[2]) // len(range_map))
|
||||||
|
|
||||||
|
# Create the mapping (3-color)
|
||||||
|
else:
|
||||||
|
|
||||||
|
range_map1 = range(0, midpoint - blackpoint)
|
||||||
|
range_map2 = range(0, whitepoint - midpoint)
|
||||||
|
|
||||||
|
for i in range_map1:
|
||||||
|
red.append(black[0] + i * (mid[0] - black[0]) // len(range_map1))
|
||||||
|
green.append(black[1] + i * (mid[1] - black[1]) // len(range_map1))
|
||||||
|
blue.append(black[2] + i * (mid[2] - black[2]) // len(range_map1))
|
||||||
|
for i in range_map2:
|
||||||
|
red.append(mid[0] + i * (white[0] - mid[0]) // len(range_map2))
|
||||||
|
green.append(mid[1] + i * (white[1] - mid[1]) // len(range_map2))
|
||||||
|
blue.append(mid[2] + i * (white[2] - mid[2]) // len(range_map2))
|
||||||
|
|
||||||
|
# Create the high-end values
|
||||||
|
for i in range(0, 256 - whitepoint):
|
||||||
|
red.append(white[0])
|
||||||
|
green.append(white[1])
|
||||||
|
blue.append(white[2])
|
||||||
|
|
||||||
|
# Return converted image
|
||||||
|
image = image.convert("RGB")
|
||||||
|
return _lut(image, red + green + blue)
|
||||||
|
|
||||||
|
|
||||||
|
def pad(image, size, method=Image.BICUBIC, color=None, centering=(0.5, 0.5)):
|
||||||
|
"""
|
||||||
|
Returns a sized and padded version of the image, expanded to fill the
|
||||||
|
requested aspect ratio and size.
|
||||||
|
|
||||||
|
:param image: The image to size and crop.
|
||||||
|
:param size: The requested output size in pixels, given as a
|
||||||
|
(width, height) tuple.
|
||||||
|
:param method: What resampling method to use. Default is
|
||||||
|
:py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.
|
||||||
|
:param color: The background color of the padded image.
|
||||||
|
:param centering: Control the position of the original image within the
|
||||||
|
padded version.
|
||||||
|
|
||||||
|
(0.5, 0.5) will keep the image centered
|
||||||
|
(0, 0) will keep the image aligned to the top left
|
||||||
|
(1, 1) will keep the image aligned to the bottom
|
||||||
|
right
|
||||||
|
:return: An image.
|
||||||
|
"""
|
||||||
|
|
||||||
|
im_ratio = image.width / image.height
|
||||||
|
dest_ratio = size[0] / size[1]
|
||||||
|
|
||||||
|
if im_ratio == dest_ratio:
|
||||||
|
out = image.resize(size, resample=method)
|
||||||
|
else:
|
||||||
|
out = Image.new(image.mode, size, color)
|
||||||
|
if im_ratio > dest_ratio:
|
||||||
|
new_height = int(image.height / image.width * size[0])
|
||||||
|
if new_height != size[1]:
|
||||||
|
image = image.resize((size[0], new_height), resample=method)
|
||||||
|
|
||||||
|
y = int((size[1] - new_height) * max(0, min(centering[1], 1)))
|
||||||
|
out.paste(image, (0, y))
|
||||||
|
else:
|
||||||
|
new_width = int(image.width / image.height * size[1])
|
||||||
|
if new_width != size[0]:
|
||||||
|
image = image.resize((new_width, size[1]), resample=method)
|
||||||
|
|
||||||
|
x = int((size[0] - new_width) * max(0, min(centering[0], 1)))
|
||||||
|
out.paste(image, (x, 0))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def crop(image, border=0):
|
||||||
|
"""
|
||||||
|
Remove border from image. The same amount of pixels are removed
|
||||||
|
from all four sides. This function works on all image modes.
|
||||||
|
|
||||||
|
.. seealso:: :py:meth:`~PIL.Image.Image.crop`
|
||||||
|
|
||||||
|
:param image: The image to crop.
|
||||||
|
:param border: The number of pixels to remove.
|
||||||
|
:return: An image.
|
||||||
|
"""
|
||||||
|
left, top, right, bottom = _border(border)
|
||||||
|
return image.crop((left, top, image.size[0] - right, image.size[1] - bottom))
|
||||||
|
|
||||||
|
|
||||||
|
def scale(image, factor, resample=Image.BICUBIC):
|
||||||
|
"""
|
||||||
|
Returns a rescaled image by a specific factor given in parameter.
|
||||||
|
A factor greater than 1 expands the image, between 0 and 1 contracts the
|
||||||
|
image.
|
||||||
|
|
||||||
|
:param image: The image to rescale.
|
||||||
|
:param factor: The expansion factor, as a float.
|
||||||
|
:param resample: What resampling method to use. Default is
|
||||||
|
:py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.
|
||||||
|
:returns: An :py:class:`~PIL.Image.Image` object.
|
||||||
|
"""
|
||||||
|
if factor == 1:
|
||||||
|
return image.copy()
|
||||||
|
elif factor <= 0:
|
||||||
|
raise ValueError("the factor must be greater than 0")
|
||||||
|
else:
|
||||||
|
size = (round(factor * image.width), round(factor * image.height))
|
||||||
|
return image.resize(size, resample)
|
||||||
|
|
||||||
|
|
||||||
|
def deform(image, deformer, resample=Image.BILINEAR):
|
||||||
|
"""
|
||||||
|
Deform the image.
|
||||||
|
|
||||||
|
:param image: The image to deform.
|
||||||
|
:param deformer: A deformer object. Any object that implements a
|
||||||
|
``getmesh`` method can be used.
|
||||||
|
:param resample: An optional resampling filter. Same values possible as
|
||||||
|
in the PIL.Image.transform function.
|
||||||
|
:return: An image.
|
||||||
|
"""
|
||||||
|
return image.transform(image.size, Image.MESH, deformer.getmesh(image), resample)
|
||||||
|
|
||||||
|
|
||||||
|
def equalize(image, mask=None):
|
||||||
|
"""
|
||||||
|
Equalize the image histogram. This function applies a non-linear
|
||||||
|
mapping to the input image, in order to create a uniform
|
||||||
|
distribution of grayscale values in the output image.
|
||||||
|
|
||||||
|
:param image: The image to equalize.
|
||||||
|
:param mask: An optional mask. If given, only the pixels selected by
|
||||||
|
the mask are included in the analysis.
|
||||||
|
:return: An image.
|
||||||
|
"""
|
||||||
|
if image.mode == "P":
|
||||||
|
image = image.convert("RGB")
|
||||||
|
h = image.histogram(mask)
|
||||||
|
lut = []
|
||||||
|
for b in range(0, len(h), 256):
|
||||||
|
histo = [_f for _f in h[b : b + 256] if _f]
|
||||||
|
if len(histo) <= 1:
|
||||||
|
lut.extend(list(range(256)))
|
||||||
|
else:
|
||||||
|
step = (functools.reduce(operator.add, histo) - histo[-1]) // 255
|
||||||
|
if not step:
|
||||||
|
lut.extend(list(range(256)))
|
||||||
|
else:
|
||||||
|
n = step // 2
|
||||||
|
for i in range(256):
|
||||||
|
lut.append(n // step)
|
||||||
|
n = n + h[i + b]
|
||||||
|
return _lut(image, lut)
|
||||||
|
|
||||||
|
|
||||||
|
def expand(image, border=0, fill=0):
|
||||||
|
"""
|
||||||
|
Add border to the image
|
||||||
|
|
||||||
|
:param image: The image to expand.
|
||||||
|
:param border: Border width, in pixels.
|
||||||
|
:param fill: Pixel fill value (a color value). Default is 0 (black).
|
||||||
|
:return: An image.
|
||||||
|
"""
|
||||||
|
left, top, right, bottom = _border(border)
|
||||||
|
width = left + image.size[0] + right
|
||||||
|
height = top + image.size[1] + bottom
|
||||||
|
out = Image.new(image.mode, (width, height), _color(fill, image.mode))
|
||||||
|
out.paste(image, (left, top))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def fit(image, size, method=Image.BICUBIC, bleed=0.0, centering=(0.5, 0.5)):
|
||||||
|
"""
|
||||||
|
Returns a sized and cropped version of the image, cropped to the
|
||||||
|
requested aspect ratio and size.
|
||||||
|
|
||||||
|
This function was contributed by Kevin Cazabon.
|
||||||
|
|
||||||
|
:param image: The image to size and crop.
|
||||||
|
:param size: The requested output size in pixels, given as a
|
||||||
|
(width, height) tuple.
|
||||||
|
:param method: What resampling method to use. Default is
|
||||||
|
:py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.
|
||||||
|
:param bleed: Remove a border around the outside of the image from all
|
||||||
|
four edges. The value is a decimal percentage (use 0.01 for
|
||||||
|
one percent). The default value is 0 (no border).
|
||||||
|
Cannot be greater than or equal to 0.5.
|
||||||
|
:param centering: Control the cropping position. Use (0.5, 0.5) for
|
||||||
|
center cropping (e.g. if cropping the width, take 50% off
|
||||||
|
of the left side, and therefore 50% off the right side).
|
||||||
|
(0.0, 0.0) will crop from the top left corner (i.e. if
|
||||||
|
cropping the width, take all of the crop off of the right
|
||||||
|
side, and if cropping the height, take all of it off the
|
||||||
|
bottom). (1.0, 0.0) will crop from the bottom left
|
||||||
|
corner, etc. (i.e. if cropping the width, take all of the
|
||||||
|
crop off the left side, and if cropping the height take
|
||||||
|
none from the top, and therefore all off the bottom).
|
||||||
|
:return: An image.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# by Kevin Cazabon, Feb 17/2000
|
||||||
|
# kevin@cazabon.com
|
||||||
|
# http://www.cazabon.com
|
||||||
|
|
||||||
|
# ensure centering is mutable
|
||||||
|
centering = list(centering)
|
||||||
|
|
||||||
|
if not 0.0 <= centering[0] <= 1.0:
|
||||||
|
centering[0] = 0.5
|
||||||
|
if not 0.0 <= centering[1] <= 1.0:
|
||||||
|
centering[1] = 0.5
|
||||||
|
|
||||||
|
if not 0.0 <= bleed < 0.5:
|
||||||
|
bleed = 0.0
|
||||||
|
|
||||||
|
# calculate the area to use for resizing and cropping, subtracting
|
||||||
|
# the 'bleed' around the edges
|
||||||
|
|
||||||
|
# number of pixels to trim off on Top and Bottom, Left and Right
|
||||||
|
bleed_pixels = (bleed * image.size[0], bleed * image.size[1])
|
||||||
|
|
||||||
|
live_size = (
|
||||||
|
image.size[0] - bleed_pixels[0] * 2,
|
||||||
|
image.size[1] - bleed_pixels[1] * 2,
|
||||||
|
)
|
||||||
|
|
||||||
|
# calculate the aspect ratio of the live_size
|
||||||
|
live_size_ratio = live_size[0] / live_size[1]
|
||||||
|
|
||||||
|
# calculate the aspect ratio of the output image
|
||||||
|
output_ratio = size[0] / size[1]
|
||||||
|
|
||||||
|
# figure out if the sides or top/bottom will be cropped off
|
||||||
|
if live_size_ratio == output_ratio:
|
||||||
|
# live_size is already the needed ratio
|
||||||
|
crop_width = live_size[0]
|
||||||
|
crop_height = live_size[1]
|
||||||
|
elif live_size_ratio >= output_ratio:
|
||||||
|
# live_size is wider than what's needed, crop the sides
|
||||||
|
crop_width = output_ratio * live_size[1]
|
||||||
|
crop_height = live_size[1]
|
||||||
|
else:
|
||||||
|
# live_size is taller than what's needed, crop the top and bottom
|
||||||
|
crop_width = live_size[0]
|
||||||
|
crop_height = live_size[0] / output_ratio
|
||||||
|
|
||||||
|
# make the crop
|
||||||
|
crop_left = bleed_pixels[0] + (live_size[0] - crop_width) * centering[0]
|
||||||
|
crop_top = bleed_pixels[1] + (live_size[1] - crop_height) * centering[1]
|
||||||
|
|
||||||
|
crop = (crop_left, crop_top, crop_left + crop_width, crop_top + crop_height)
|
||||||
|
|
||||||
|
# resize the image and return it
|
||||||
|
return image.resize(size, method, box=crop)
|
||||||
|
|
||||||
|
|
||||||
|
def flip(image):
|
||||||
|
"""
|
||||||
|
Flip the image vertically (top to bottom).
|
||||||
|
|
||||||
|
:param image: The image to flip.
|
||||||
|
:return: An image.
|
||||||
|
"""
|
||||||
|
return image.transpose(Image.FLIP_TOP_BOTTOM)
|
||||||
|
|
||||||
|
|
||||||
|
def grayscale(image):
|
||||||
|
"""
|
||||||
|
Convert the image to grayscale.
|
||||||
|
|
||||||
|
:param image: The image to convert.
|
||||||
|
:return: An image.
|
||||||
|
"""
|
||||||
|
return image.convert("L")
|
||||||
|
|
||||||
|
|
||||||
|
def invert(image):
|
||||||
|
"""
|
||||||
|
Invert (negate) the image.
|
||||||
|
|
||||||
|
:param image: The image to invert.
|
||||||
|
:return: An image.
|
||||||
|
"""
|
||||||
|
lut = []
|
||||||
|
for i in range(256):
|
||||||
|
lut.append(255 - i)
|
||||||
|
return _lut(image, lut)
|
||||||
|
|
||||||
|
|
||||||
|
def mirror(image):
|
||||||
|
"""
|
||||||
|
Flip image horizontally (left to right).
|
||||||
|
|
||||||
|
:param image: The image to mirror.
|
||||||
|
:return: An image.
|
||||||
|
"""
|
||||||
|
return image.transpose(Image.FLIP_LEFT_RIGHT)
|
||||||
|
|
||||||
|
|
||||||
|
def posterize(image, bits):
|
||||||
|
"""
|
||||||
|
Reduce the number of bits for each color channel.
|
||||||
|
|
||||||
|
:param image: The image to posterize.
|
||||||
|
:param bits: The number of bits to keep for each channel (1-8).
|
||||||
|
:return: An image.
|
||||||
|
"""
|
||||||
|
lut = []
|
||||||
|
mask = ~(2 ** (8 - bits) - 1)
|
||||||
|
for i in range(256):
|
||||||
|
lut.append(i & mask)
|
||||||
|
return _lut(image, lut)
|
||||||
|
|
||||||
|
|
||||||
|
def solarize(image, threshold=128):
|
||||||
|
"""
|
||||||
|
Invert all pixel values above a threshold.
|
||||||
|
|
||||||
|
:param image: The image to solarize.
|
||||||
|
:param threshold: All pixels above this greyscale level are inverted.
|
||||||
|
:return: An image.
|
||||||
|
"""
|
||||||
|
lut = []
|
||||||
|
for i in range(256):
|
||||||
|
if i < threshold:
|
||||||
|
lut.append(i)
|
||||||
|
else:
|
||||||
|
lut.append(255 - i)
|
||||||
|
return _lut(image, lut)
|
||||||
|
|
||||||
|
|
||||||
|
def exif_transpose(image):
|
||||||
|
"""
|
||||||
|
If an image has an EXIF Orientation tag, return a new image that is
|
||||||
|
transposed accordingly. Otherwise, return a copy of the image.
|
||||||
|
|
||||||
|
:param image: The image to transpose.
|
||||||
|
:return: An image.
|
||||||
|
"""
|
||||||
|
exif = image.getexif()
|
||||||
|
orientation = exif.get(0x0112)
|
||||||
|
method = {
|
||||||
|
2: Image.FLIP_LEFT_RIGHT,
|
||||||
|
3: Image.ROTATE_180,
|
||||||
|
4: Image.FLIP_TOP_BOTTOM,
|
||||||
|
5: Image.TRANSPOSE,
|
||||||
|
6: Image.ROTATE_270,
|
||||||
|
7: Image.TRANSVERSE,
|
||||||
|
8: Image.ROTATE_90,
|
||||||
|
}.get(orientation)
|
||||||
|
if method is not None:
|
||||||
|
transposed_image = image.transpose(method)
|
||||||
|
del exif[0x0112]
|
||||||
|
transposed_image.info["exif"] = exif.tobytes()
|
||||||
|
return transposed_image
|
||||||
|
return image.copy()
|
||||||
221
venv/lib/python3.9/site-packages/PIL/ImagePalette.py
Normal file
|
|
@ -0,0 +1,221 @@
|
||||||
|
#
|
||||||
|
# The Python Imaging Library.
|
||||||
|
# $Id$
|
||||||
|
#
|
||||||
|
# image palette object
|
||||||
|
#
|
||||||
|
# History:
|
||||||
|
# 1996-03-11 fl Rewritten.
|
||||||
|
# 1997-01-03 fl Up and running.
|
||||||
|
# 1997-08-23 fl Added load hack
|
||||||
|
# 2001-04-16 fl Fixed randint shadow bug in random()
|
||||||
|
#
|
||||||
|
# Copyright (c) 1997-2001 by Secret Labs AB
|
||||||
|
# Copyright (c) 1996-1997 by Fredrik Lundh
|
||||||
|
#
|
||||||
|
# See the README file for information on usage and redistribution.
|
||||||
|
#
|
||||||
|
|
||||||
|
import array
|
||||||
|
|
||||||
|
from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile
|
||||||
|
|
||||||
|
|
||||||
|
class ImagePalette:
|
||||||
|
"""
|
||||||
|
Color palette for palette mapped images
|
||||||
|
|
||||||
|
:param mode: The mode to use for the Palette. See:
|
||||||
|
:ref:`concept-modes`. Defaults to "RGB"
|
||||||
|
:param palette: An optional palette. If given, it must be a bytearray,
|
||||||
|
an array or a list of ints between 0-255 and of length ``size``
|
||||||
|
times the number of colors in ``mode``. The list must be aligned
|
||||||
|
by channel (All R values must be contiguous in the list before G
|
||||||
|
and B values.) Defaults to 0 through 255 per channel.
|
||||||
|
:param size: An optional palette size. If given, it cannot be equal to
|
||||||
|
or greater than 256. Defaults to 0.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, mode="RGB", palette=None, size=0):
|
||||||
|
self.mode = mode
|
||||||
|
self.rawmode = None # if set, palette contains raw data
|
||||||
|
self.palette = palette or bytearray(range(256)) * len(self.mode)
|
||||||
|
self.colors = {}
|
||||||
|
self.dirty = None
|
||||||
|
if (size == 0 and len(self.mode) * 256 != len(self.palette)) or (
|
||||||
|
size != 0 and size != len(self.palette)
|
||||||
|
):
|
||||||
|
raise ValueError("wrong palette size")
|
||||||
|
|
||||||
|
def copy(self):
|
||||||
|
new = ImagePalette()
|
||||||
|
|
||||||
|
new.mode = self.mode
|
||||||
|
new.rawmode = self.rawmode
|
||||||
|
if self.palette is not None:
|
||||||
|
new.palette = self.palette[:]
|
||||||
|
new.colors = self.colors.copy()
|
||||||
|
new.dirty = self.dirty
|
||||||
|
|
||||||
|
return new
|
||||||
|
|
||||||
|
def getdata(self):
|
||||||
|
"""
|
||||||
|
Get palette contents in format suitable for the low-level
|
||||||
|
``im.putpalette`` primitive.
|
||||||
|
|
||||||
|
.. warning:: This method is experimental.
|
||||||
|
"""
|
||||||
|
if self.rawmode:
|
||||||
|
return self.rawmode, self.palette
|
||||||
|
return self.mode + ";L", self.tobytes()
|
||||||
|
|
||||||
|
def tobytes(self):
|
||||||
|
"""Convert palette to bytes.
|
||||||
|
|
||||||
|
.. warning:: This method is experimental.
|
||||||
|
"""
|
||||||
|
if self.rawmode:
|
||||||
|
raise ValueError("palette contains raw palette data")
|
||||||
|
if isinstance(self.palette, bytes):
|
||||||
|
return self.palette
|
||||||
|
arr = array.array("B", self.palette)
|
||||||
|
if hasattr(arr, "tobytes"):
|
||||||
|
return arr.tobytes()
|
||||||
|
return arr.tostring()
|
||||||
|
|
||||||
|
# Declare tostring as an alias for tobytes
|
||||||
|
tostring = tobytes
|
||||||
|
|
||||||
|
def getcolor(self, color):
|
||||||
|
"""Given an rgb tuple, allocate palette entry.
|
||||||
|
|
||||||
|
.. warning:: This method is experimental.
|
||||||
|
"""
|
||||||
|
if self.rawmode:
|
||||||
|
raise ValueError("palette contains raw palette data")
|
||||||
|
if isinstance(color, tuple):
|
||||||
|
try:
|
||||||
|
return self.colors[color]
|
||||||
|
except KeyError as e:
|
||||||
|
# allocate new color slot
|
||||||
|
if isinstance(self.palette, bytes):
|
||||||
|
self.palette = bytearray(self.palette)
|
||||||
|
index = len(self.colors)
|
||||||
|
if index >= 256:
|
||||||
|
raise ValueError("cannot allocate more than 256 colors") from e
|
||||||
|
self.colors[color] = index
|
||||||
|
self.palette[index] = color[0]
|
||||||
|
self.palette[index + 256] = color[1]
|
||||||
|
self.palette[index + 512] = color[2]
|
||||||
|
self.dirty = 1
|
||||||
|
return index
|
||||||
|
else:
|
||||||
|
raise ValueError(f"unknown color specifier: {repr(color)}")
|
||||||
|
|
||||||
|
def save(self, fp):
|
||||||
|
"""Save palette to text file.
|
||||||
|
|
||||||
|
.. warning:: This method is experimental.
|
||||||
|
"""
|
||||||
|
if self.rawmode:
|
||||||
|
raise ValueError("palette contains raw palette data")
|
||||||
|
if isinstance(fp, str):
|
||||||
|
fp = open(fp, "w")
|
||||||
|
fp.write("# Palette\n")
|
||||||
|
fp.write(f"# Mode: {self.mode}\n")
|
||||||
|
for i in range(256):
|
||||||
|
fp.write(f"{i}")
|
||||||
|
for j in range(i * len(self.mode), (i + 1) * len(self.mode)):
|
||||||
|
try:
|
||||||
|
fp.write(f" {self.palette[j]}")
|
||||||
|
except IndexError:
|
||||||
|
fp.write(" 0")
|
||||||
|
fp.write("\n")
|
||||||
|
fp.close()
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# Internal
|
||||||
|
|
||||||
|
|
||||||
|
def raw(rawmode, data):
|
||||||
|
palette = ImagePalette()
|
||||||
|
palette.rawmode = rawmode
|
||||||
|
palette.palette = data
|
||||||
|
palette.dirty = 1
|
||||||
|
return palette
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------
|
||||||
|
# Factories
|
||||||
|
|
||||||
|
|
||||||
|
def make_linear_lut(black, white):
|
||||||
|
lut = []
|
||||||
|
if black == 0:
|
||||||
|
for i in range(256):
|
||||||
|
lut.append(white * i // 255)
|
||||||
|
else:
|
||||||
|
raise NotImplementedError # FIXME
|
||||||
|
return lut
|
||||||
|
|
||||||
|
|
||||||
|
def make_gamma_lut(exp):
|
||||||
|
lut = []
|
||||||
|
for i in range(256):
|
||||||
|
lut.append(int(((i / 255.0) ** exp) * 255.0 + 0.5))
|
||||||
|
return lut
|
||||||
|
|
||||||
|
|
||||||
|
def negative(mode="RGB"):
|
||||||
|
palette = list(range(256))
|
||||||
|
palette.reverse()
|
||||||
|
return ImagePalette(mode, palette * len(mode))
|
||||||
|
|
||||||
|
|
||||||
|
def random(mode="RGB"):
|
||||||
|
from random import randint
|
||||||
|
|
||||||
|
palette = []
|
||||||
|
for i in range(256 * len(mode)):
|
||||||
|
palette.append(randint(0, 255))
|
||||||
|
return ImagePalette(mode, palette)
|
||||||
|
|
||||||
|
|
||||||
|
def sepia(white="#fff0c0"):
|
||||||
|
r, g, b = ImageColor.getrgb(white)
|
||||||
|
r = make_linear_lut(0, r)
|
||||||
|
g = make_linear_lut(0, g)
|
||||||
|
b = make_linear_lut(0, b)
|
||||||
|
return ImagePalette("RGB", r + g + b)
|
||||||
|
|
||||||
|
|
||||||
|
def wedge(mode="RGB"):
|
||||||
|
return ImagePalette(mode, list(range(256)) * len(mode))
|
||||||
|
|
||||||
|
|
||||||
|
def load(filename):
|
||||||
|
|
||||||
|
# FIXME: supports GIMP gradients only
|
||||||
|
|
||||||
|
with open(filename, "rb") as fp:
|
||||||
|
|
||||||
|
for paletteHandler in [
|
||||||
|
GimpPaletteFile.GimpPaletteFile,
|
||||||
|
GimpGradientFile.GimpGradientFile,
|
||||||
|
PaletteFile.PaletteFile,
|
||||||
|
]:
|
||||||
|
try:
|
||||||
|
fp.seek(0)
|
||||||
|
lut = paletteHandler(fp).getpalette()
|
||||||
|
if lut:
|
||||||
|
break
|
||||||
|
except (SyntaxError, ValueError):
|
||||||
|
# import traceback
|
||||||
|
# traceback.print_exc()
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise OSError("cannot load palette")
|
||||||
|
|
||||||
|
return lut # data, rawmode
|
||||||