title: Java ImageIO PNG Encoding Incorrectly?
body: <p>I've been trying to encode some data (represented as array of byte values 0-255) in a PNG image format with Java. The data is read out using HTML canvas element getImageData() method in JavaScript (similar to this: <a href="http://blog.nihilogic.dk/2008/05/compression-using-canvas-and-png.html" rel="nofollow">http://blog.nihilogic.dk/2008/05/compression-using-canvas-and-png.html</a>).</p>
  
  <p>However, the output data is not always identical to the input. Some of the values appear to differ from the input. It seems to work encoding as an image 1 pixel high, and is only incorrect for an image with multiple rows. I had the idea it could be caused by the line-by-line filtering for PNG images somehow but don't really know.</p>
  
  <p>It seems that each incorrect value is only ever wrong by 1 or 2.</p>
  
  <p>Here's the Java code but I'm wondering if it could also be an issue with the ImageIO api, in particular its PNG encoder?</p>
  
  <pre><code>public static File encodeInPng(byte[] data, String filename) throws java.io.IOException{
      int width = (int)Math.ceil(Math.sqrt(data.length));
      int height = (int)Math.ceil((double)data.length/width);
  
      BufferedImage bufImg = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
  
      int x = 0, y = 0;
      for (byte b : data) {
          bufImg.getRaster().setPixel(x, y, new int[]{b&amp;0xFF});
          x++;
          if (x == width) {
              x = 0;
              y ++;
          }
      }
  
      File f = new File(filename);
      ImageIO.write(bufImg, "png", f);
  
      return f;
  }
  </code></pre>
  
  <p><strong>Edit:</strong> The problem only appears for PNG files over a certain size (around 50 kB, or possibly 256x256px).</p>