@@ -182,7 +182,7 @@ private void displayArea(DisplayArea area) {
182182 writeCommand (DPY_AREA_CMD , area .toByteArray ());
183183 }
184184
185- private byte [] pixelsFromImage (BufferedImage image , int x , int y , int w , int h ) {
185+ private static byte [] pixelsFromImage (BufferedImage image , int x , int y , int w , int h ) {
186186 var buffer = (DataBufferByte ) image .getRaster ().getDataBuffer ();
187187 var data = buffer .getData ();
188188 var stride = buffer .getSize () / image .getHeight ();
@@ -199,7 +199,7 @@ private byte[] pixelsFromImage(BufferedImage image, int x, int y, int w, int h)
199199 * @param width image width (in pixels)
200200 * @return initial errors
201201 */
202- private int [] createInitialDitheringErrors (int width ) {
202+ private static int [] createInitialDitheringErrors (int width ) {
203203 // initialize errors with random values in the range [-127, 128].
204204 int [] errors = new int [width + 2 ];
205205 var random = new Random ();
@@ -227,7 +227,7 @@ private int[] createInitialDitheringErrors(int width) {
227227 * @param errors errors carried forward from the previous band
228228 * @return errors to be carried forward to the next band
229229 */
230- private int [] dither (byte [] pixels , int stride , int [] errors ) {
230+ private static int [] dither (byte [] pixels , int stride , int [] errors ) {
231231 int [] currentErrors = errors ;
232232 int [] nextErrors = new int [errors .length ];
233233
@@ -244,12 +244,20 @@ private int[] dither(byte[] pixels, int stride, int[] errors) {
244244 return currentErrors ;
245245 }
246246
247- private void ditherRow (byte [] pixels , int offset , int [] currentErrors , int [] nextErrors ) {
247+ private static void ditherRow (byte [] pixels , int offset , int [] currentErrors , int [] nextErrors ) {
248248 int w = currentErrors .length - 2 ;
249249 for (int i = 0 ; i < w ; i += 1 ) {
250- int targetValue = (pixels [offset + i ] & 0xff ) + (currentErrors [i + 1 ] + 7 ) / 16 ;
251- int quantizedValue = targetValue < 0 ? 0 : (targetValue > 0xf0 ? 0xf0 : (targetValue + 7 ) & 0xf0 );
250+ // scale range from [0, 255] to [0, 240]
251+ int targetValue = (((pixels [offset + i ] & 0xff ) * 16 + currentErrors [i + 1 ]) * 15 + 127 ) / 255 ;
252+ int quantizedValue ;
253+ if (targetValue <= 0 )
254+ quantizedValue = 0 ;
255+ else if (targetValue >= 240 )
256+ quantizedValue = 240 ;
257+ else
258+ quantizedValue = (targetValue + 8 ) & 0xf0 ;
252259 pixels [offset + i ] = (byte ) quantizedValue ;
260+
253261 int quantizationError = targetValue - quantizedValue ;
254262 currentErrors [i + 2 ] += quantizationError * 7 ;
255263 nextErrors [i ] += quantizationError * 3 ;
0 commit comments