package devUtil;

import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import java.io.InputStream;

import javax.imageio.ImageIO;

import com.sun.opengl.util.texture.Texture;
import com.sun.opengl.util.texture.TextureData;
import com.sun.opengl.util.texture.TextureIO;

public class TextureLoader {
	
	static TextureLoader tl = new TextureLoader();
	
	public static Texture getTexture(String image) {
		
		TextureData data = null;
		
		try {
			
			InputStream stream = tl.getClass().getResourceAsStream(image);
			
			data = TextureIO.newTextureData(stream, false,
					image.substring(image.lastIndexOf(".") + 1));
		}
		
		catch (IOException exc) {
			data = null;
		}
		
		if(data != null)
			return TextureIO.newTexture(data);
		
		else
			return null;
	}
	
	public static Texture createTexture(BufferedImage image, String imageType) {
		
		TextureData data = null;
		
		try {
			
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			ImageIO.write((RenderedImage) image, "jpg", os);
			
			InputStream stream = new ByteArrayInputStream(os.toByteArray());
			
			data = TextureIO.newTextureData(stream, false, imageType);
		}
		
		catch (IOException exc) {
			data = null;
		}
		
		if(data != null)
			return TextureIO.newTexture(data);
		
		else
			return null;
	}
}