如何flock()图像?

I am looking to flock() an image.

Currently I am using the following

$img = ImageCreateFromPng($img_path);
flock($img,LOCK_EX);

It seems that the GD library's file handle is not valid with flock. How can I access the image and flock the file?

The function flock only works on file handles (or stream wrappers if they support locking). So, if you want to lock an image when you read it, you'd need to open it twice:

$f = fopen($imgPath, 'r');
if (!$f) {
    //Handle error (file does not exist perhaps, or no permissions?)
}
if (flock($f, LOCK_EX)) {
    $img = imagecreatefrompng($imgPath);
    //...  Do your stuff here

    flock($f, LOCK_UN);
}
fclose($f);

flock only works with file pointers and ImageCreateFromPng only works with filenames. Try making two different calls:

$fp = fopen($img_path, 'r');
flock($fp, LOCK_EX);
$img = ImageCreateFromPng($img_path);

flock is cooperative, so it only works if everybody uses it. As long as ImageCreateFromPng doesn't use flock, the code above should work.

$img in your example is not a file handle, it is a handle to a GD image resource in memory.

You can use imagecreatefromstring to load an image like this:

$file=fopen($fileName,"r+b");
flock($file,LOCK_EX);
$imageBinary=stream_get_contents($file);
$img=imagecreatefromstring($imageBinary);
unset($imageBinary); // we don't need this anymore - it saves a lot of memory

If you want to save a modified version of the image to the open stream you have to use output buffering:

ob_start();
imagepng($img);
$imageBinary=ob_get_clean();

ftruncate($file,0);
fseek($file,0);
fwrite($file,$imageBinary);
unset($imageBinary);
flock($file,LOCK_UN);
fclose($file);