Skip to content

Commit bf0d176

Browse files
committed
Maintain transparency while desaturating images
1 parent 43f291b commit bf0d176

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

build.gradle

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ plugins {
66
}
77

88
group = 'com.labelzoom.api'
9-
version = '1.2.0'
9+
version = '1.2.1'
1010

1111
java {
1212
sourceCompatibility = JavaVersion.VERSION_1_8

src/main/java/com/labelzoom/api/util/ImageUtils.java

+13-4
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ public class ImageUtils
1313
private static final float ERROR_SEVEN_SIXTEENTHS = 7f/16f;
1414
private static final int BLACK = Color.BLACK.getRGB();
1515
private static final int WHITE = Color.WHITE.getRGB();
16+
private static final int TRANSPARENT = new Color(0, 0, 0, 0).getRGB();
1617

1718
private ImageUtils() {}
1819

@@ -51,7 +52,15 @@ public static void desaturateWithDithering(final BufferedImage image, final floa
5152

5253
// Convert to grayscale (or use other method to choose between color1 and color2)
5354
final int gray = (int)(0.299 * red + 0.587 * green + 0.114 * blue);
54-
final int newPixel = gray <= luminanceByteThreshold && alpha >= alphaByteThreshold ? BLACK : WHITE;
55+
final int newPixel;
56+
if (alpha >= alphaByteThreshold)
57+
{
58+
newPixel = gray <= luminanceByteThreshold ? BLACK : WHITE;
59+
}
60+
else
61+
{
62+
newPixel = TRANSPARENT;
63+
}
5564

5665
final int error = gray - ((newPixel == BLACK) ? 0 : 255);
5766

@@ -92,13 +101,13 @@ public static void desaturateWithHardCut(final BufferedImage image, final float
92101
{
93102
final Color pixelColor = new Color(image.getRGB(x, y), true);
94103
final float luminance = HSLColor.fromRGB(pixelColor)[2];
95-
if (pixelColor.getAlpha() >= alphaByteThreshold && luminance <= luminanceByteThreshold)
104+
if (pixelColor.getAlpha() >= alphaByteThreshold)
96105
{
97-
image.setRGB(x, y, BLACK);
106+
image.setRGB(x, y, luminance <= luminanceByteThreshold ? BLACK : WHITE);
98107
}
99108
else
100109
{
101-
image.setRGB(x, y, WHITE);
110+
image.setRGB(x, y, TRANSPARENT);
102111
}
103112
}
104113
}

0 commit comments

Comments
 (0)