#Java
#PicoPi
Image 2 black/white-Array
2 years ago
109
For one of my Pico Pi Projects, I needed to transform some images into a black/white-Array. I'm sure there are other tools or simpler ways to do this, but for such a simple task, it was easier to just do it in Java myself.
The code is pretty much straight forward:
- read the Image as a BufferedImage
- walk through the pixels
- and set the new black/white array accordingly
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String args[]){
try {
BufferedImage bufferedImage = ImageIO.read(new File(args[0]));
StringBuffer sb=new StringBuffer();
for(int i=0;i<bufferedImage.getHeight();i++) {
if(i==0) {
sb.append("[");
}
for (int j = 0; j < bufferedImage.getWidth(); j++) {
if(j==0) {
sb.append("[");
}
int c=bufferedImage.getRGB(j,i);
Color color = new Color(c,true);
if(color.getRed()==0){
sb.append(1);
}else{
sb.append(0);
}
if(j==bufferedImage.getWidth()-1){
sb.append("]");
}else{
sb.append(",");
}
}
if(i==bufferedImage.getHeight()-1){
sb.append("]");
}else{
sb.append(",\n");
}
}
System.out.println(sb.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}