0
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?

3
  • 1
    Check the PHP configuaration. you may not be able to open remote file to read with file_get_contents Commented Jul 12, 2011 at 17:30
  • Remove the header() line and the @s to get some meaningful error messages. Commented Jul 12, 2011 at 17:32
  • using @ is a bad habit. In your case both file_get_contents() and imagecreatefromstring() may fail and you will only notice it the way it currently is. Commented Jul 12, 2011 at 17:32

2 Answers 2

3

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).

Sign up to request clarification or add additional context in comments.

2 Comments

if OP's code isn't omitting resizing code, or similar, there's no reason to use imagecreatefrom*() or iamgejpeg() at all. Just file_get_contents($urlOfImage) and write the result to some local file.
Actually, OP's code will accept ANY kind of image and convert it to a jpeg, assuming it's a format that GD accepts.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.