dismiss Step into the future! Click here to switch to the beta php.net site
downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

image_type_to_mime_type> <getimagesizefromstring
[edit] Last updated: Fri, 28 Jun 2013

view this page in

image_type_to_extension

(PHP 5)

image_type_to_extensionGet file extension for image type

Description

string image_type_to_extension ( int $imagetype [, bool $include_dot = TRUE ] )

Returns the extension for the given IMAGETYPE_XXX constant.

Parameters

imagetype

One of the IMAGETYPE_XXX constant.

include_dot

Whether to prepend a dot to the extension or not. Default to TRUE.

Return Values

A string with the extension corresponding to the given image type.

Examples

Example #1 image_type_to_extension() example

<?php
// Create image instance
$im imagecreatetruecolor(100100);

// Save image
imagepng($im'./test' image_type_to_extension(IMAGETYPE_PNG));
imagedestroy($im);
?>

Notes

Note:

This function does not require the GD image library.



image_type_to_mime_type> <getimagesizefromstring
[edit] Last updated: Fri, 28 Jun 2013
 
add a note add a note User Contributed Notes image_type_to_extension - [14 notes]
up
0
mike dot carper at gmail dot com
10 months ago
Here is a way to get the extension of an image without GD installed by using getimagesize() http://php.net/getimagesize. Note that using the predefined constants like IMAGETYPE_JPEG only get loaded if GD is enabled; see http://php.net/image.constants.

<?php

$file
= 'http://static.php.net/www.php.net/images/php.gif';
echo
get_image_extension($file);
// Returns '.gif'

/**
 * Given an image filename, get the file extension.
 *
 * @param $filename
 *   This parameter specifies the file you wish to retrieve information about.
 *   It can reference a local file or (configuration permitting) a remote file
 *   using one of the supported streams.
 * @param $include_dot
 *   Whether to prepend a dot to the extension or not. Default to TRUE.
 * @param $shorter_extensions
 *   Whether to use a shorter extension or not. Default to TRUE.
 * @return
 *   A string with the extension corresponding to the given image filename, or
 *   FALSE on failure.
 */
function get_image_extension($filename, $include_dot = true, $shorter_extensions = true) {
 
$image_info = @getimagesize($filename);
  if (!
$image_info || empty($image_info[2])) {
    return
false;
  }

  if (!
function_exists('image_type_to_extension')) {
   
/**
     * Given an image filename, get the file extension.
     *
     * @param $imagetype
     *   One of the IMAGETYPE_XXX constants.
     * @param $include_dot
     *   Whether to prepend a dot to the extension or not. Default to TRUE.
     * @param $shorter_extensions
     *   Whether to use a shorter extension or not. Default to TRUE.
     * @return
     *   A string with the extension corresponding to the given image type, or
     *   FALSE on failure.
     */
   
function image_type_to_extensiona ($imagetype, $include_dot = true) {
     
// Note we do not use the IMAGETYPE_XXX constants as these will not be
      // defined if GD is not enabled.
     
$extensions = array(
       
=> 'gif',
       
=> 'jpeg',
       
=> 'png',
       
=> 'swf',
       
=> 'psd',
       
=> 'bmp',
       
=> 'tiff',
       
=> 'tiff',
       
=> 'jpc',
       
10 => 'jp2',
       
11 => 'jpf',
       
12 => 'jb2',
       
13 => 'swc',
       
14 => 'aiff',
       
15 => 'wbmp',
       
16 => 'xbm',
      );

     
// We are expecting an integer between 1 and 16.
     
$imagetype = (int)$imagetype;
      if (!
$imagetype || !isset($extensions[$imagetype])) {
        return
false;
      }

      return (
$include_dot ? '.' : '') . $extensions[$imagetype];
    }
  }

 
$extension = image_type_to_extension($image_info[2], $include_dot);
  if (!
$extension) {
    return
false;
  }

  if (
$shorter_extensions) {
   
$replacements = array(
     
'jpeg' => 'jpg',
     
'tiff' => 'tif',
    );
   
$extension = strtr($extension, $replacements);
  }
  return
$extension;
}
?>
up
0
bimal at sanjaal dot com
1 year ago
<?php
/**
* Returns a COMMON extension with a dot
*/
function gd_extension($full_path_to_image='')
{
   
$extension = 'null';
    if(
$image_type = exif_imagetype($full_path_to_image))
    {
       
$extension = image_type_to_extension($image_type, false);
    }
   
$known_replacements = array(
       
'jpeg' => 'jpg',
       
'tiff' => 'tif',
    );
   
$extension = '.'.str_replace(array_keys($known_replacements), array_values($known_replacements), $extension);
   
    return
$extension;
}

