
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.ImageFormatException;

public class CropImage {
	public CropImage(){
		super();
		BufferedImage image = null;
		BufferedImage image2 = null;
		
		try {

			// Read from a file
			File file = new File("ocr1.jpg");
			image = ImageIO.read(file);
		} catch (IOException e) {

			System.err.println("Cannot open the file.");
		}
		
		System.out.println("Width: " + image.getWidth());
		System.out.println("Height: " + image.getHeight());
		
		
		//ตัด รูปภาพจากภาพใหญ่ เป็นภาพเล็ก  มี parameter 4 ตัว คือ
		// x,y,width,height
		image2 = image.getSubimage(0,5,image.getWidth(),30);
		
		
		try {
			writeImage(image2,1);
		} catch (ImageFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 

	}

//	แปลงค่า Hex เป็น integer ตังแต่ 0-255
	public int averageRGB(int rgb)
	{
		int r = (rgb >> 16) & 0xff;
		int g = (rgb >>  8) & 0xff;
		int b = (rgb >>  0) & 0xff;
	
		int nIntensity = (int) (r+g+b)/3;
		r = g = b = nIntensity;
		return nIntensity;
	}	
	
	//แปลงค่าจาก integer กลับเป็น Hex เนื่องจากก่อนสร้างภาพขึ้นมาเป็นไฟล์ ค่าที่นำไป setRGB
	//ลงใน BufferedImage จะต้องกลับไปเป็น Hex เหมือนเดิม
	public int averageRGB2(int rgb)
	{

		int r = (rgb  & 0xff ) << 16;
		int g = (rgb  & 0xff) << 8;
		int b = (rgb  & 0xff) ;

		int nIntensity = (int) (r+g+b);
		r = g = b = nIntensity;
		return (rgb & 0xff000000)| (r<<16) | (g<<8) | (b<<0);

	}
	
	//	method นี้สำหรับสร้างไฟล์รูปภาพขึ้นมาใหม่ซึ่งจะสร้างเป็นไฟล์ png เนื่องจาก
	// ไฟล์ png จะได้คุณภาพของภาพดีกว่า ซึ่งถ้า save เป็น jpg จะทำให้ภาพแตก
	public void writeImage(BufferedImage img,int numimg){
		File f = new File("img_crop"+numimg+".png");
	     try {
			ImageIO.write(img, "png", f);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new CropImage();
	}

}
