Rectangle 27 1

imagecreatefromstring
imagesx

Thanks, this worked perfectly. I think when I initially saw imagesx I assumed it had to do with x-pos and not dimensions.

PHP - get blob image size - FPDF - getimagesizefromstring doesn't work...

php image blob fpdf getimagesize
Rectangle 27 0

There seems to be no way around this than to resize the image container when the image inside can't be centered pixel-perfect, to have consistent cross-browser behaviour on the positioning. Therefore I need to fetch the image meta-data either server-side or client-side.

Server-side (1): Using getimagesize and getimagesizefromstring and was obviously the way to go. But then I bumped into a problem in my current use-case: the tree is rendered using AJAX, and the relative URL for the image is not relative to the location of the AJAX script.

Issues: So, for this to work I either have to pass both URL and absolute PATH (or absolute path alone, and have the URL figured out by stripping $_SERVER['DOCUMENT_ROOT'] from it). This approach seems counter-intuitive and restrictive on the developer's part trying to implement this tree module. So I abandoned this idea.

Server-side (2): Ask for the image dimensions at design time. Plain and simple, place the responsibility at the implementer.

Issues: Not very elegant, but it works :). (solution 1)

Client-side: I've but both images inside a hidden DIV, and I fetch the size of the image from the onload event. If by this data the images used inside the containers appear off-center ( image.width%2 != container.width%2 , image.height%2 != container.height%2 ), I loop through these containers and resize them by one pixel in either width or height.

Issues: I don't like the idea of using hidden elements with triggers for the sole purpose of working around this positioning problem. However, it provides a solid cross-browser solution. The only downside is that there seems to be a slight delay before the images 'snap in position' (at least in FireFox). The obvious solution for this is to have the containers show the images after resizing the container. (solution 2)

Thanks for posting a solution to this difficult problem:) I tried several other CSS centering methods using display:table, display:inline-block, floating, and absolute positioning, and the 1px drift was still there, or it borked in IE9 or under.

html - CSS image centering within centered container gives unpredictab...

html css centering
Rectangle 27 0

You could use getimagesizefromstring() If you have a newer php version.

But since you are decoding you could use this as well.

$uri = 'data://application/octet-stream;base64,' . base64_encode($data);
    getimagesize($uri);

php - File size of a PNG image created with data URL? - Stack Overflow

php png filesize
Rectangle 27 0

getimagesizefromstring()

getimagesizefromstring is a PHP5.4 function. What about php5.3?

php - Extract Image Dimensions from Base64 String - Stack Overflow

php regex image base64
Rectangle 27 0

An image created using imagecreatefromstring has no MIME type any more, it is decoded from its native format and stored in GD's internal format.

The same question was asked a while back with the same result.

The only way to go is to catch the image before it gets imagecreatefromstringed, and somehow catch the size information from it.

You say that you can't do file read/write operations on your system, so just writing out the file is out of the question.

The fact that getimagesize() can't read from variables is known and lamented: http://bugs.php.net/bug.php?id=44239

The guy there mentions a nifty workaround: Registering a new stream wrapper that allows file operations on variables.

Sorry, like I said I can't read/write files to the server normally, so it's not possible to use getimagesize because there is no filename. EDIT: dude, don't be so impatient, I was writing an explanation... ;)

Can't be done with a GD resource only, sorry. But if you imagecreatefromstring, you have the original data at some point, right? Why not write it out to disk and do a getimagesize? I agree it's silly, but it'll do the job. EDIT: That's why I first comment and then vote ;) Second edit: Ah, you can't write to disk. And I take it you can't use the ftp:// wrapper for imagesize()?

FWIW, I just ran into this as well. PHP 5.3 is not available currently so getimagesizefromstring() is not an option (nor is FileInfo), and I didn't want to complicate the implementation with the VariableStream wrapper. The next best thing is using the data:// wrapper, which allows you to create an in-memory URI that getimagesize() can read. It also optimizes the request by only encoding a small substring of the binary data. The gist of the implementation is here: gist.github.com/3751491

Get image mimetype from resource in PHP/GD? - Stack Overflow

php image ftp gd
Rectangle 27 0

I think you should use the getimagesizefromstring function instead of parsing the raw data yourself:

list($width, $height, $type) = getimagesizefromstring($data);

Resaving the image will only degrade image quality.

php extension - Why does PHP fail to produce an image when loading an ...

