我是編程新手,我目前正在研究一個將圖像旋轉到右側和上下顛倒的程序。我能夠使顛倒的方法工作,但不能向右旋轉(順時針旋轉90度)。它不斷給我一個越界的錯誤,我不知道爲什麼,因爲我看過其他的例子。任何幫助,將不勝感激。線程「main」中的異常java.lang.ArrayIndexOutOfBoundsException:座標超出邊界setRGB
這裏是我的工作方法:
public Image rotateRight()
{
Image right = new Image (this);
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int width = right.img.getWidth();
int height = right.img.getHeight();
for (int i = 0; i < width; i++)
for (int j = 0; j < height; j++)
{
this.img.setRGB(height-j-1,i,right.img.getRGB(i,j));
}
return right;
}
下面的代碼的其餘部分:
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
public class Image {
private BufferedImage img = null;
int width;
int height;
private Image()
{
}
public Image (int w, int h)
{
img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
width = w;
height = h;
}
public Image (Image anotherImg)
{
width = anotherImg.img.getWidth();
height = anotherImg.img.getHeight();
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < height; i++)
for (int j = 0; j < width; j++)
{
this.img.setRGB(j,i,anotherImg.img.getRGB(j,i)) ;
}
}
public String toString()
{
return "Width of Image:" +width+"\nHeight of Image:"+height;
}
public Image (String filename)
{
try
{
img = ImageIO.read(new File(filename));
width = img.getWidth();
height = img.getHeight();
}
catch (IOException e)
{
System.out.println(e);
}
}
public void save(String filename, String extension)
{
try
{
File outputfile = new File(filename);
ImageIO.write(img, extension, outputfile);
}
catch (IOException e)
{
System.out.println(e);
}
}
public Image copy()
{
Image copiedImage = new Image(this);
return copiedImage;
}
這裏主營:
public static void main (String args[])
{
Image srcimg = new Image("apple.jpg");
System.out.println(srcimg);
Image copy = srcimg.copy();
copy.save("apple-copy.jpg", "jpg");
Image copy2 = srcimg.copy();
Image right = copy2.rotateRight();
right.save("apple-rotateRight.jpg", "jpg");
}
不應該你的新圖像寬度等於原來的高度? ...我的意思是''img = new BufferedImage(height,width,BufferedImage.TYPE_INT_RGB)''......你也使用了同名的局部變量和全局變量......它有點混亂......只是說。 – Plirkee
@Plirkee Woow ....解決了我的問題,現在我非常生氣,整個過程我都認爲問題出在我的for循環中。我浪費了這麼多個小時,應該在前一段時間發佈。非常感謝你:D和感謝您的建議。 – Alexis