aaro4130
aaro4130

Reputation: 115

PHP fopen not getting whole file

I'm trying to read a 3MB file in PHP. I use fopen to get the handle, and fread to read it. But when I call fread after reading ~1/2 the file, it stops reading, and my unpack function throws an error saying it got 0 bytes. Any ideas?

This is my binary reading function:

function binaryReadUShort($f){
      return unpack("S",fread($f,4))[1];
      }

And this is the code for reading the heightmap. $fh is the file handle.

  for($y = 0; $y < $size; $y++){
      for($x = 0; $x < $size; $x++){
        $height = binaryReadUShort($fh);
        $height = $height / 65535;
        $height = $height * 255;

        $color_alloc = imagecolorallocate($img,$height,$height,$height);
        imagesetpixel($img,$x,$y,$color_alloc);
      }
  }

Also, filesize() returns the correct amount of bytes in the file, and I did a test, in which I counted the bytes I was reading. I confirmed I am NOT attempting to read past the end of the file.

Upvotes: 3

Views: 505

Answers (1)

VolkerK
VolkerK

Reputation: 96189

Without further information I think the best guess is that you want to read 2-byte unsigned shorts ->

fread($f,2)

Upvotes: 1

Related Questions