Factor out boolean[][] -> BitMatrix parsing

This commit is contained in:
Sean Owen 2017-01-06 13:29:10 +00:00
parent cdf4fe51c5
commit f5b5c3a97e
No known key found for this signature in database
GPG key ID: F6CE9695C9318406
3 changed files with 34 additions and 23 deletions

View file

@ -40,11 +40,21 @@ public final class BitMatrix implements Cloneable {
private final int rowSize;
private final int[] bits;
// A helper to construct a square matrix.
/**
* Creates an empty square {@link BitMatrix}.
*
* @param dimension height and width
*/
public BitMatrix(int dimension) {
this(dimension, dimension);
}
/**
* Creates an empty {@link BitMatrix}.
*
* @param width bit matrix width
* @param height bit matrix height
*/
public BitMatrix(int width, int height) {
if (width < 1 || height < 1) {
throw new IllegalArgumentException("Both dimensions must be greater than 0");
@ -62,6 +72,27 @@ public final class BitMatrix implements Cloneable {
this.bits = bits;
}
/**
* Interprets a 2D array of booleans as a {@link BitMatrix}, where "true" means an "on" bit.
*
* @param image bits of the image, as a row-major 2D array. Elements are arrays representing rows
* @return {@link BitMatrix} representation of image
*/
public static BitMatrix parse(boolean[][] image) {
int height = image.length;
int width = image[0].length;
BitMatrix bits = new BitMatrix(width, height);
for (int i = 0; i < height; i++) {
boolean[] imageI = image[i];
for (int j = 0; j < width; j++) {
if (imageI[j]) {
bits.set(j, i);
}
}
}
return bits;
}
public static BitMatrix parse(String stringRepresentation, String setString, String unsetString) {
if (stringRepresentation == null) {
throw new IllegalArgumentException();

View file

@ -48,17 +48,7 @@ public final class Decoder {
* @throws ChecksumException if error correction fails
*/
public DecoderResult decode(boolean[][] image) throws FormatException, ChecksumException {
int dimension = image.length;
BitMatrix bits = new BitMatrix(dimension);
for (int i = 0; i < dimension; i++) {
boolean[] imageI = image[i];
for (int j = 0; j < dimension; j++) {
if (imageI[j]) {
bits.set(j, i);
}
}
}
return decode(bits);
return decode(BitMatrix.parse(image));
}
/**

View file

@ -57,17 +57,7 @@ public final class Decoder {
*/
public DecoderResult decode(boolean[][] image, Map<DecodeHintType,?> hints)
throws ChecksumException, FormatException {
int dimension = image.length;
BitMatrix bits = new BitMatrix(dimension);
for (int i = 0; i < dimension; i++) {
boolean[] imageI = image[i];
for (int j = 0; j < dimension; j++) {
if (imageI[j]) {
bits.set(j, i);
}
}
}
return decode(bits, hints);
return decode(BitMatrix.parse(image), hints);
}
public DecoderResult decode(BitMatrix bits) throws ChecksumException, FormatException {