php php-extension
Rectangle 27 0

getimagesize() does work with stream wrappers. Unfortunately, php://memory doesn't give you a way to reference it by filename. Either create your own stream wrapper that work smarter or use the VariableStream example.

PHP - get blob image size - FPDF - getimagesizefromstring doesn't work...

php image blob fpdf getimagesize
Rectangle 27 0

Make a new php by copying and pasting this (piece of fpdf's code edited):

require('fpdf.php');
class DATAIMAGE extends FPDF
{
protected function _parsedata($file)
{
    // Extract info from a JPEG file
    $a = getimagesizefromstring($file);
    if(!$a)
        $this->Error('Missing or incorrect image file: '.$file);
    if($a[2]!=2)
        $this->Error('Not a JPEG file: '.$file);
    if(!isset($a['channels']) || $a['channels']==3)
        $colspace = 'DeviceRGB';
    elseif($a['channels']==4)
        $colspace = 'DeviceCMYK';
    else
        $colspace = 'DeviceGray';
    $bpc = isset($a['bits']) ? $a['bits'] : 8;
    return array('w'=>$a[0], 'h'=>$a[1], 'cs'=>$colspace, 'bpc'=>$bpc, 'f'=>'DCTDecode', 'data'=>$file);
}
}

Then call this php instead of fpdf.php in your main php.

You'll now be able to display an image simply by adding 'data' to the end of the function:

$pdf->Image($mysqlrow["blob"],0,0,40,0,'data');

php - Image from database into PDF using FPDF - Stack Overflow

php pdf fpdf
Rectangle 27 0

if (!function_exists('getimagesizefromstring')) {
    function getimagesizefromstring($data)
    {
        $uri = 'data://application/octet-stream;base64,' . base64_encode($data);
        return getimagesize($uri);
    }
}

imagemagick - php get image size from a string of image content - Stac...

php imagemagick gd
Rectangle 27 0

Well you have basically two options:

  • Type check the image source directly

Probably the quicker way because it only involve splitting string, but it may be incorrect. Something like:

$data = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA.';
$pos  = strpos($data, ';');
$type = explode(':', substr($data, 0, $pos))[1];

Use getimagesize() and it's equivalent for string:

$info = getimagesizefromstring(explode(',', base64_decode($data)[1], 2));
// $info['mime']; contains the mimetype

@Developer, fixed it missed getting index 1 of the resulting explode function :)

the two options have php error. With php i can't use [1]

can you tell me how exactly you fixed this? I got the exact same error by copying and pasting your code @BorisGury

@user3531149, it is a shortcut notation since PHP5.5, you're probably using an older version. Just set the result of the function to a variable and access the array values from there.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

php - Get image type from base64 encoded src string - Stack Overflow

php image
Rectangle 27 0

$imageInfo = getimagesizefromstring($imgContent);
if ($imageInfo !== false) { 
  // that's an image
}

Additionally, you may want to check the image's MIME type (for setting the Content-Type header properly, for example):

$imageMimeType = image_type_to_mime_type($imageInfo[2]);

Note that both getimagesizefromstring() and image_type_to_mime_type() require GD extension to be in place - but then again, you probably have it loaded already.

php - How to verify the content type of the image file stored in ZIP a...

php zip mime-types
Rectangle 27 0

You can check when a file is an image with GD's function getimagesize or getimagesizefromstring. Then for every file being uploaded you check dimension. If the function you are using returns false then the file isn't an image.

With getimagesize you can also check the mime-type, so you can limit an image to be a specific type.

image - PHP File Uploads - .htaccess allowed file types - Stack Overfl...

php image .htaccess
Rectangle 27 0

Since you have the image's contents in a string, you can use getimagesizefromstring() which contains a mime field that will tell you the type of the image.

$data = base64_decode($data[1]);
$info = getimagesizefromstring($data);
$mime = $info['mime'];

If you need support for any file, not just images, you'll need to either write a custom file parser or, if you have the FileInfo PECL extension, you can use finfo_file():

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, '/path/to/your/file.jpg');
finfo_close($finfo);

The caveat to this is that you need an actual file, not a string (but you could always write the string to a temporary file).

EDIT: Here's the answer to solve the question without the need of a file being created. Let's take the following data from an image:

data:image/jpeg;base64/9j/4AAQSkZJRgA [...] xD5epeRHJ4glkjk/sb7R5lrFJ5fmfu/wDv5W1TEV/5wp+58

