开发者

Converting an image from a url to a true image to be saved on a server. (PHP)

开发者 https://www.devze.com 2023-03-20 06:24 出处:网络
header(\'Content-Type: image/jpeg\'); $imageURL = $_POST[\'url\']; $image = @ImageCreateFromString(@file_get_contents($imageURL));
header('Content-Type: image/jpeg');
$imageURL = $_POST['url'];
$image = @ImageCreateFromString(@file_get_contents($imageURL));

if (is_resource($image) === true)开发者_如何学运维
    imagejpeg($image, 'NameYouWantGoesHere.jpg');

else
    echo "This image ain't quite cuttin it.";

This is the code I have to convert a url that I receive from an html form into an image. However, whenever I try to display it or take it off the server to look at it, it 'cannot be read' or is 'corrupted'. So for some reason it is converted to an image, recognized as a proper resource, but is not proper image at that point. Any ideas?


You don't want ImageCreateFromString - using file_get_contents is getting you the actual binary data for the image.

Try $image = @imagecreatefromjpeg(@file_get_contents($imageURL)); and see if you like the results better (assuming the original is a JPEG).


You can use cURL to open remote file:

   $ch = curl_init();
   // set the url to fetch
   curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/img.jpg');
   // don't give me the headers just the content
   curl_setopt($ch, CURLOPT_HEADER, 0);

   // return the value instead of printing the response to browser
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

   // use a user agent to mimic a browser
   curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0');

   $content = curl_exec($ch);
   // remember to always close the session and free all resources
   curl_close($ch); 
0

精彩评论

暂无评论...
验证码 换一张
取 消