Skip to content

Instantly share code, notes, and snippets.

@xicalango
Last active August 29, 2015 14:21
Show Gist options
  • Save xicalango/360c2e1d79d32332aeb2 to your computer and use it in GitHub Desktop.
Save xicalango/360c2e1d79d32332aeb2 to your computer and use it in GitHub Desktop.
A java (8) script that converts any image java can load into a Open Office Spreadsheet file. (you'll need the libs mentioned here: http://incubator.apache.org/odftoolkit/simple/gettingstartguide.html)
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Iterator;
import java.util.stream.IntStream;
import javax.imageio.ImageIO;
import org.odftoolkit.odfdom.type.Color;
import org.odftoolkit.simple.SpreadsheetDocument;
import org.odftoolkit.simple.table.Table;
public class Image2Spreadsheet {
private static final int BYTE_MASK = 0xFF;
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: Image2Spreadsheet source-image destination-spreadsheet");
}
final File source = new File(args[0]);
final File dest = new File(args[1]);
try {
SpreadsheetDocument doc = SpreadsheetDocument.newSpreadsheetDocument();
BufferedImage img = ImageIO.read(source);
generateImage(doc, img);
doc.save(dest);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void generateImage(SpreadsheetDocument doc, BufferedImage img) {
final int width = img.getWidth();
final int height = img.getHeight();
final Iterator<Color> sourceColors = IntStream.of(img.getRGB(0, 0, width, height, null, 0, width))//
.mapToObj(Image2Spreadsheet::rgbToColor)//
.iterator();
final Table table = doc.addTable(height, width + 1); // with 1 pixel border
table.setTableName("Image");
doc.removeSheet(0);
table.getColumnList().forEach(c -> c.setWidth(5));
table.getRowList().forEach(h -> h.setHeight(5, false));
for (int y = 0; y < height; y++) {
if (y % Math.max(1, (height / 100)) == 0) {
System.out.println("Line " + (y + 1) + " / " + height + " " + ((y + 1) * 100) / height + " %");
}
for (int x = 0; x < width; x++) {
// happy garbage collecting
table.getCellByPosition(x, y).setCellBackgroundColor(sourceColors.next());
}
}
if ((height - 1) % Math.max(1, (height / 100)) != 0) {
System.out.println("Line " + height + " / " + height + " 100 %");
}
}
private static Color rgbToColor(int rgb) {
return new Color((rgb >> 16) & BYTE_MASK, (rgb >> 8) & BYTE_MASK, (rgb >> 0) & BYTE_MASK);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment