Extracting external image and saving locally results in image distortion

Stuck on this. I have this function below that just takes $ImageSrc

which is an external image from anywhere like imgur and then saves it locally (this is not a scraper, I let people attach images to their profiles)

public function UploadScreenshot($ImageSrc, $Title, $Description = false) {
    $RandomName = substr(md5($Title . time()), 0, 20);
    $UploadDir = "/home/vanrust/public_html/Screenshots/";

    $file = pathinfo($ImageSrc);
    $ext = $file["extension"];
    if (!in_array($ext, array('jpg','png','bmp','jpeg'))) return array("error" => "Invalid File Type");

    $RandomName = "{$RandomName}.{$ext}";
    $image = file_get_contents($ImageSrc);
    file_put_contents($UploadDir . $RandomName, $image);
}

      

The result of the file is no matter what is unrecognizable.

Picture:

enter image description here

After UploadScreenshot () got it:

The result of the above script regardless of image url

+3


source to share


1 answer


Try using rename () to move the original file to a new location and rename it.

$file = pathinfo($ImageSrc);
$ext = $file["extension"];
if (!in_array($ext, array('jpg','png','bmp','jpeg'))) return array("error" => "Invalid File Type");

$RandomName = "{$RandomName}.{$ext}";
rename($UploadDir . $RandomName, $ImageSrc);

      

}



Alternatively, you can use move_uploaded_file () if your $ ImageSrc file does indeed contain a valid upload file (meaning it was uploaded via the PHP HTTP POST upload mechanism).

file_put_contents () must be used with care. One offset (in binary) at the beginning or end of the file will significantly change the image. This requires a check at the end to compare both bytes of the files.

0


source







All Articles