Получить расширение изображения
Как я знаю, лучшим способом является getimagesize() .
но это функция mime, возвращает image/jpeg когда изображение имеет .jpg или также расширение .JPEG .
Как получить точное расширение?
вы можете использовать функцию image_type_to_extension с типом изображения, возвращаемым getimagesize :
$info = getimagesize($path); $extension = image_type_to_extension($info[2]);
$ext = pathinfo($filename, PATHINFO_EXTENSION);
Вы также можете использовать функции strrpos и substr, чтобы получить расширение любого файла
$filePath="images/ajax-loader.gif"; $type=substr($filePath,strrpos($filePath,'.')+1); echo "file type=".$type;
если вы хотите расширение, например .gif
$type=substr($filePath,strrpos($filePath,'.')+0);
$image = explode(".","test.file.hhh.kkk.jpg"); echo end($image);
Еще один способ сделать это:
$ext = strrchr($filename, "."); // .jpg
Вы также можете взорвать имя файла с точками и взять конец массива следующим образом:
$ext = end(explode('.', 'image.name.gif'));
Согласно: Два разных способа найти расширение файла в PHP
И новый способ для вас LOL:
$ext = explode('.', 'file.name.lol.lolz.jpg'); echo $ext[count($ext) - 1];
Для тех, кто хочет проверить, есть ли тип изображения JPEG, PNG или т. Д. Вы можете использовать функцию exif_imagetype . Эта функция считывает первые байты изображения и проверяет его подпись. Вот простой пример из php.net:
$size = getimagesize($filename); $ext = explode('/', $size['mime'])[1];
image_type_to_extension
Возвращает расширение файла для заданной IMAGETYPE_XXX константы.
Список параметров
Одна из констант IMAGETYPE_XXX .
Добавлять точку к расширению или нет. По умолчанию true .
Возвращаемые значения
Строка с расширением файла, соответствующим типу изображения или false в случае возникновения ошибки.
Примеры
Пример #1 Пример использования image_type_to_extension()
// Создание изображения
$im = imagecreatetruecolor ( 100 , 100 );
?php
// Сохранение изображения
imagepng ( $im , ‘./test’ . image_type_to_extension ( IMAGETYPE_PNG ));
imagedestroy ( $im );
?>
Примечания
Замечание:
Этой функции не требуется библиотека GD.
User Contributed Notes 7 notes
If you would like to get the extension from a filename (string), the following should save you any frustration with exploding the string into parts (be sure to read the documentation warnings for pathinfo):
$filename = «wallpaper.jpg» ;
$extension = pathinfo ( $filename , PATHINFO_EXTENSION );
// if you just want to find the format from the file path name without creating any images
// image path name
$image_name = «image name.png»;
// After the last point is naturally the format.
$dots = explode(«.»,$image_name);
// We assign the last data of $dots to the variable $type.
$type = $dots[(count($dots)-1)];
// The output will be written without a dot.
echo «without dot : «.$type;
//for dotted
$type = «.».$type;
echo «dotted : «.$type;
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.
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:
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.
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!
if(! function_exists ( ‘image_type_to_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 )) $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(( false != $include_dot ) AND ( INVALID_IMAGETYPE != $extension )) $extension = ‘.’ . $extension ;
>
>
else
$extension = INVALID_IMAGETYPE ;
>
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 ;
>
?>
/**
* 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 );
?php
# 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.
There is no need to over complicated folks.
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 ;
>
- Функции GD и функции для работы с изображениями
- gd_info
- getimagesize
- getimagesizefromstring
- image_type_to_extension
- image_type_to_mime_type
- image2wbmp
- imageaffine
- imageaffinematrixconcat
- imageaffinematrixget
- imagealphablending
- imageantialias
- imagearc
- imageavif
- imagebmp
- imagechar
- imagecharup
- imagecolorallocate
- imagecolorallocatealpha
- imagecolorat
- imagecolorclosest
- imagecolorclosestalpha
- imagecolorclosesthwb
- imagecolordeallocate
- imagecolorexact
- imagecolorexactalpha
- imagecolormatch
- imagecolorresolve
- imagecolorresolvealpha
- imagecolorset
- imagecolorsforindex
- imagecolorstotal
- imagecolortransparent
- imageconvolution
- imagecopy
- imagecopymerge
- imagecopymergegray
- imagecopyresampled
- imagecopyresized
- imagecreate
- imagecreatefromavif
- imagecreatefrombmp
- imagecreatefromgd2
- imagecreatefromgd2part
- imagecreatefromgd
- imagecreatefromgif
- imagecreatefromjpeg
- imagecreatefrompng
- imagecreatefromstring
- imagecreatefromtga
- imagecreatefromwbmp
- imagecreatefromwebp
- imagecreatefromxbm
- imagecreatefromxpm
- imagecreatetruecolor
- imagecrop
- imagecropauto
- imagedashedline
- imagedestroy
- imageellipse
- imagefill
- imagefilledarc
- imagefilledellipse
- imagefilledpolygon
- imagefilledrectangle
- imagefilltoborder
- imagefilter
- imageflip
- imagefontheight
- imagefontwidth
- imageftbbox
- imagefttext
- imagegammacorrect
- imagegd2
- imagegd
- imagegetclip
- imagegetinterpolation
- imagegif
- imagegrabscreen
- imagegrabwindow
- imageinterlace
- imageistruecolor
- imagejpeg
- imagelayereffect
- imageline
- imageloadfont
- imageopenpolygon
- imagepalettecopy
- imagepalettetotruecolor
- imagepng
- imagepolygon
- imagerectangle
- imageresolution
- imagerotate
- imagesavealpha
- imagescale
- imagesetbrush
- imagesetclip
- imagesetinterpolation
- imagesetpixel
- imagesetstyle
- imagesetthickness
- imagesettile
- imagestring
- imagestringup
- imagesx
- imagesy
- imagetruecolortopalette
- imagettfbbox
- imagettftext
- imagetypes
- imagewbmp
- imagewebp
- imagexbm
- iptcembed
- iptcparse
- jpeg2wbmp
- png2wbmp