Skip to content

Commit

Permalink
Added color → grayscale handling to Image.to*Array()
Browse files Browse the repository at this point in the history
  • Loading branch information
pcantrell committed Nov 2, 2024
1 parent 93eae52 commit 005f162
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/edu/macalester/graphics/Image.java
Original file line number Diff line number Diff line change
Expand Up @@ -391,9 +391,16 @@ private byte[] makeByteArray(BufferedImage buf) {
byte[] pixels = new byte[width * height * externalChans];
int i = 0;
for(int pix : rawData) {
for(int c = externalChans - 1; c >= 0; c--) {
pixels[i + c] = (byte) (pix & 0xFF);
pix >>= 8;
for(int c = 0; c < externalChans; c++) {
// Need to handle both color → grayscale and color → color:
// Average channels if internalChans > externalChans, and extract channels
// cyclically if internalChans < externalChans.
int sum = 0, count = 0;
for(int d = c; d < internalChans; d += externalChans) {
sum += (pix >> (8 * (internalChans - d - 1))) & 0xFF;
count++;
}
pixels[i + c] = (byte) (sum / count);
}
i += externalChans;
}
Expand Down
10 changes: 10 additions & 0 deletions test/edu/macalester/graphics/ImageTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,16 @@ private float[] generateFloatData(int w, int h, int chans) {
return pixels;
}

@RenderingTest(height=200, modes = { PLAIN })
void colorPixelConversionToGrayscaleArray() {
Image colorImage = new Image(FOXBOT_IMAGE);
image = new Image(
colorImage.getImageWidth(),
colorImage.getImageHeight(),
colorImage.toByteArray(Image.PixelFormat.GRAYSCALE),
Image.PixelFormat.GRAYSCALE);
}

@RenderingTest
void empty() {
image = new Image(1, 1);
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 005f162

Please sign in to comment.