# Testing
$images = glob('*');
foreach(
$images as $i => $image)
{
   
$extension = gd_extension($image);
    echo
"\r\n", $image, ': ', $extension;
}
?>

Sometimes, the extension is not as I expected, until I wrote this piece.
up
0
mew at world dot org
5 years ago
There is no need to over complicated folks.

<?php

if ( !function_exists('image_type_to_extension') ) {

    function
image_type_to_extension ($type, $dot = true)
    {
       
$e = array ( 1 => 'gif', 'jpeg', 'png', 'swf', 'psd', 'bmp'
            'tiff'
, 'tiff', 'jpc', 'jp2', 'jpf', 'jb2', 'swc',
           
'aiff', 'wbmp', 'xbm');

       
// We are expecting an integer.
       
$type = (int)$type;
        if (!
$type) {
           
trigger_error( '...come up with an error here...', E_USER_NOTICE );
            return
null;
        }

        if ( !isset(
$e[$type]) ) {
           
trigger_error( '...come up with an error here...' E_USER_NOTICE );
            return
null;
        }

        return (
$dot ? '.' : '') . $e[$type];
    }
   
}

if ( !
function_exists('image_type_to_mime_type') ) {

    function
image_type_to_mime_type ($type)
    {
       
$m = array ( 1 => 'image/gif', 'image/jpeg', 'image/png',
           
'application/x-shockwave-flash', 'image/psd', 'image/bmp',
           
'image/tiff', 'image/tiff', 'application/octet-stream',
           
'image/jp2', 'application/octet-stream', 'application/octet-stream',
           
'application/x-shockwave-flash', 'image/iff', 'image/vnd.wap.wbmp', 'image/xbm');

       
// We are expecting an integer.
       
$type = (int)$type;
        if (!
$type) {
           
trigger_error( '...come up with an error here...', E_USER_NOTICE );
            return
null;
        }

        if ( !isset(
$m[$type]) ) {
           
trigger_error( '...come up with an error here...' E_USER_NOTICE );
            return
null;
        }

        return
$m[$type];
    }

}

?>
up
0
Chris
5 years ago
- Function was added in PHP 5.2, not PHP 5 (you would assume this means 5.0)
- Function returns .jpeg, not .jpg
up
0
Ian Paul Short chukdocsAtHotmailDotCom
6 years ago
To: mail at spybreak dot de

I noted  your solution was for mime_type_to_extension which is flawed because the MIME types to extensions are not unique. See my example to consider what I have observed.

This function performs image type or mime type to extension. With limitation it will not attempt to handle duplicated MIME types. NOT DEFINITIVE!
<?php
   
