ImagePaper.java
package libsidplay.components.printer.paper;
import libsidplay.components.printer.IPaper;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/** Thread-safe, opaque paper shared by the preview and PNG export. */
public final class ImagePaper implements IPaper {
private final List<boolean[]> rows = new ArrayList<>();
private boolean[] currentRow;
private int width, x;
public ImagePaper(int width) {
setWidth(width);
}
@Override
public synchronized void setWidth(int width) {
if (width <= 0) {
throw new IllegalArgumentException("Paper width must be positive");
}
this.width = Math.max(this.width, width);
currentRow = currentRow == null ? new boolean[this.width] : Arrays.copyOf(currentRow, this.width);
}
@Override
public synchronized void put(Outputs output) {
if (output == Outputs.OUTPUT_NEWLINE) {
rows.add(currentRow);
currentRow = new boolean[width];
x = 0;
} else {
if (x < width) {
currentRow[x] = output == Outputs.OUTPUT_PIXEL_BLACK;
}
x++;
}
}
public synchronized void clear(int width) {
rows.clear();
this.width = 0;
x = 0;
currentRow = null;
setWidth(width);
}
public synchronized BufferedImage getImage() {
int height = Math.max(1, rows.size() + (x == 0 ? 0 : 1));
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);
int[] pixels = new int[width];
for (int y = 0; y < height; y++) {
boolean[] row = y < rows.size() ? rows.get(y) : currentRow;
for (int column = 0; column < width; column++) {
pixels[column] = column < row.length && row[column] ? 0xff000000 : 0xffffffff;
}
image.setRGB(0, y, width, 1, pixels, 0, width);
}
return image;
}
public void writePng(File file) throws IOException {
if (!ImageIO.write(getImage(), "png", file)) {
throw new IOException("No PNG writer available");
}
}
}