php get image size from a string of image content - php

I have a function that would fetch a remote image via CURL, returning a string variable of the contents of the remote image.
I do not wish to write the content into the file, but wish to get the size of the image.
since getimagesize() only supports a file, is there a function similar to getimagesize() but can support strings of image content?
to clarify:
$image_content = file_get_contents('http://www.example.com/example.jpg');
how to get the image size of $image_content instead of running getimagesize('http://www.example.com/example.jpg');?
Thanks in advance

PHP functions imagecreatefromstring, imagesx, and imagesy.
Something like this;
$image_content = file_get_contents('http://www.example.com/example.jpg');
$image = imagecreatefromstring($image_content);
$width = imagesx($image);
$height = imagesy($image);

FYI, for those coming late to the game, PHP >= 5.4 now includes getimagesizefromstring() which is identical to getimagesize() but accepts a string for the first param instead of a location.
http://php.net/manual/en/function.getimagesizefromstring.php

OK, I found answer for PHP 5.3 and less
if (!function_exists('getimagesizefromstring')) {
function getimagesizefromstring($data)
{
$uri = 'data://application/octet-stream;base64,' . base64_encode($data);
return getimagesize($uri);
}
}

Related

Retrieve Image Resolution(DPI) of an image (JPEG,PNG,SVG,GIF) without using any PHP extension

I want to Retrieve Image Resolution(DPI) of an image (JPEG,PNG,SVG,GIF) without using any PHP extension (like imageMagick). I searched everywhere, but I couldn't find a perfect solution. I tried below code (got from link)
function get_dpi($filename){
$a = fopen($filename,'r');
$string = fread($a,20);
fclose($a);
$data = bin2hex(substr($string,14,4));
$x = substr($data,0,4);
$y = substr($data,0,4);
return array(hexdec($x),hexdec($y));
}
But I am not getting the correct Horizontal and vertical DPI. For example, I used an image with 96dpi and 96dpi, but I got (100,100).And this function is only for JPEG file formats.
The DPI of an image is usually a matter of fiction. Rarely is an image created where the physical dimensions of the final rendering actually matter (as far as the image itself is concerned). That said, the DPI information is stored in the EXIF data of a JPEG so you can read it from there with the built-in PHP function:
<?php
$filename = "/Users/quentin/Dropbox/Camera Uploads/2016-03-30 21.01.09.jpg";
$exif = exif_read_data($filename);
?>
DPI is <?php echo $exif["XResolution"] ?> by <?php echo $exif["YResolution"] ?>

How can I retrieve and save images with non-standard basenames using PHP

Short version
When I try to run file_get_contents() with this link, 'http://s1.reutersmedia.net/resources/r/?m=02&d=20131205&t=2&i=817503382&w=&fh=&fw=&ll=700&pl=378&r=CBRE9B401AG00', it returns: "illegal: d - msg". Why is it that file_get_contents() works on most image link but not this one, and how can I make it work?
Details
Part of my webapp's functionality is to parse external html files for images, then allow the user to select a desired image, and automatically save a reduced-size version of the image to my server. My code works for 99% of cases, but for the remaining 1% I am unable to successfully get the image file onto my server in order to re-size it. The cases that don't work seem to all involve html elements with 'src' attributes that look like this:
http://s1.reutersmedia.net/resources/r/?m=02&d=20131205&t=2&i=817503382&w=&fh=&fw=&ll=580&pl=378&r=CBRE9B401AG00
as opposed to a more standard image path such as this:
http://www.wired.com/images_blogs/wiredscience/2013/12/keyes-wd.jpg
Below is the code that I use in order to get and save the external image once the user has selected it, where the variable $newFileName is equal to an img path string such as the ones pasted above:
$contentOrFalseOnFailure = file_get_contents($newFileName);
$byteCountOrFalseOnFailure = file_put_contents($filenameOut, $contentOrFalseOnFailure);
$fileName = basename($newFileName);
$fileTmpLoc = $filenameOut;
$fileSize = $byteCountOrFalseOnFailure;
$fileExt = pathinfo($fileTmpLoc, PATHINFO_EXTENSION);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
header("location: ../message.php?msg=ERROR: That image has no dimensions");
exit();
}
When the src is non-standard, the script doesn't make it beyond this point, ie i get the "That image has no dimestions" error. What can I do to save save these non-standard images?
If you're interested in JUST the image dimensions and nothing else about it, you could go with GD's imagecreatefromstring() without needing a temp on-disk file:
$img = file_get_contents($url);
$gd = imagecreatefromstring($img);
$width = imagesx($gd);
$height = imagesy($gd);
This has the downside of having to decompress the image into memory, however. You'd have to hope that the remote server doesn't sent over a ludicriously dimensioned image that doesn't exceed the PHP memory_limit upon decompression.
Ignore the URL, look at the Content-Type header in the response.

