Search code examples
javacsvpixelfilewriterprintwriter

Image Pixel Data Reading and Printing


Boo Hoo. I had this awesome code that output-ed the data of all the pixels of an image into a csv/txt file. And now it is not showing anything in the files. The file comes up completely blank. What am I missing guys?

import java.awt.Component;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.util.Scanner;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;

public class JavaWalkBufferedImageTest1 extends Component {

  public static void main(String[] foo) {
  File outFile = new File ("finall.txt");
    try{
  FileWriter fWriter = new FileWriter (outFile, true);
    PrintWriter pWriter = new PrintWriter (fWriter);
    new JavaWalkBufferedImageTest1(pWriter);
   pWriter.close();
} catch(Exception e){       }
  }

  public void printPixelARGB(int pixel, PrintWriter pW4) {
    int red = (pixel >> 16) & 0xff;
    int green = (pixel >> 8) & 0xff;
    int blue = (pixel) & 0xff;
    pW4.print(red + ", " + green + ", " + blue);
  }

  private void marchThroughImage(BufferedImage image, PrintWriter pW3) {
    int w = image.getWidth();
    int h = image.getHeight();

    for (int i = h; i < h; i++) {
      for (int j = w; j < w; j++) {
    pW3.print( j + ", " + i + ", ");               //X,Y
    int pixel = image.getRGB(j, i);
    printPixelARGB(pixel, pW3); //red,green,blue
    pW3.println("");      
      }
    }
  }

  public JavaWalkBufferedImageTest1(PrintWriter pW2) {
    try {
      BufferedImage image = ImageIO.read(this.getClass().getResource("color.jpg"));
      marchThroughImage(image, pW2);
    } catch (IOException e) {
      System.err.println(e.getMessage());
    }
  }
}

Solution

  • Take a closer look at the for loops in marchThroughImage() :) You're starting with i equal to h, and asking it to stop when i is >= h. So no iterations actually occur. Same thing with j.

    Start them from 0, and you should get some output.