Tuesday, May 8, 2012

cropping an image using java

//This lab assignment will have you write at least two methods in java that will create a new image that will
 //show a portion from another image. This technique is called cropping.
//** a specific image was used for this, u need to change the values!!






import java.awt.Color;

public class Lab11
{
public static void main (String[] args)
{

// use the string files to get the first picture,
String filename = FileChooser.pickAFile();
Picture p1 = new Picture (filename);

Picture p2 ;
int x1, x2;
int y1, y2;
// determine the values by using p1.explore()

//Input your values of X, Y of the part you want to crop from the image.

x1 =123 ;
x2 = 621;
y1 = 134;
y2 = 292;

// call method
p2 = cropImg (p1,x1,y1,x2,y2);

//use explore to determine the part you want crop
//p1.explore();

//display the picture
p2.show();

// show the original image
//p1.show();
// get a new filename and save the picture
String saveFilename = FileChooser.pickAFile ();
//p2.write (saveFilename);

} // end of main

// alternate way to access the pixels from three different pictures
public static Picture cropImg (Picture p1,
int x1, int y1,
int x2, int y2)
{
// set up my return variable
Picture p2;

// set dimensions of the new created picture and copy pixels over to p2
p2 = new Picture ((x2-x1),(y2-y1));

// access pixels.
Pixel pixelArray[] = p1.getPixels();

for (int i = 0 ; i < pixelArray.length ; i++)
{
// access the original pixel and information from that pixel
Pixel pix1 = pixelArray [i];
int red = pix1.getRed ();
int green = pix1.getGreen ();
int blue = pix1.getBlue ();
int xPos = pix1.getX();
int yPos = pix1.getY();

// access the portion of the picture to be cropped
if ( ((xPos >= x1) &&
(xPos < x2)) &&
((yPos >= y1) &&
(yPos < y2)) )
{
// detirmine the new location for the pixels
int X3;
X3 = xPos-x1;
int Y3;
Y3 = yPos-y1;

Pixel pix2 = p2.getPixel (X3, Y3);

// Set colors
pix2.setRed (red);
pix2.setGreen (green);
pix2.setBlue (blue);

}

} // end of for loop

return p2;

} // end of cropImg method

} // end of class

No comments:

Post a Comment