How to get size from swf file?

I have dynamic pages with swf file inside 'object' tag, but swf files have not identical size.
So for more crossbrowsing method i need to set size attributes for 'object'....here is the problem: i don`t know how to get size from swf and transmit it to php. Please help!
$media = "media.swf";
$dem = getimagesize($media);
$height = $dem[1];
$width = $dem[0];
PHP's getimagesize() documentation.

Generate image with Drupal imagecache before using imagecache_create_path & getimagesize

I'm using imagecache_create_path() and getimagesize() to get the path of a imagecache-generated image and its dimensions. However, if it's the first time we access the page that image doesn't exist yet and imagecache_create_path doesn't generate it either.
Here's the code:
// we get the image path from a preset (always return the path even if the file doesn't exist)
$small_image_path = imagecache_create_path('gallery_image_small', $image["filepath"]);
// I get the image dimensions (only if the file exists already)
$data_small = list($width, $height, $type, $image_attributes) = #getimagesize($small_image_path);
Is there any API method to get the path AND generate the file? In other words, can I generate the image (using a preset) from PHP without showing it in the browser?
Thank you in advance
Check the imagecache_build_derivative() function and its usage in imagecache.module. For your case, it should work roughly like so:
$presetname = 'gallery_image_small';
$preset = imagecache_preset_by_name($presetname);
$src = $image["filepath"];
$dst = imagecache_create_path($presetname, $src);
// Ensure existing derivative or try to create it on the fly
if (file_exists($dst) || imagecache_build_derivative($preset['actions'], $src, $dst)) {
// Do what you need to do with the image
}
(NOTE: untested code, beware of typos and other errors/oversights)

ImageCreateFromString and getimagesize in PHP

Currently if a user POST/uploads a photo to my PHP script I start out with some code like this
getimagesize($_FILES['picture1']['tmp_name']);
I then do a LOT more stuff to it but I am trying to also be able to get a photo from a URL and process it with my other existing code if I can. SO I am wanting to know, I f I use something like this
$image = ImageCreateFromString(file_get_contents($url));
Would I be able to then run getimagesize() on my $image variable?
UPDATE
I just tried this...
$url = 'http://a0.twimg.com/a/1262802780/images/twitter_logo_header.png';
$image = imagecreatefromstring(file_get_contents($url));
$imageinfo = getimagesize($image);
print_r($imageinfo);
But it didnt work, gave this.
Warning: getimagesize(Resource id #4) [function.getimagesize]: failed to open stream: No such file or directory in
Any idea how I can do this or something similar to get the result I am after?
I suggest you follow this approach:
// if you need the image type
$type = exif_imagetype($url);
// if you need the image mime type
$type = image_type_to_mime_type(exif_imagetype($url));
// if you need the image extension associated with the mime type
$type = image_type_to_extension(exif_imagetype($url));
// if you don't care about the image type ignore all the above code
$image = ImageCreateFromString(file_get_contents($url));
echo ImageSX($image); // width
echo ImageSY($image); // height
Using exif_imagetype() is a lot faster than getimagesize(), the same goes for ImageSX() / ImageSY(), plus they don't return arrays and can also return the correct image dimension after the image has been resized or cropped for instance.
Also, using getimagesize() on URLs isn't good because it'll consume much more bandwidth than the alternative exif_imagetype(), from the PHP Manual:
When a correct signature is found, the
appropriate constant value will be
returned otherwise the return value is
FALSE. The return value is the same
value that getimagesize() returns in
index 2 but exif_imagetype() is much
faster.
That's because exif_imagetype() will only read the first few bytes of data.
If you've already got an image resource, you'd get the size using the imagesx and imagesy functions.
getimagesize can be used with HTTP.
Filename - It can reference a local file or (configuration permitting) a remote file using one of the supported streams.
Thus
$info = getimagesize($url);
$image = ImageCreateFromString(file_get_contents($url));
should be fine.
Not sure if this will help, but I ran into a similar issue and it turned out the firewall controlled by my host was blocking outgoing http connection from my server.
They changed the firewall settings. My code then worked.
BTW: I thought this might have been an issue when I tried file_get_contents() on a number of urls, none of which worked!

Categories