if(!function_exists('image_type_to_extension')){      

       
$extension;

        function
image_type_or_mime_type_to_extension($image_type, $include_dot) {
           
define ("INVALID_IMAGETYPE", '');
           
           
$extension = INVALID_IMAGETYPE;            /// Default return value for invalid input

           
$image_type_identifiers = array (                                                                ### These values correspond to the IMAGETYPE constants
                   
array (IMAGETYPE_GIF         => 'gif',     "mime_type" => 'image/gif'),                        ###  1 = GIF
                   
array (IMAGETYPE_JPEG        => 'jpg',     "mime_type" => 'image/jpeg'),                        ###  2 = JPG
                   
array (IMAGETYPE_PNG        => 'png',     "mime_type" => 'image/png'),                        ###  3 = PNG
                   
array (IMAGETYPE_SWF        => 'swf',     "mime_type" => 'application/x-shockwave-flash'),    ###  4 = SWF  // A. Duplicated MIME type
                   
array (IMAGETYPE_PSD        => 'psd',     "mime_type" => 'image/psd'),                        ###  5 = PSD
                   
array (IMAGETYPE_BMP        => 'bmp',     "mime_type" => 'image/bmp'),                        ###  6 = BMP
                   
array (IMAGETYPE_TIFF_II    => 'tiff',     "mime_type" => 'image/tiff'),                        ###  7 = TIFF (intel byte order)
                   
array (IMAGETYPE_TIFF_MM    => 'tiff',     "mime_type" => 'image/tiff'),                        ###  8 = TIFF (motorola byte order)
                   
array (IMAGETYPE_JPC        => 'jpc',     "mime_type" => 'application/octet-stream'),            ###  9 = JPC  // B. Duplicated MIME type
                   
array (IMAGETYPE_JP2        => 'jp2',     "mime_type" => 'image/jp2'),                        ### 10 = JP2
                   
array (IMAGETYPE_JPX        => 'jpf',     "mime_type" => 'application/octet-stream'),            ### 11 = JPX  // B. Duplicated MIME type
                   
array (IMAGETYPE_JB2        => 'jb2',     "mime_type" => 'application/octet-stream'),            ### 12 = JB2  // B. Duplicated MIME type           
                   
array (IMAGETYPE_SWC        => 'swc',     "mime_type" => 'application/x-shockwave-flash'),    ### 13 = SWC  // A. Duplicated MIME type
                   
array (IMAGETYPE_IFF        => 'aiff',     "mime_type" => 'image/iff'),                        ### 14 = IFF
                   
array (IMAGETYPE_WBMP        => 'wbmp',     "mime_type" => 'image/vnd.wap.wbmp'),                ### 15 = WBMP
                   
array (IMAGETYPE_XBM        => 'xbm',     "mime_type" => 'image/xbm')                            ### 16 = XBM
           
);                                                                                   
           
            if((
is_int($image_type)) AND (IMAGETYPE_GIF <= $image_type) AND (IMAGETYPE_XBM >= $image_type)){
               
$extension = $image_type_identifiers[$image_type-1]; // -1 because $image_type_identifiers array starts at [0]
               
$extension = $extension[$image_type];
            }
            elseif(
is_string($image_type) AND (($image_type != 'application/x-shockwave-flash') OR ($image_type != 'application/octet-stream'))){               
           
               
$extension match_mime_type_to_extension($image_type, $image_type_identifiers);
            }
            else
            {
               
$extension = INVALID_IMAGETYPE;
            }

               if(
is_bool($include_dot)){

                   if((
false != $include_dot) AND (INVALID_IMAGETYPE != $extension)){
                      
$extension = '.' . $extension;
                   }
               }
               else
               {
                  
$extension = INVALID_IMAGETYPE;
               }                 
      
           return
$extension;

           }
    }   

    function
match_mime_type_to_extension($image_type, $image_type_identifiers){
       
// Return from loop on a match
       
foreach($image_type_identifiers as $_key_outer_loop => $_val_outer_loop){           
            foreach(
$_val_outer_loop as $_key => $_val){
                if(
is_int ($_key)){             // Keep record of extension for mime check
                   
$extension = $_val;
                }
                if(
$_key == 'mime_type'){   
                    if(
$_val === $image_type){    // Found match no need to continue looping
                       
return $extension;        ### Return
                   
}                    
                }
            }
        }
       
// Compared all values without match
       
return $extension = INVALID_IMAGETYPE;   
    }
   
   
$extension = image_type_or_mime_type_to_extension($image_type, $include_dot);
     return
$extension;
}
?>
up
0
Ian Paul Short chukdocsAtHotmailDotCom
6 years ago
2006-09-29

A few notes about some contributions on this page.

1. It seemed to me that on the face it of all of the offerings to emulate "image_type_to_extension" function fell short of the mark in one way or another (See my comments below). That's why I wrote my own and submitted to this page below. In respect of my work any comments, bugs noted or improvements would be gratefully received.

