Skip to content

Instantly share code, notes, and snippets.

@matejdro
Created December 14, 2015 22:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matejdro/947c06cafe5c3a5657ef to your computer and use it in GitHub Desktop.
Save matejdro/947c06cafe5c3a5657ef to your computer and use it in GitHub Desktop.
public static void ditherToBlackWhite(LightBitmap bitmap)
{
double[][] separatedColorArray = new double[bitmap.getWidth()][bitmap.getHeight()];
for (int y = 0; y < bitmap.getHeight(); y++)
{
for (int x = 0; x < bitmap.getWidth(); x++)
{
separatedColorArray[x][y] = getGrayscaleColor(bitmap.getPixel(x, y));
}
}
for (int y = 0; y < bitmap.getHeight(); y++)
{
for (int x = 0; x < bitmap.getWidth(); x++)
{
double oldColor = separatedColorArray[x][y];
double newColor = getNearestBlackWhiteColor(oldColor);
bitmap.setPixel(x, y, Color.rgb((int) newColor, (int) newColor, (int) newColor));
double quantError = oldColor - newColor;
if (x < bitmap.getWidth() - 1)
separatedColorArray[x + 1][y] += quantError * 7.0 / 16;
if (y < bitmap.getHeight() - 1)
{
if (x > 0)
separatedColorArray[x - 1][y + 1] += quantError * 3.0 / 16.0;
separatedColorArray[x][y + 1] += quantError * 5.0 / 16.0;
if (x < bitmap.getWidth() - 1)
separatedColorArray[x + 1][y + 1] += quantError / 16.0;
}
}
}
}
public static double getGrayscaleColor(int rgbPixel)
{
return Math.round((Color.red(rgbPixel) + Color.green(rgbPixel) + Color.blue(rgbPixel)) / 3.0);
}
public static double getNearestBlackWhiteColor(double colorWithError)
{
return colorWithError > 255 / 2 ? 255 : 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment