Java如何实现二维数组裁剪去右两列及像素亮度调整?
问题解决
错误原因分析
- 内层循环边界错误:原代码使用
imageData.length作为内层循环终止条件,这个值是二维数组的行数,遍历列需要取单行列长度imageData[0].length - 赋值偏移逻辑错误:给新数组列下标加了2,导致新数组前两列没有被赋值,保留了int类型的默认初始值0;原数组的列偏移规则也不符合「排除最右两列」的需求
正确实现代码
import java.util.Arrays; public class ImageProcess { public static void main(String[] args) { int[][] imageData={{100,90,255,80,70,255,60,50}, {255,10,5,255,10,5,255,255}, {255,255,255,0,255,255,255,75}, {255,60,30,0,30,60,255,255}}; int[][] newImage = new int[4][6]; // 正确拷贝逻辑:排除原数组最右两列 for(int i = 0; i < newImage.length; i++) { // 按新数组的列数遍历即可,刚好对应原数组前6列(去掉最后2列) for(int j = 0; j < newImage[i].length; j++) { newImage[i][j] = imageData[i][j]; } } System.out.println("裁剪结果:" + Arrays.deepToString(newImage)); // 亮度降低50逻辑 for(int i = 0; i < newImage.length; i++) { for(int j = 0; j < newImage[i].length; j++) { int calValue = newImage[i][j] - 50; // 小于0直接取0,减操作无需判断上限(原值最大255,减后最大205在合法范围内) newImage[i][j] = Math.max(calValue, 0); } } System.out.println("亮度调整结果:" + Arrays.deepToString(newImage)); } }
输出结果
裁剪结果:[[100, 90, 255, 80, 70, 255], [255, 10, 5, 255, 10, 5], [255, 255, 255, 0, 255, 255], [255, 60, 30, 0, 30, 60]] 亮度调整结果:[[50, 40, 205, 30, 20, 205], [205, 0, 0, 205, 0, 0], [205, 205, 205, 0, 205, 205], [205, 10, 0, 0, 0, 10]]
内容的提问来源于stack exchange,提问作者Jean Baptiste Asong
相关产品推荐
相关产品推荐

