图像垂直翻转实现求助:Java代码运行报错(Main.java:403)
Let's break down why you're hitting that error at img[row][col] = img[height - row - 1][col] and fix it step by step. The core issue here is a mix-up in how you're calculating the image's height and width, which is causing an array index out of bounds exception.
What's Wrong in Your Current Code
Swapped height and width definitions
When storing an image as a 2D arrayint[][] img, the structure followsimg[row][column]. That means:- The height of the image is the number of rows:
img.length - The width is the number of columns per row:
img[0].length
Your code has these reversed (height = img[0].length,width = img.length). So when you loop usingheight/2as the row limit and accessimg[height - row -1][col], you're trying to access a row index that doesn't exist (sinceheighthere is actually the width/column count). That's exactly what's throwing the error.
- The height of the image is the number of rows:
Unintentional parameter override
You're passingimgas a method parameter but immediately overwriting it withUtil.readImageToMatrix(dir). This makes the input parameter useless—either remove the parameter or move the image reading logic outside the method.
Corrected Code
Here's the fixed version with clear improvements:
public static int[][] flipVertically() { // Read the image once at the start of the method String dir = "image.jpg"; int[][] img = Util.readImageToMatrix(dir); // Correct height and width calculations int height = img.length; int width = img[0].length; // Swap top rows with corresponding bottom rows (only need to loop through half the rows) for(int row = 0; row < height / 2; row++) { for(int col = 0; col < width; col++) { // Store the top pixel temporarily int tempPixel = img[row][col]; // Assign bottom pixel to top position img[row][col] = img[height - row - 1][col]; // Assign stored top pixel to bottom position img[height - row - 1][col] = tempPixel; } } return img; }
Key Fixes Explained
- Corrected dimension logic: Now
heightproperly refers to the number of rows, soheight - row -1will always point to a valid row index from the bottom half of the image. - Cleaned up method structure: I removed the redundant
imgparameter since you're reading the image inside the method. If you intended to pass a pre-existing matrix instead, just add the parameter back and remove theUtil.readImageToMatrixline inside the method.
This should resolve the index out of bounds error you're seeing, and the vertical flip will work as expected.
内容的提问来源于stack exchange,提问作者Slurp123