2. Avoid using the Switch statement in an unconventional method to "Break" (I note the use of the return statement!). Also even if it does nothing at the inception of our code - Still put in the default case (It lets others realise that a default is not required or at worst forgotton.

3. In an environment that is under your control the risk of an error by determining the content by its extension or MIME type may seem an attractive solution to a problem. However, in the real world there's no guarantee that a MIME type or file extension is correct for it's associated file.

Consider using functions to get the image type:
      getimagesize or (This is available without GD)
      exif_imagetype

4. There's more to coding than just putting something together to do a job!!! But whatever is done is worthwhile - Hence expletives have no place in this forum!!

5. The idea from "oridan at hotmail dot com" is a very slick idea. I will be taking a closer look at this for my own project.
up
0
Ian Paul Short
6 years ago
2006-09-29 Author: Ian Paul Short (chukdocs at hotmail dot com)

For reasons I have yet to determine the function “image_type_to_extension” is not available to both PHP 5.1.4 on my local host running under Windows XP or on my remote host running under Linux. Has anyone else had this problem? If so kindly post your findings here please.

In the meantime I needed a workaround and with many thanks to the previous contributors on this page - I took bits and pieces developed the following function to emulate the function image_type_to_extension:

    if(!function_exists('image_type_to_extension')){    ### Include this for graceful tranisition to using
                                                        ### PHP's equivalent function when it's available in the box
       
        function image_type_to_extension($image_type, $include_dot){
           
            // Assign definitions and intialise variables
            define ("INVALID_IMAGETYPE", '');            // Empty string            
            $extension = INVALID_IMAGETYPE;             // Return this (empty string) if "$image_type or $include_dot" do not contain legal values  

           
            if((is_int($image_type)) AND (is_bool($include_dot)) AND (IMAGETYPE_GIF <= $image_type) AND (IMAGETYPE_XBM >= $image_type)){ // Check input data are legal
           
                $image_type_extension = array (            ### These integer values correspond to the the respective IMAGETYPE constants
                    IMAGETYPE_GIF         => 'gif',        ###  1 = GIF
                    IMAGETYPE_JPEG         => 'jpg',        ###  2 = JPG
                    IMAGETYPE_PNG         => 'png',        ###  3 = PNG
                    IMAGETYPE_SWF         => 'swf',        ###  4 = SWF
                    IMAGETYPE_PSD         => 'psd',        ###  5 = PSD
                    IMAGETYPE_BMP         => 'bmp',        ###  6 = BMP   
                    IMAGETYPE_TIFF_II     => 'tiff',        ###  7 = TIFF     (intel byte order)
                    IMAGETYPE_TIFF_MM     => 'tiff',        ###  8 = TIFF     (motorola byte order)
                    IMAGETYPE_JPC         => 'jpc',        ###  9 = JPC
                    IMAGETYPE_JP2         => 'jp2',        ### 10 = JP2
                    IMAGETYPE_JPX         => 'jpf',        ### 11 = JPX     Yes! jpf extension is correct for JPX image type
                    IMAGETYPE_JB2         => 'jb2',        ### 12 = JB2
                    IMAGETYPE_SWC         => 'swc',        ### 13 = SWC
                    IMAGETYPE_IFF         => 'aiff',        ### 14 = IFF
                    IMAGETYPE_WBMP         => 'wbmp',        ### 15 = WBMP
                    IMAGETYPE_XBM         => 'xbm'        ### 16 = XBM
                );
                           
                $extension = $image_type_extension[$image_type]; // Get extension by using array as a look up table using $image_type as key
               
                if($include_dot != false) $extension = '.' . $extension; // If $include_dot is true prefix a dot to extension
               }

### Limitation - No user friendly error handler              
/*           
            else
               {
                   ### Put your error handler here
               }                   
*/       
        return $extension;
        }
    }
up
0
aleksandrs dot bogdanovs at gmail dot com
7 years ago
When I was writing a script for my photo website, it was necessary to write such function, which can get the extension of uploaded file (image), so the function is:

<?php
function get_extension($imagetype)
   {
       if(empty(
$imagetype)) return false;
       switch(
$imagetype)
       {
           case
'image/bmp': return '.bmp';
           case
'image/cis-cod': return '.cod';
           case
'image/gif': return '.gif';
           case
'image/ief': return '.ief';
           case
'image/jpeg': return '.jpg';
           case
'image/pipeg': return '.jfif';
           case
'image/tiff': return '.tif';
           case
'image/x-cmu-raster': return '.ras';
           case
'image/x-cmx': return '.cmx';
           case
'image/x-icon': return '.ico';
           case
'image/x-portable-anymap': return '.pnm';
           case
'image/x-portable-bitmap': return '.pbm';
           case
'image/x-portable-graymap': return '.pgm';
           case
'image/x-portable-pixmap': return '.ppm';
           case
'image/x-rgb': return '.rgb';
           case
'image/x-xbitmap': return '.xbm';
           case
'image/x-xpixmap': return '.xpm';
           case
'image/x-xwindowdump': return '.xwd';
           case
'image/png': return '.png';
           case
'image/x-jps': return '.jps';
           case
'image/x-freehand': return '.fh';
           default: return
false;
       }
   }
?>

It's useful for those, who upload files on server.
up
0
oridan at hotmail dot com
7 years ago
i used your code in the following to open different types of files depending on their 'type' (or rather, extension).  the eval simply creates
<?
// make sure you initialize $filename as the path to the image you want to load/create

   list(,,$type) = getimagesize($filename);
   $type = image_type_to_extension($type);
   eval("global \$filename; \$source = imagecreatefrom$type(\$filename);");
   global $source;
?>

$source is then the var you can play with.  saved me a big switch statement calling different "imagecreatefromjpg"/"imagecreatefromgif" functions just to do the one simple task.... open an image of varying types.
up
0
robe at amd dot co dot at
7 years ago
neil: your version fails to make sense for me
spybreak.de guy:

a) you left out BMP
b) you fucked up the order of the extension in the mid of the listing. if this was changed in the getimagesize function during php versions, I'm sorry. Otherwise: WHY?!
c) the include_dot stuff is the worst abuse of function arguments I've ever seen. Shame on you.

