"""
Programme   : TP-images-correction-exo1.py
Langage     : Python 3.7.3
Modules     : Pillow 7.1.2
Auteur      : Mathieu Pons
Description : affiche les informations d'une image
Docs Pillow : https://pillow.readthedocs.io/en/stable/

Exercice à réaliser :
	1)Ecrire une fonction printRGB(pimg, ppixel)

	2)Ecrire une fonction afficher_info(pimg) qui reproduit l'affichage suivant :

+ -------------------------------------------------------- +
| perroquet.jpg                                            |
+ -------------------------------------------------------- +
| FORMAT                         : JPEG                    |
| MODE                           : Couleurs RGB            |
| TAILLE                         : 1920 x 1280             |
| NB PIXELS                      : 2457600                 |
| POIDS (non compressé) en Mo    : 7.03                    |
+ -------------------------------------------------------- +

Le poids non compressé d'une image correspond à son occupation en mémoire de travail qui est
forcément plus importante que son poids sur disque sur lequel elle est stockée sous forme compressée
(format JPG ou PNG ...). Attention, 1 Ko = 1024 octets et 1 Mo = 1024 Ko

	3) Ecrire une fonction retailler_sauver(pimg, plarg) qui modifie la largeur de l'image en
	conservant ses proportions et l'enregistre au format PNG.
"""

# IMPORT =========================================================================================
from PIL import Image

# FONCTIONS =======================================================================================
def printRGB(pimg, ppixel):
	"""
    Description : affiche le code RGB de ppixel dans l'image pimg
	Paramètres  : type(pimg) => Image.PIL
	              type(ppixel) => 2-tuple : (x, y)
	Retour      : aucun
	"""
	r, g, b = pimg.getpixel(ppixel)
	print("Pixel({},{}) => RGB = ({},{},{})".format(ppixel[0], ppixel[1], r, g, b))

def afficher_info(pimg):
	"""
	Description : 	affiche des informations sur l'image passée en paramètre
	Paramètres 	: 	type(pimg) => Image.PIL
	Retour 		: 	aucun
	"""
	_mode = pimg.mode
	_nbpixel = pimg.width * pimg.height # nombre de pixel de l'image
	if _mode == "1":
		_txtmode = "Noir et blanc"
		_poids = _nbpixel / 8 # pixel codé sur un bit (1/8ième d'octet) -> blanc ou noir
	elif _mode == "L":
		_txtmode = "Niveaux de gris"
		_poids = _nbpixel # pixel codé sur un octet (8 bits) -> 256 niveaux de gris
	elif _mode == "RGB":
		_txtmode = "Couleurs RGB"
		_poids = _nbpixel * 3 # pixel codé sur 3 octets (24 bits), un par couleur -> 16 millions de couleurs
	elif _mode == "RGBA":
		_txtmode = "Couleurs RGB + Alpha"
		_poids = _nbpixel * 4 # pixel codé sur 4 octets (32 bits), un par couleur + un canal de transparence
	else:
		_txtmode = _mode

	print("+ {:-^56} +".format(""))
	print("| {:<56} |".format(pimg.filename))
	print("+ {:-^56} +".format(""))
	print("| {:<30} : {:<23} |".format("FORMAT", pimg.format))
	print("| {:<30} : {:<23} |".format("MODE", _txtmode))
	print("| {:<30} : {:<23} |".format("TAILLE", str(pimg.width) + " x " + str(pimg.height)))
	print("| {:<30} : {:<23} |".format("NB PIXELS", _nbpixel))
	print("| {:<30} : {:<23.2f} |".format("POIDS(non compressé) en Mo ", _poids / (1024 * 1024)))
	print("+ {:-^56} +".format(""))
	print("")

def retailler_sauver(pimg, plarg):
	"""
    Description : modifie la largeur de l'image en conservant son ratio et l'enregistre au format PNG
	Paramètres  : type(pimg) => Image.PIL
	              type(plarg) => int
	Retour      : Image.PIL
	"""
	_ratio = plarg / pimg.width # facteur d'échelle pour conserver les proportions de l'image
	_haut = int(pimg.height * _ratio) # on calcule la nouvelle hauteur qui doit être entières
	img_retaille = pimg.resize((plarg, _haut)) # la méthode d'image resize prend en paramètre un 2-tuple d'ENTIERS du type (largeur, hauteur)
	(_nomfic, _extfic) = pimg.filename.split('.') # on découpe le nom du ficher au niveau de l'extension
	img_retaille.save(_nomfic + ".png", "PNG") # on enregistre l'image au format PNG avec l'extension .png

# PROGRAMME PRINCIPAL =============================================================================
img = Image.open("perroquet.jpg")
afficher_info(img)
printRGB(img, (562, 655))
retailler_sauver(img, int(img.width / 2))
