如何从Java中提取当前图片中的图片?

时间:2015-12-03 00:37:20

标签: java image

我被分配了一个必须编写代码的任务,该代码将从当前图片中提取图片。我做了一些研究,发现了一些名为“BufferedImage'是我需要用来完成这项任务的,但是,我从未被教过如何使用它,所以我想我可能会要求一些帮助/提示,​​特别是如果这不是我实际需要使用的。我目前在IntelliJ工作。

实际任务: 在Picture类及其JavaDocs中编写一个名为extract的方法。该方法应从当前图片中提取由要提取的区域的左上角坐标(x,y),区域的宽度和高度定义的新图片。您的方法应该通过extractTests类中包含的测试。

图片类:

public Picture(int width, int height) {
// let the parent class handle this width and height
super(width, height);
}

/**
* Constructor that takes a picture and creates a
* copy of that picture
*/
public Picture(Picture copyPicture) {
// let the parent class do the copy
super(copyPicture);
}

/**
* Constructor that takes a buffered image
*
* @param image the buffered image to use
*/
public Picture(BufferedImage image) {
super(image);
}

////////////////////// methods ///////////////////////////////////////

/**
* Method to return a string with information about this picture.
*
* @return a string with information about the picture such as fileName,
* height and width.
*/
public String toString() {
String output = "Picture, filename " + getFileName() +
" height " + getHeight()
+ " width " + getWidth();
return output;

}

public static void main(String[] args) {
FileChooser.setMediaPath("mediasources/");
String fileName = FileChooser.getMediaPath("butterfly1.jpg");
Picture pictObj = new Picture(fileName);
pictObj.explore();
}
}

测试类:

public class n extractTests {
@Test
public void comparePicturesTest1() {
FileChooser.setMediaPath("mediasources/");
String fileName = FileChooser.getMediaPath("butterfly1.jpg");
Picture pictObj = new Picture(fileName);
Picture out = pictObj.extract(30, 240, 100, 100);
String fileName3 = FileChooser.getMediaPath("extract2.jpg");
out.write(fileName3);
String fileName1 = FileChooser.getMediaPath("extract1.jpg");
Picture pict2 = new Picture(fileName1);
String fileName2 = FileChooser.getMediaPath("extract2.jpg");
Picture pict3 = new Picture(fileName2);
comparePictures(pict2, pict3);
}

@Test
public void comparePicturesTest2() {
FileChooser.setMediaPath("mediasources/");
String fileName = FileChooser.getMediaPath("butterfly2.jpg");
Picture pictObj = new Picture(fileName);
Picture out = pictObj.extract(80, 50, 400, 300);
String fileName3 = FileChooser.getMediaPath("extract4.jpg");
out.write(fileName3);
String fileName1 = FileChooser.getMediaPath("extract3.jpg");
Picture pict2 = new Picture(fileName1);
String fileName2 = FileChooser.getMediaPath("extract4.jpg");
Picture pict3 = new Picture(fileName2);
comparePictures(pict2, pict3);
}

private void comparePictures(Picture pict2, Picture pict3) {
Pixel[] pixels1 = pict2.getPixels();
Pixel[] pixels2 = pict3.getPixels();
assertEquals(pixels1.length, pixels2.length);
for(int i = 0; i < pixels1.length; i++) {
Pixel pixel1 = pixels1[i];
Pixel pixel2 = pixels2[i];
assertEquals("At pixel (" + pixel1.getX() + ", " + pixel1.getY() + ")",
pixel1.getColor(), pixel2.getColor());
}
}
}

提前致谢!

0 个答案:

没有答案