Here's a unfucked, working version:

<?
if(!function_exists('image_type_to_extension'))
{
   function image_type_to_extension($imagetype)
   {
       if(empty($imagetype)) return false;
       switch($imagetype)
       {
           case IMAGETYPE_GIF    : return 'gif';
           case IMAGETYPE_JPEG    : return 'jpg';
           case IMAGETYPE_PNG    : return 'png';
           case IMAGETYPE_SWF    : return 'swf';
           case IMAGETYPE_PSD    : return 'psd';
           case IMAGETYPE_BMP    : return 'bmp';
           case IMAGETYPE_TIFF_II : return 'tiff';
           case IMAGETYPE_TIFF_MM : return 'tiff';
           case IMAGETYPE_JPC    : return 'jpc';
           case IMAGETYPE_JP2    : return 'jp2';
           case IMAGETYPE_JPX    : return 'jpf';
           case IMAGETYPE_JB2    : return 'jb2';
           case IMAGETYPE_SWC    : return 'swc';
           case IMAGETYPE_IFF    : return 'aiff';
           case IMAGETYPE_WBMP    : return 'wbmp';
           case IMAGETYPE_XBM    : return 'xbm';
           default                : return false;
       }
   }
}
?>
up
0
mail at spybreak dot de
8 years ago
In case your PHP doesn't have this function, you can use this:
<?