You would need to first parse it first

$data = explode(",", $data);

Then insert the string in the buffer

$finfo->buffer(base64_decode($data[1]))

Finally, use the answer from @JohnErck to solve the extension type.

file_put_contents($path . $filename . AppUtil::FileExt($data[1]), $data[1]);

So I would save the file with no extension, then read it from finfo and would deduct the extension from that?

@MichaelVilleneuve Yeah; file-types aren't solely dependent on the file's extension (for instance, you can save a jpeg as img.png and it will still open/render fine). Almost all files have headers in them that declare what their actual file-type is.

I'm on it, will get back to you with result, thanks for your time (no idea why someone downvoted you!)

You mind if I edit your answer, it's working but I would make a few modification for future user that would experience this issue?

@MichaelVilleneuve Feel free; make any changes to it that were necessary to solve your problem that could also help out others =]

php - Is there a way to know the file type with only the data - Stack ...

php
Rectangle 27 0

getimagesize() does work with stream wrappers. Unfortunately, php://memory doesn't give you a way to reference it by filename. Either create your own stream wrapper that work smarter or use the VariableStream example.

PHP - get blob image size - FPDF - getimagesizefromstring doesn't work...

php image blob fpdf getimagesize
Rectangle 27 0

As zerkms wrote, this is part of the file format header. It provides meta data about the file so programs know how to work with it.

To get information about the stored image you can use getimagesizefromstring().

This returns an array of information about the image. For example, my mini-avatar image here on SO (as seen at the bottom of this answer), when saved as a text file and accessed like so:

print_r(getimagesizefromstring(file_get_contents('./image.txt')));
Array
(
    [0] => 32
    [1] => 32
    [2] => 3
    [3] => width="32" height="32"
    [bits] => 8
    [mime] => image/png
)

As you can see, the image type is available via the [mime] key.

Note that you'll need PHP >= 5.4 for this function (which shouldn't be a problem since < 5.4 is no longer supported).

php - Get file type in BLOB Oracle - Stack Overflow

php image oracle types blob
Rectangle 27 0

getimagesizefromstring
$input = fopen('php://input', 'r');
$string = stream_get_contents($input);
fclose($input);

getimagesizefromstring($string);

php - getimagesize() on stream instead of string - Stack Overflow

php ajax file file-upload inputstream
Rectangle 27 0

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.

imagemagick - php get image size from a string of image content - Stac...

php imagemagick gd
Rectangle 27 0

It seems your image is stored as a BLOB in your database, and your query retrieves the image data.

getimagesizefromstring()
getimagesize()

But beware, the MySQL bindings sometimes have difficulty retrieving large BLOBs from the database.

php - How to getimagesize() when fetch image data from mysql database ...

php mysql image
Rectangle 27 0

  • Load the image string directly from your database into a variable ... not via getimagesize('avatar.php?id=1');
  • Use imagecreatefromstring to load your image as an image object. Afterwards you can manipulate your image and send it to your output.

If you just want the image size without any manipulation you can use getimagesizefromstring

php - getimagesize on dynamic image - Stack Overflow

php .htaccess dynamic getimagesize
Rectangle 27 0

Make a new php by copying and pasting this (piece of fpdf's code edited):

require('fpdf.php');
class DATAIMAGE extends FPDF
{
protected function _parsedata($file)
{
    // Extract info from a JPEG file
    $a = getimagesizefromstring($file);
    if(!$a)
        $this->Error('Missing or incorrect image file: '.$file);
    if($a[2]!=2)
        $this->Error('Not a JPEG file: '.$file);
    if(!isset($a['channels']) || $a['channels']==3)
        $colspace = 'DeviceRGB';
    elseif($a['channels']==4)
        $colspace = 'DeviceCMYK';
    else
        $colspace = 'DeviceGray';
    $bpc = isset($a['bits']) ? $a['bits'] : 8;
    return array('w'=>$a[0], 'h'=>$a[1], 'cs'=>$colspace, 'bpc'=>$bpc, 'f'=>'DCTDecode', 'data'=>$file);
}
}

Then call this php instead of fpdf.php in your main php.

You'll now be able to display an image simply by adding 'data' to the end of the function:

$pdf->Image($mysqlrow["blob"],0,0,40,0,'data');

php - Image from database into PDF using FPDF - Stack Overflow

php pdf fpdf