import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;


public class ImageOutils {
	
	 // Création d'une nouvelle image en inversant les pixels des lignes et des colonnes
    public static BufferedImage Rotate(BufferedImage image){
    	BufferedImage imageRotate;
    	int i, j, nbX, nbY;
    	Color color;
    	
    	nbY = image.getHeight();
    	nbX = image.getWidth();
    	imageRotate = new BufferedImage(nbY, nbX, BufferedImage.TYPE_INT_ARGB);
    	
    	for(i=0;i<nbX;i++)
    		for(j=0;j<nbY;j++)
    		{
    			color = new Color(image.getRGB(i, j));
    			imageRotate.setRGB(j, i, color.getRGB());
    		}
    	
    	return imageRotate;
    } 

    // Création d'une nouvelle image en passant en niveaux de gris
    public static BufferedImage GrayScale(BufferedImage image){
    	BufferedImage imageGray;
    	int i, j, nbX, nbY;
    	Color color;
    	
    	nbY = image.getHeight();
    	nbX = image.getWidth(); 
    	imageGray = new BufferedImage(nbX, nbY, BufferedImage.TYPE_INT_ARGB);
    	
    	for(i=0;i<nbX;i++)
    		for(j=0;j<nbY;j++)
    		{
    			color = new Color(image.getRGB(i,j));
    	        int r = color.getRed();
    	        int g = color.getGreen();
    	        int b = color.getBlue();   
    	        
    	        int luminance = (int) (0.299*r + 0.587*g + 0.114*b);  // NTSC formula
    	        
    	        imageGray.setRGB(i, j, new Color(luminance, luminance, luminance).getRGB());
    		}
    	return imageGray;
    } 

    // Création d'une nouvelle image en recadrant
    public static BufferedImage Crop(BufferedImage image, int x, int y, int tailleX, int tailleY){
    	BufferedImage imageCrop;
    	int i, j;
    	Color color;
    	
    	imageCrop = new BufferedImage(tailleX, tailleY, BufferedImage.TYPE_INT_ARGB);
    	
    	for(i=x;i<x+tailleX;i++)
    		for(j=y;j<y+tailleY;j++)
    		{
    			color = new Color(image.getRGB(i,j));    			
    	        imageCrop.setRGB(i-x, j-y, color.getRGB());
    		}
    	
    	return imageCrop;
    } 

    // Création d'une BufferedImage à partir d'une Image
    public static BufferedImage Image2Buffered(Image image){
    	BufferedImage bufImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
    	bufImage.getGraphics().drawImage(image, 0, 0, null);
    	return bufImage;
    }
    
 // Redimensionne l'image
	// ATTENTION : mauvaise qualité en sortie !!!!!!
	public static BufferedImage resize(Image image, int width, int height) {		
		BufferedImage resizedImage = new BufferedImage(width, height,
		BufferedImage.TYPE_INT_ARGB);
		Graphics2D g = resizedImage.createGraphics();
		g.drawImage(image, 0, 0, width, height, null);
		g.dispose();
		return resizedImage;
		} 
}