if(!function_exists('image_type_to_extension'))
{
    function image_type_to_extension($imagetype,$include_dot=true)
    {
        if(empty($imagetype)) return false;
        $dot = $include_dot ? $dot.'' : '';
        switch($imagetype)
        {
            case IMAGETYPE_GIF     : return $dot.'gif';
            case IMAGETYPE_JPEG    : return $dot.'jpg';
            case IMAGETYPE_PNG     : return $dot.'png';
            case IMAGETYPE_SWF     : return $dot.'swf';
            case IMAGETYPE_PSD     : return $dot.'psd';
            case IMAGETYPE_WBMP    : return $dot.'wbmp';
            case IMAGETYPE_XBM     : return $dot.'xbm';
            case IMAGETYPE_TIFF_II : return $dot.'tiff';
            case IMAGETYPE_TIFF_MM : return $dot.'tiff';
            case IMAGETYPE_IFF     : return $dot.'aiff';
            case IMAGETYPE_JB2     : return $dot.'jb2';
            case IMAGETYPE_JPC     : return $dot.'jpc';
            case IMAGETYPE_JP2     : return $dot.'jp2';
            case IMAGETYPE_JPX     : return $dot.'jpf';
            case IMAGETYPE_SWC     : return $dot.'swc';
            default                : return false;
        }
    }
}
?>
up
-1
discerer at _REMOVETHIS_yahoo dot co dot uk
7 years ago
at aleksandrs note about mime checking

i really hope that piece of code isn't used as some kind of security check for uploading (excluding those which have no value in the switch-case ie), as the mime type in uploading could be very easily changed

and btw if you want to get the extension why not just use substr to get all the text after the last dot in the filename to be really sure that the file is really what the mime says?

this could be done easily with
<?php
$filename
= "roflhax.pwnage.jpeg";
if ((
$pos = strrpos($filename, ".")) === FALSE)
  echo
"Error - file doesn't have a dot... weird.";
else {
 
$extension = substr($filename, $pos + 1);
  echo
$extension; // will echo "jpeg"
}
?>
(or you could use pathinfo() or a regex :))
up
-1
neil at g4s dot org
7 years ago
refining the homebrew method a little further, i wound up with this version. note that i had to change the case statements from previous version to include call to image_type_to_mime_type()
<?php
public static function imageTypeToExtension($imageType, $includeDot = false) {
       
$dot = $includeDot ? '.' : '';
       
$ext = false;
       if(!empty(
$imageType)) {
          switch(
$imageType) {
              case
image_type_to_mime_type(IMAGETYPE_GIF)    : $ext = $dot.'gif'; break;
              case
image_type_to_mime_type(IMAGETYPE_JPEG)    : $ext = $dot.'jpg'; break;
              case
image_type_to_mime_type(IMAGETYPE_PNG)    : $ext = $dot.'png'; break;
              case
image_type_to_mime_type(IMAGETYPE_SWF)    : $ext = $dot.'swf'; break;
              case
image_type_to_mime_type(IMAGETYPE_PSD)    : $ext = $dot.'psd'; break;
              case
image_type_to_mime_type(IMAGETYPE_WBMP)    : $ext = $dot.'wbmp'; break;
              case
image_type_to_mime_type(IMAGETYPE_XBM)    : $ext = $dot.'xbm'; break;
              case
image_type_to_mime_type(IMAGETYPE_TIFF_II) : $ext = $dot.'tiff'; break;
              case
image_type_to_mime_type(IMAGETYPE_TIFF_MM) : $ext = $dot.'tiff'; break;
              case
image_type_to_mime_type(IMAGETYPE_IFF)    : $ext = $dot.'aiff'; break;
              case
image_type_to_mime_type(IMAGETYPE_JB2)    : $ext = $dot.'jb2'; break;
              case
image_type_to_mime_type(IMAGETYPE_JPC)    : $ext = $dot.'jpc'; break;
              case
image_type_to_mime_type(IMAGETYPE_JP2)    : $ext = $dot.'jp2'; break;
              case
image_type_to_mime_type(IMAGETYPE_JPX)   : $ext = $dot.'jpf'; break;
              case
image_type_to_mime_type(IMAGETYPE_SWC)    : $ext = $dot.'swc'; break;
          }
   }
   return
$ext;
  }
?>
up
-1
Anonymous
8 years ago
Just an improvement/bugfix for the function below:
<?php
$dot
= $include_dot ? $dot.'' : '';
//surely what was meant is....:
$dot = $include_dot ? '.' : '';
?>

Because otherwise $dot always will be empty.....

 
show source | credits | stats | sitemap | contact | advertising | mirror sites