-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImageProcessing.java
More file actions
407 lines (344 loc) · 15.2 KB
/
Copy pathImageProcessing.java
File metadata and controls
407 lines (344 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.Random;
import javax.imageio.ImageIO;
/**
* ImageProcessing
*
* A collection of image manipulation and pixel-painting utilities.
* Supports loading images from local files or URLs, applying visual filters,
* and generating procedural artwork using 2D pixel arrays.
*
* Developed as part of a Codecademy Java project.
*/
public class ImageProcessing {
public static void main(String[] args) {
// Load image from local file (options: apple.jpg, flower.jpg, kitten.jpg)
int[][] imageData = imgToTwoD("./apple.jpg");
// Or load from a URL:
// int[][] imageData = imgToTwoD("https://content.codecademy.com/projects/project_thumbnails/phaser/bug-dodger.png");
// Uncomment to inspect raw pixel values from the top-left corner
// viewImageData(imageData);
// --- Image Filters ---
int[][] negativeImg = negativeColor(imageData);
twoDToImage(negativeImg, "./negative_apple.jpg");
int[][] trimmed = trimBorders(imageData, 50);
twoDToImage(trimmed, "./trimmed_apple.jpg");
int[][] stretchedHImg = stretchHorizontally(imageData);
twoDToImage(stretchedHImg, "./strh_apple.jpg");
// int[][] shrinkedVImg = shrinkVertically(imageData);
// twoDToImage(shrinkedVImg, "./srkv_apple.jpg");
int[][] invertedImg = invertImage(imageData);
twoDToImage(invertedImg, "./iv_apple.jpg");
int[][] colorFilteredImg = colorFilter(imageData, -75, 65, 78);
twoDToImage(colorFilteredImg, "./cf_apple.jpg");
// Example of chaining multiple filters together:
// int[][] allFilters = stretchHorizontally(shrinkVertically(colorFilter(negativeColor(trimBorders(invertImage(imageData), 50)), 200, 20, 40)));
// --- Procedural Painting ---
int[][] blankCanvas = new int[500][500];
int[][] randomImg = paintRandomImage(blankCanvas);
twoDToImage(randomImg, "./random_img.jpg");
// Paint a single yellow rectangle at row 200, col 100, sized 150x300
int[] rgba = {255, 255, 0, 255};
int[][] rectangleImg = paintRectangle(blankCanvas, 150, 300, 200, 100, getColorIntValFromRGBA(rgba));
twoDToImage(rectangleImg, "./paint_rect.jpg");
// Generate 1000 random rectangles for procedural art
int[][] rectangleArtImg = generateRectangles(blankCanvas, 1000);
twoDToImage(rectangleArtImg, "./rect_art.jpg");
}
// =========================================================================
// IMAGE PROCESSING METHODS
// =========================================================================
/**
* Removes a border of the given pixel thickness from all four sides of the image.
*
* @param imageTwoD the source image as a 2D pixel array
* @param pixelCount number of pixels to remove from each edge
* @return trimmed image, or the original if it's too small to trim
*/
public static int[][] trimBorders(int[][] imageTwoD, int pixelCount) {
if (imageTwoD.length > pixelCount * 2 && imageTwoD[0].length > pixelCount * 2) {
int[][] trimmedImg = new int[imageTwoD.length - pixelCount * 2][imageTwoD[0].length - pixelCount * 2];
for (int i = 0; i < trimmedImg.length; i++) {
for (int j = 0; j < trimmedImg[i].length; j++) {
trimmedImg[i][j] = imageTwoD[i + pixelCount][j + pixelCount];
}
}
return trimmedImg;
} else {
System.out.println("Cannot trim that many pixels from the given image.");
return imageTwoD;
}
}
/**
* Inverts all RGB channels of each pixel, producing a negative of the image.
* Alpha channel is preserved.
*
* @param imageTwoD the source image as a 2D pixel array
* @return new image with negated colors
*/
public static int[][] negativeColor(int[][] imageTwoD) {
int[][] negImage = new int[imageTwoD.length][imageTwoD[0].length];
for (int i = 0; i < imageTwoD.length; i++) {
for (int j = 0; j < imageTwoD[0].length; j++) {
int[] rgba = getRGBAFromPixel(imageTwoD[i][j]);
rgba[0] = 255 - rgba[0];
rgba[1] = 255 - rgba[1];
rgba[2] = 255 - rgba[2];
negImage[i][j] = getColorIntValFromRGBA(rgba);
}
}
return negImage;
}
/**
* Doubles the image width by duplicating each pixel horizontally.
*
* @param imageTwoD the source image as a 2D pixel array
* @return new image stretched to 2x its original width
*/
public static int[][] stretchHorizontally(int[][] imageTwoD) {
int[][] stretchedHImg = new int[imageTwoD.length][imageTwoD[0].length * 2];
for (int i = 0; i < imageTwoD.length; i++) {
for (int j = 0; j < imageTwoD[0].length; j++) {
int col = j * 2;
stretchedHImg[i][col] = imageTwoD[i][j];
stretchedHImg[i][col + 1] = imageTwoD[i][j];
}
}
return stretchedHImg;
}
/**
* Halves the image height by sampling every other row.
*
* @param imageTwoD the source image as a 2D pixel array
* @return new image shrunk to half its original height
*/
public static int[][] shrinkVertically(int[][] imageTwoD) {
int[][] shrinkedVImg = new int[imageTwoD.length / 2][imageTwoD[0].length];
for (int i = 0; i < imageTwoD[0].length; i++) {
for (int j = 0; j < imageTwoD.length; j += 2) {
shrinkedVImg[j / 2][i] = imageTwoD[j][i];
}
}
return shrinkedVImg;
}
/**
* Flips the image both vertically and horizontally (180° rotation).
*
* @param imageTwoD the source image as a 2D pixel array
* @return new image rotated 180 degrees
*/
public static int[][] invertImage(int[][] imageTwoD) {
int[][] invImage = new int[imageTwoD.length][imageTwoD[0].length];
for (int i = 0; i < imageTwoD.length; i++) {
for (int j = 0; j < imageTwoD[0].length; j++) {
invImage[i][j] = imageTwoD[(imageTwoD.length - 1) - i][(imageTwoD[i].length - 1) - j];
}
}
return invImage;
}
/**
* Applies an additive color shift to each pixel's RGB channels.
* Values are clamped to the [0, 255] range.
*
* @param imageTwoD the source image as a 2D pixel array
* @param redChangeValue amount to add to the red channel
* @param greenChangeValue amount to add to the green channel
* @param blueChangeValue amount to add to the blue channel
* @return new image with the color filter applied
*/
public static int[][] colorFilter(int[][] imageTwoD, int redChangeValue, int greenChangeValue, int blueChangeValue) {
int[][] coloredImage = new int[imageTwoD.length][imageTwoD[0].length];
for (int i = 0; i < imageTwoD.length; i++) {
for (int j = 0; j < imageTwoD[0].length; j++) {
int[] rgba = getRGBAFromPixel(imageTwoD[i][j]);
rgba[0] = Math.clamp(rgba[0] + redChangeValue, 0, 255);
rgba[1] = Math.clamp(rgba[1] + greenChangeValue, 0, 255);
rgba[2] = Math.clamp(rgba[2] + blueChangeValue, 0, 255);
coloredImage[i][j] = getColorIntValFromRGBA(rgba);
}
}
return coloredImage;
}
// =========================================================================
// PAINTING METHODS
// =========================================================================
/**
* Fills every pixel of the canvas with a random opaque color.
*
* @param canvas the target canvas as a 2D pixel array
* @return canvas filled with random colors
*/
public static int[][] paintRandomImage(int[][] canvas) {
Random rand = new Random();
for (int i = 0; i < canvas.length; i++) {
for (int j = 0; j < canvas[0].length; j++) {
int[] rgba = {rand.nextInt(256), rand.nextInt(256), rand.nextInt(256), 255};
canvas[i][j] = getColorIntValFromRGBA(rgba);
}
}
return canvas;
}
/**
* Paints a filled rectangle onto the canvas using the specified color.
*
* @param canvas the target canvas as a 2D pixel array
* @param width width of the rectangle in pixels
* @param height height of the rectangle in pixels
* @param rowPosition starting row (top edge) of the rectangle
* @param colPosition starting column (left edge) of the rectangle
* @param color packed ARGB color integer for the fill
* @return canvas with the rectangle painted on it
*/
public static int[][] paintRectangle(int[][] canvas, int width, int height, int rowPosition, int colPosition, int color) {
for (int i = 0; i < canvas.length; i++) {
for (int j = 0; j < canvas[0].length; j++) {
if (i >= rowPosition && i <= rowPosition + width) {
if (j >= colPosition && j <= colPosition + height) {
canvas[i][j] = color;
}
}
}
}
return canvas;
}
/**
* Generates a given number of randomly sized and colored rectangles,
* anchored to random positions along the canvas edges.
*
* @param canvas the target canvas as a 2D pixel array
* @param numRectangles number of rectangles to generate
* @return canvas with all rectangles painted on it
*/
public static int[][] generateRectangles(int[][] canvas, int numRectangles) {
Random rand = new Random();
for (int i = 0; i < numRectangles; i++) {
int randomHeight = rand.nextInt(canvas.length);
int randomWidth = rand.nextInt(canvas[0].length);
// Position rectangles so they fit within canvas bounds
int randomRowPosition = canvas.length - randomHeight;
int randomColumnPosition = canvas[0].length - randomWidth;
int[] rgba = {rand.nextInt(256), rand.nextInt(256), rand.nextInt(256), 255};
int randomColor = getColorIntValFromRGBA(rgba);
canvas = paintRectangle(canvas, randomWidth, randomHeight, randomRowPosition, randomColumnPosition, randomColor);
}
return canvas;
}
// =========================================================================
// UTILITY METHODS
// =========================================================================
/**
* Loads an image from a local file path or a public URL
* and returns it as a 2D array of packed ARGB pixel integers.
*
* @param inputFileOrLink local file path or HTTP/HTTPS URL
* @return 2D pixel array, or null if loading fails
*/
public static int[][] imgToTwoD(String inputFileOrLink) {
try {
BufferedImage image = null;
if (inputFileOrLink.substring(0, 4).toLowerCase().equals("http")) {
URL imageUrl = new URL(inputFileOrLink);
image = ImageIO.read(imageUrl);
if (image == null) {
System.out.println("Failed to get image from provided URL.");
}
} else {
image = ImageIO.read(new File(inputFileOrLink));
}
int imgRows = image.getHeight();
int imgCols = image.getWidth();
int[][] pixelData = new int[imgRows][imgCols];
for (int i = 0; i < imgRows; i++) {
for (int j = 0; j < imgCols; j++) {
pixelData[i][j] = image.getRGB(j, i);
}
}
return pixelData;
} catch (Exception e) {
System.out.println("Failed to load image: " + e.getLocalizedMessage());
return null;
}
}
/**
* Writes a 2D pixel array to a JPEG file at the given path.
*
* @param imgData source pixel data as a 2D array
* @param fileName output file path (e.g. "./output.jpg")
*/
public static void twoDToImage(int[][] imgData, String fileName) {
try {
int imgRows = imgData.length;
int imgCols = imgData[0].length;
BufferedImage result = new BufferedImage(imgCols, imgRows, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < imgRows; i++) {
for (int j = 0; j < imgCols; j++) {
result.setRGB(j, i, imgData[i][j]);
}
}
File output = new File(fileName);
ImageIO.write(result, "jpg", output);
} catch (Exception e) {
System.out.println("Failed to save image: " + e.getLocalizedMessage());
}
}
/**
* Extracts the RGBA components from a packed pixel integer.
*
* @param pixelColorValue packed ARGB integer
* @return int array of [red, green, blue, alpha], each in range [0, 255]
*/
public static int[] getRGBAFromPixel(int pixelColorValue) {
Color pixelColor = new Color(pixelColorValue);
return new int[] {pixelColor.getRed(), pixelColor.getGreen(), pixelColor.getBlue(), pixelColor.getAlpha()};
}
/**
* Packs an RGBA array into a single integer color value.
*
* @param colorData int array of [red, green, blue, alpha]
* @return packed ARGB integer, or -1 if the array length is invalid
*/
public static int getColorIntValFromRGBA(int[] colorData) {
if (colorData.length == 4) {
Color color = new Color(colorData[0], colorData[1], colorData[2], colorData[3]);
return color.getRGB();
} else {
System.out.println("Incorrect number of elements in RGBA array.");
return -1;
}
}
/**
* Prints the raw and RGBA-extracted pixel values of the top-left 3x3 region.
* Useful for inspecting image data during development.
*
* @param imageTwoD the image to inspect
*/
public static void viewImageData(int[][] imageTwoD) {
if (imageTwoD.length > 3 && imageTwoD[0].length > 3) {
int[][] rawPixels = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
rawPixels[i][j] = imageTwoD[i][j];
}
}
System.out.println("Raw pixel data from the top left corner.");
System.out.print(Arrays.deepToString(rawPixels).replace("],", "],\n") + "\n");
int[][][] rgbPixels = new int[3][3][4];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
rgbPixels[i][j] = getRGBAFromPixel(imageTwoD[i][j]);
}
}
System.out.println();
System.out.println("Extracted RGBA pixel data from the top left corner.");
for (int[][] row : rgbPixels) {
System.out.print(Arrays.deepToString(row) + System.lineSeparator());
}
} else {
System.out.println("The image is not large enough to extract 9 pixels from the top left corner");
}
}
}