How to put () an image?

I am looking for flock () image.

I am currently using the following

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

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

+3
source share
3 answers

The flockfunction only works with files (or stream wrappers , if they support locking). So, if you want to block the image while reading it, you will 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);
+1
source

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

You can use imagecreatefromstring to load an image as follows:

$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

, :

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);
+1

flockonly works with file pointers, but ImageCreateFromPngonly works with file names. Try to make two different calls:

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

flockis cooperative, so it only works if everyone uses it. While ImageCreateFromPngnot using flock, the code should work.

0
source

Source: https://habr.com/ru/post/1750113/


All Articles