exif_read_data

(PHP 4 >= 4.2.0, PHP 5)

exif_read_data Читает EXIF-заголовки JPEG и TIFF изображений

Описание

array exif_read_data ( string $filename [, string $sections = NULL [, bool $arrays = false [, bool $thumbnail = false ]]] )

exif_read_data() читает EXIF-заголовки JPEG и TIFFфайлов. Таким образом можно читать метаданные, генерируемые цифровыми фотоаппаратами.

По идее, EXIF-заголовки должны идти первыми в JPEG/TIFF файлах, генерируемых фотоаппаратами. Но, к сожалению, каждый производитель имеет свое представление того, каким образом компоновать метаданные изображения. Поэтому будьте готовы к ситуации, когда перед Exif-заголовком есть еще что-то.

Height и Width вычисляются аналогично вычислениям getimagesize(), так что эти параметры не обязаны присутствовать в заголовке. html - текстовая строка, задающая высоту/ширину, которую можно использовать в обычном HTML.

Если Exif-заголовок содержит сообщение об авторских правах (Copyright), само сообщение может содержать 2 значения. Эта ситуация не описана в стандарте Exif 2.10, поэтому раздел COMPUTED будет содержать оба этих значения в полях Copyright.Photographer и Copyright.Editor. В то же время разделы IFD0 будут содержать массив байт с NULL-символом в качестве разделителся этих двух значений либо только первое значение, если тип файла определен неверно (нормальная ситуация для Exif). Раздел COMPUTED будет также содержать Copyright, это может быть либо исходная строка, либо список из владельца фотографии и редактора через запятую.

Тэг UserComment имеет те же проблемы, что и Copyright. Он может хранить 2 значения. Первое - использованную кодировку, второе - само значение. В этом случае раздел IFD содержит либо кодировку, либо массив байт. Раздел COMPUTED будет хранить оба этих значения в полях UserCommentEncoding и UserComment. Содержимое UserComment будет доступно в любом случае, поэтому предпочтительней использовать его вместо раздела IFD0.

Также exif_read_data() проверяет EXIF тэги на соответствие спецификации EXIF (» http://exif.org/Exif2-2.PDF, стр. 20).

Замечание:

Windows Me/XP могут затирать Exif-заголовки при подключении фотоаппарата.

Список параметров

filename

Имя файла изображения. Нельзя передавать URL.

sections

Список разделенных запятой разделов, которые должны быть представлены в результирующем массиве array. Если ни один из разделов найти не удастся, функция вернет FALSE.

FILE FileName, FileSize, FileDateTime, SectionsFound
COMPUTED html, Width, Height, IsColor, и другие. Height and Width вычисляются аналогично getimagesize(), поэтому их не обязательно включать в заголовок. html - текстовая строка, задающая высоту/ширину, которую можно использовать в обычном HTML.
ANY_TAG Любая информация заключенная в тэг, например IFD0, EXIF, ...
IFD0 Все данные тэга IFD0. В обычных изображениях в нем хранится размер изображения.
THUMBNAIL Если файл содержит второй раздел IFD, то считается, что у изображения есть эскиз. Вся информация об эскизе хранится в этом разделе.
COMMENT Заголовки комментариев JPEG изображений.
EXIF Раздел EXIF является подразделом IFD0. Он содержит более детальную информацию об изображении. Большинство его записей зависит от фотоаппарата.

arrays

Определяет, формировать ли разделы в виде массивов. Разделы sections, COMPUTED, THUMBNAIL и COMMENT всегда делаются массивами, так как они могут содержать значения, имена которых будут конфликтовать с именами в других разделах.

thumbnail

Если TRUE, будет прочитан сам эскиз. В противном случае будет прочитана только информация в тэгах.

Возвращаемые значения

Возвращает ассоциативный массив array, в котором ключами будут имена заголовков, а значениями - значения соответствующие этим заголовкам. Если никаких данных вернуть нельзя, exif_read_data() вернет FALSE.

Список изменений

Версия Описание
4.3.0 Может читать все встроенные IFD данные, включая массивы. Размер встроенного эскиза возвращается во вложенном THUMBNAIL. Может возвращать эскизы в формате TIFF. Больше нет ограничения максимальной длины возвращаемых значений (но всю память выработать не получится).
4.3.0 Если в PHP есть поддержка mbstring, кодировка пользовательского комментария может быть автоматически изменена. Если пользовательский комментарий представлен в кодировках Unicode или JIS, эти кодировки будут автоматически преобразованы в соответствии с ini-настройками в php.ini
4.3.0 Если изображение содержит какие-либо данные в IFD0, то COMPUTED будет содержать порядок байт ByteOrderMotorola со значением 0 для little-endian (intel) и 1 для big-endian (motorola). Также, COMPUTED и UserComment больше не содержат первое значение copyright, если при определении типа данных файла возникла ошибка.

Примеры

Пример #1 Пример использования exif_read_data()

<?php
echo "test1.jpg:<br />\n";
$exif exif_read_data('tests/test1.jpg''IFD0');
echo 
$exif===false "Не найдено данных заголовка.<br />\n" "Изображение содержит заголовки<br />\n";

$exif exif_read_data('tests/test2.jpg'0true);
echo 
"test2.jpg:<br />\n";
foreach (
$exif as $key => $section) {
    foreach (
$section as $name => $val) {
        echo 
"$key.$name$val<br />\n";
    }
}
?>

Первых вызов завершается неудачей, так как в заголовках изображения нет информации.

Результатом выполнения данного примера будет что-то подобное:

test1.jpg:
No header data found.
test2.jpg:
FILE.FileName: test2.jpg
FILE.FileDateTime: 1017666176
FILE.FileSize: 1240
FILE.FileType: 2
FILE.SectionsFound: ANY_TAG, IFD0, THUMBNAIL, COMMENT
COMPUTED.html: width="1" height="1"
COMPUTED.Height: 1
COMPUTED.Width: 1
COMPUTED.IsColor: 1
COMPUTED.ByteOrderMotorola: 1
COMPUTED.UserComment: Exif test image.
COMPUTED.UserCommentEncoding: ASCII
COMPUTED.Copyright: Photo (c) M.Boerger, Edited by M.Boerger.
COMPUTED.Copyright.Photographer: Photo (c) M.Boerger
COMPUTED.Copyright.Editor: Edited by M.Boerger.
IFD0.Copyright: Photo (c) M.Boerger
IFD0.UserComment: ASCII
THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNAIL.JPEGInterchangeFormatLength: 523
COMMENT.0: Comment #1.
COMMENT.1: Comment #2.
COMMENT.2: Comment #3end
THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNAIL.Thumbnail.Height: 1
THUMBNAIL.Thumbnail.Height: 1

Смотрите также

  • exif_thumbnail() - Получает встроенный эскиз TIFF или JPEG изображения
  • getimagesize() - Получение размера изображения

Коментарии

Автор:
When reading EXIF information from the 'WINXP' group, you may need to change used encoding from the default "ISO-8859-15" to "UTF-8". This can be done in php.ini or in your code:

<?php
    ini_set
('exif.encode_unicode''UTF-8');

   
$exif exif_read_data('TEST.JPG'0true);
    echo 
$exif['WINXP']['Title'];
?>

Useful documentation about EXIF:
http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/EXIF.html
See also comments next to XPTitle and XPAuthor.
2007-03-05 13:50:54
http://php5.kiev.ua/manual/ru/function.exif-read-data.html
some cameras (most higher models) have position senzor (gyroskope?) and taking-position is wrote in EXIF, here is simple script for automatic rotating images

<?php
$exif 
exif_read_data($filename);
$ort $exif['IFD0']['Orientation'];
    switch(
$ort)
    {
        case 
1// nothing
       
break;

        case 
2// horizontal flip
           
$image->flipImage($public,1);
        break;
                               
        case 
3// 180 rotate left
           
$image->rotateImage($public,180);
        break;
                   
        case 
4// vertical flip
           
$image->flipImage($public,2);
        break;
               
        case 
5// vertical flip + 90 rotate right
           
$image->flipImage($public2);
               
$image->rotateImage($public, -90);
        break;
               
        case 
6// 90 rotate right
           
$image->rotateImage($public, -90);
        break;
               
        case 
7// horizontal flip + 90 rotate right
           
$image->flipImage($public,1);   
           
$image->rotateImage($public, -90);
        break;
               
        case 
8:    // 90 rotate left
           
$image->rotateImage($public90);
        break;
    }

?>

$image->rotateImage() is inspired by example of function.imagerotate
$image->flipImage() is inspired by function.imagecopy#42803 (thank you)
2007-08-08 04:57:31
http://php5.kiev.ua/manual/ru/function.exif-read-data.html
Using the exif methods to read WINXP data returns unexpected results unless both exif and mbstring are compiled statically.  Please reference the following bug reports:

Bug #31980
Bug #23105

 
Specifically, the last comment on #23105:

"[8 Apr 2003 4:26pm UTC] edink@php.net

This cannot be fixed due to the fact that mbstring has been removed from PHP core (it has been 'unbundled') and the rest of core files and other extensions cannot use mbstring functionality when it is compiled as a shared library (dll).
"

If exif is compiled statically (--enable-exif) and mbstring compiled as a DSO module (--enable-mbstring=shared) then exif_read_data may only return a single character rather than the entire string.

Compiling both exif and mbstring statically (--enable-exif --enable-mbstring) resolves the issue.
2007-09-04 21:20:39
http://php5.kiev.ua/manual/ru/function.exif-read-data.html
I wanted some quick and easy functions for computing the shutter speed and f-stop.  I couldn't find any anywhere, so I made some.  It took some research :

<?php
function exif_get_float($value) {
 
$pos strpos($value'/');
  if (
$pos === false) return (float) $value;
 
$a = (float) substr($value0$pos);
 
$b = (float) substr($value$pos+1);
  return (
$b == 0) ? ($a) : ($a $b);
}

function 
exif_get_shutter(&$exif) {
  if (!isset(
$exif['ShutterSpeedValue'])) return false;
 
$apex    exif_get_float($exif['ShutterSpeedValue']);
 
$shutter pow(2, -$apex);
  if (
$shutter == 0) return false;
  if (
$shutter >= 1) return round($shutter) . 's';
  return 
'1/' round($shutter) . 's';
}

function 
exif_get_fstop(&$exif) {
  if (!isset(
$exif['ApertureValue'])) return false;
 
$apex  exif_get_float($exif['ApertureValue']);
 
$fstop pow(2$apex/2);
  if (
$fstop == 0) return false;
  return 
'f/' round($fstop,1);
}
?>
2008-07-29 02:33:47
http://php5.kiev.ua/manual/ru/function.exif-read-data.html
Get some EXIFs fields (easy way):

<?php
        $exif_make 
exif_read_data $_FILES['photo']['tmp_name'] ,'IFD0' ,);
       
$emake $exif_make['Make'];
       
       
$exif_model exif_read_data $_FILES['photo']['tmp_name'] ,'IFD0' ,);
       
$emodel $exif_model['Model'];
       
       
$exif_exposuretime exif_read_data $_FILES['photo']['tmp_name'] ,'EXIF' ,);
       
$eexposuretime $exif_exposuretime['ExposureTime'];
       
       
$exif_fnumber exif_read_data $_FILES['photo']['tmp_name'] ,'EXIF' ,);
       
$efnumber $exif_fnumber['FNumber'];

       
$exif_iso exif_read_data $_FILES['photo']['tmp_name'] ,'EXIF' ,);
       
$eiso $exif_iso['ISOSpeedRatings'];
               
       
$exif_date exif_read_data $_FILES['photo']['tmp_name'] ,'IFD0' ,);
       
$edate $exif_date['DateTime'];
?>
2008-09-26 19:57:07
http://php5.kiev.ua/manual/ru/function.exif-read-data.html
From - darkain at darkain dot com 's example.

If all the data is from the same image - simply

<?php
        $exif_data 
exif_read_data $_FILES['photo']

       
$emake =$exif_data['Make'];
       
$emodel $exif_data['Model'];
       
$eexposuretime $exif_data['ExposureTime'];
       
$efnumber $exif_data['FNumber'];
       
$eiso $exif_data['ISOSpeedRatings'];
       
$edate $exif_data['DateTime'];
?>

will work, I tried using the PEL library, and while pretty cool, I can't for the life understand how to call some things, this is simpler if your system is pretty basic or if you're in a rush.  If you have time, try playing with PEL.  It's not maintained at the moment though..

http://pel.sourceforge.net/
2008-11-20 23:01:23
http://php5.kiev.ua/manual/ru/function.exif-read-data.html
Please note that when resizing images with GD and most image processing scripts or applications you will loose the EXIF information. What I did as a workaround is book this information into MySQL before I re-size images. 

<?php

// This function is used to determine the camera details for a specific image. It returns an array with the parameters.
function cameraUsed($imagePath) {

   
// Check if the variable is set and if the file itself exists before continuing
   
if ((isset($imagePath)) and (file_exists($imagePath))) {
   
     
// There are 2 arrays which contains the information we are after, so it's easier to state them both
     
$exif_ifd0 read_exif_data($imagePath ,'IFD0' ,0);       
     
$exif_exif read_exif_data($imagePath ,'EXIF' ,0);
     
     
//error control
     
$notFound "Unavailable";
     
     
// Make 
     
if (@array_key_exists('Make'$exif_ifd0)) {
       
$camMake $exif_ifd0['Make'];
      } else { 
$camMake $notFound; }
     
     
// Model
     
if (@array_key_exists('Model'$exif_ifd0)) {
       
$camModel $exif_ifd0['Model'];
      } else { 
$camModel $notFound; }
     
     
// Exposure
     
if (@array_key_exists('ExposureTime'$exif_ifd0)) {
       
$camExposure $exif_ifd0['ExposureTime'];
      } else { 
$camExposure $notFound; }

     
// Aperture
     
if (@array_key_exists('ApertureFNumber'$exif_ifd0['COMPUTED'])) {
       
$camAperture $exif_ifd0['COMPUTED']['ApertureFNumber'];
      } else { 
$camAperture $notFound; }
     
     
// Date
     
if (@array_key_exists('DateTime'$exif_ifd0)) {
       
$camDate $exif_ifd0['DateTime'];
      } else { 
$camDate $notFound; }
     
     
// ISO
     
if (@array_key_exists('ISOSpeedRatings',$exif_exif)) {
       
$camIso $exif_exif['ISOSpeedRatings'];
      } else { 
$camIso $notFound; }
     
     
$return = array();
     
$return['make'] = $camMake;
     
$return['model'] = $camModel;
     
$return['exposure'] = $camExposure;
     
$return['aperture'] = $camAperture;
     
$return['date'] = $camDate;
     
$return['iso'] = $camIso;
      return 
$return;
   
    } else {
      return 
false
    } 
}

?>

An example of it's use follows:

<?php

$camera 
cameraUsed("/img/myphoto.jpg");
echo 
"Camera Used: " $camera['make'] . " " $camera['model'] . "<br />";
echo 
"Exposure Time: " $camera['exposure'] . "<br />";
echo 
"Aperture: " $camera['aperture'] . "<br />";
echo 
"ISO: " $camera['iso'] . "<br />";
echo 
"Date Taken: " $camera['date'] . "<br />";

?>

Will display the following, depending on the data:

Camera Used: SONY DSC-S930
Exposure Time: 1/400
Aperture: f/4.3
ISO: 100
Date Taken: 2010:12:10 18:18:45

If the image has been re-sized and the information is no longer available then you should receive the following when echoing the same:

Camera Used: Unavailable
Exposure Time: Unavailable
Aperture: Unavailable
ISO: Unavailable
Date Taken: Unavailable

Some cameras do not capture all the information, for instance Blackberry phones do not record an aperture, or iso and you will get Unavailable for those fields. 

I hope you find this helpful.
2012-03-13 13:40:33
http://php5.kiev.ua/manual/ru/function.exif-read-data.html
When the new update came out from Apple for iOS6 it provided the ability for iPad, iPod, and iPhones to be able to upload files from the device through Safari. Obviously this will open up an array of implementations where at one point it was just not possible.

The issue comes when a photo is uploaded it will be dependent on the location of the "button" when the photo was taken. Imagine if you will that you have your iPhone turned with the button at the top and you take a photo. The photo when uploaded to your server might be "upside down".

The following code will ensure that all uploaded photos will be oriented correctly upon upload:
<?php
$image 
imagecreatefromstring(file_get_contents($_FILES['image_upload']['tmp_name']));
$exif exif_read_data($_FILES['image_upload']['tmp_name']);
if(!empty(
$exif['Orientation'])) {
    switch(
$exif['Orientation']) {
        case 
8:
           
$image imagerotate($image,90,0);
            break;
        case 
3:
           
$image imagerotate($image,180,0);
            break;
        case 
6:
           
$image imagerotate($image,-90,0);
            break;
    }
}
// $image now contains a resource with the image oriented correctly
?>

What you do with the image resource from there is entirely up to you.

I hope that this helps you identify and orient any image that's uploaded from an iPad, iPhone, or iPod. Orientation for the photo is the key to knowing how to rotate it correctly.
2012-12-20 15:34:30
http://php5.kiev.ua/manual/ru/function.exif-read-data.html
Photos processed in Picasa often contain garbage data in the "MAKERNOTE" section and under EXIF.MakerNote, (UTF8) like:

[MakerNote] => r0~Þæ"î2OÔy     e §…b!    )    ) EI "ÐÓ
#s &0{ 'Û (å -Ð`ÿÿ@ÿÿÿìE è€Ýÿÿ  ÿÿÿÿÿÿx "ú»Dóÿ H ?.}BúIMG:DIGITAL IXUS 100 IS JPEGFirmware Version 1.00s›xÇØÿÿÿ–l¥ÿÿÿ   ØÌÌxŒ ÿÿÌÌŸãÿÿÿ¼Ž(½ (½T‹U’‹d–~Ø“¥ÿÿÿ    ÀÿœªãjáÀpgaXfaWb[Te«
8ú5:Áð-3åÿÿ5»ÿ ‹;ßÊ Š €à€`         ¸ ddîÿîÿîÿîÿîÿîÿ
ÿÿŠ1—ÏàôÉæ׬gªiï

This can't be written to Blob in MySql. The following code removes the garbage tags.

$exif = exif_read_data($process_photo, 0, 'EXIF');

if($exif['IFD0']['Software'] == "Picasa"){

foreach ($exif as $key => $section){

 if($key != "MAKERNOTE"){
  foreach ($section as $name => $val){
   if($name != 'MakerNote'){
    $exifA[$key][$name] = $val;
   }
  }
  $exifB[$key] = $exifA[$key];
 }
}
$serialized_exif = serialize ($exifB);
}else{
$serialized_exif = serialize ($exif);
}
2013-04-25 09:34:14
http://php5.kiev.ua/manual/ru/function.exif-read-data.html
This is function, resize image and don't rotates images have exif info

PHP must be enabled: 
extension=php_mbstring.dll 
extension=php_exif.dll

<?php
function CreateThumbnail($pic,$thumb,$thumbwidth$quality 100)
{

       
$im1=ImageCreateFromJPEG($pic);

       
//if(function_exists("exif_read_data")){
               
$exif exif_read_data($pic);
                if(!empty(
$exif['Orientation'])) {
                switch(
$exif['Orientation']) {
                case 
8:
                   
$im1 imagerotate($im1,90,0);
                    break;
                case 
3:
                   
$im1 imagerotate($im1,180,0);
                    break;
                case 
6:
                   
$im1 imagerotate($im1,-90,0);
                    break;
                } 
                }
       
//}
       
$info = @getimagesize($pic);

       
$width $info[0];

       
$w2=ImageSx($im1);
       
$h2=ImageSy($im1);
       
$w1 = ($thumbwidth <= $info[0]) ? $thumbwidth $info[0]  ;

       
$h1=floor($h2*($w1/$w2));
       
$im2=imagecreatetruecolor($w1,$h1);

       
imagecopyresampled ($im2,$im1,0,0,0,0,$w1,$h1,$w2,$h2); 
       
$path=addslashes($thumb);
       
ImageJPEG($im2,$path,$quality);
       
ImageDestroy($im1);
       
ImageDestroy($im2);
}
?>
2013-05-26 20:47:40
http://php5.kiev.ua/manual/ru/function.exif-read-data.html
Following up on darkain at darkain dot com  script for grabbing the ShutterSpeedValue from exif data...
@function.exif-read-data

I have found that the option shown for ShutterSppedValue, can also be ExposureTime in the exif data. 

Also the code as written provides a WRONG return, as the return is always 1 so you get 1/1sec.

Here is corrected code, or a version that corrects what is obviously not working after 5 years since it was originally developed::

Here is the updated version for:: $exif[ExposureTime]

    function exif_get_float($value) { 
        $pos = strpos($value, '/'); 
        if ($pos === false) return (float) $value; 
        $a = (float) substr($value, 0, $pos); 
        $b = (float) substr($value, $pos+1); 
    return ($b == 0) ? ($a) : ($a / $b); 
    };

    function exif_get_exposureTime(&$exif) { 
        if (!isset($exif['ExposureTime'])) return false; 
        $apex    = exif_get_float($exif['ExposureTime']);           
        $shutter = 1/$apex; 
        // above 1 sec exposure time::
        if ($shutter <= 1) return round($apex) . ' seconds'; 

    return '1/' . round(1 / $apex) . 'sec';
    };
2013-12-06 11:19:08
http://php5.kiev.ua/manual/ru/function.exif-read-data.html
I posted the original version of the function, but after using it for a while I discovered I didn't do enough error checking. 

I have re-factored it somewhat, and it now returns an empty array should it not be able to read the image's exif. If it is able to, it will return the details it was able to retrieve. And this should be without error. 

I am suppressing errors, because if you pass it images which cannot parse, you will get a warning. 

<?php 

# Modified Version of cameraUsed, no longer returns date. 
public function cameraUsed($imagePath)
{
   
# The default empty return
   
$return = array(
       
'make'      => "",
       
'model'     => "",
       
'exposure'  => "",
       
'aperture'  => "",
       
'iso'       => ""
   
);

   
// Check if the variable is set and if the file itself exists before continuing
   
if ((isset($imagePath)) AND (file_exists($imagePath)))
    {
       
// There are 2 arrays which contains the information we are after, so it's easier to state them both
       
$exif_ifd0 = @read_exif_data($imagePath ,'IFD0' ,0);
       
$exif_exif = @read_exif_data($imagePath ,'EXIF' ,0);

       
# Ensure that we actually got some information
       
if (($exif_ifd0 !== false) AND ($exif_exif !== false))
        {
           
// Make
           
if (@array_key_exists('Make'$exif_ifd0))
            {
               
$return['make']     = $exif_ifd0['Make'];
            }

           
// Model
           
if (@array_key_exists('Model'$exif_ifd0))
            {
               
$return['model']    = $exif_ifd0['Model'];
            }

           
// Exposure
           
if (@array_key_exists('ExposureTime'$exif_ifd0))
            {
               
$return['exposure'] = $exif_ifd0['ExposureTime'];
            }

           
// Aperture
           
if (@array_key_exists('ApertureFNumber'$exif_ifd0['COMPUTED']))
            {
               
$return['aperture'] = $exif_ifd0['COMPUTED']['ApertureFNumber'];
            }

           
// ISO
           
if (@array_key_exists('ISOSpeedRatings',$exif_exif))
            {
               
$return['iso']     = $exif_exif['ISOSpeedRatings'];
            }
        }
    }

   
# Return either an empty array, or the details which we were able to extrapolate.
   
return $return;
}

?>
2013-12-20 10:15:53
http://php5.kiev.ua/manual/ru/function.exif-read-data.html
Автор:
I was needing to use exif_read_data() to read out the orientation flag, only to find that the webhost didn't have the exif extension available for use.  Instead, I hacked up a regex that worked fairly well as a replacement

<?php
$orientation 
1;
if (
function_exists('exif_read_data')) {
   
$exif exif_read_data($filename);
    if (isset(
$exif['Orientation']))
       
$orientation $exif['Orientation'];
} else if (
preg_match('@\x12\x01\x03\x00\x01\x00\x00\x00(.)\x00\x00\x00@'file_get_contents($filename), $matches)) {
   
$orientation ord($matches[1]);
}
?>
2015-05-26 23:56:14
http://php5.kiev.ua/manual/ru/function.exif-read-data.html
Problem with "S�o�m�e� �T�e�x�t��" on value(s), exif[IFD0][Title] for example, when they were edited trough windows right click properties and then got read with the read_exif_data() function. 
try:

$exif_['IFD0']['Title']=mb_convert_encoding($exif_['IFD0']['Title'],"auto","byte2le");

works on UTF-8 and so.

//
// outputs all available character encodings and prints on screen
// foreach(mb_list_encodings() as $chr)
//  {$test[$chr]=mb_convert_encoding($image[IFD0][Title],'auto',$chr);}
//  exit(print_r($test));
//
2015-10-18 03:42:21
http://php5.kiev.ua/manual/ru/function.exif-read-data.html
Автор:
<?php

// auto rotates an image file based on exif data from camera
// if destination file is specified then it saves file there, otherwise it will display it to user
// note that images already at normal orientation are skipped (when exif data Orientation = 1)

if(!function_exists("gd_auto_rotate")){
    function 
gd_auto_rotate($original_file$destination_file=NULL){
       
       
$original_extension strtolower(pathinfo($original_filePATHINFO_EXTENSION));
        if(isset(
$destination_file) and $destination_file!=''){
           
$destination_extension strtolower(pathinfo($destination_filePATHINFO_EXTENSION));
        }
       
       
// try to auto-rotate image by gd if needed (before editing it)
        // by imagemagik it has an easy option
       
if(function_exists("exif_read_data")){
           
           
$exif_data exif_read_data($original_file);
           
$exif_orientation $exif_data['Orientation'];
           
           
// value 1 = normal ?! skip it ?!
           
           
if($exif_orientation=='3'  or $exif_orientation=='6' or $exif_orientation=='8'){
               
               
$new_angle[3] = 180;
               
$new_angle[6] = -90;
               
$new_angle[8] = 90;
               
               
// load the image
               
if($original_extension == "jpg" or $original_extension == "jpeg"){
                   
$original_image imagecreatefromjpeg($original_file);
                }
                if(
$original_extension == "gif"){
                   
$original_image imagecreatefromgif($original_file);
                }
                if(
$original_extension == "png"){
                   
$original_image imagecreatefrompng($original_file);
                }
               
               
$rotated_image imagerotate($original_image$new_angle[$exif_orientation], 0);
               
               
// if no destination file is set, then show the image
               
if(!$destination_file){
                   
header('Content-type: image/jpeg');
                   
imagejpeg($rotated_imageNULL100);
                }
                       
               
// save the smaller image FILE if destination file given
               
if($destination_extension == "jpg" or $destination_extension=="jpeg"){
                   
imagejpeg($rotated_image$destination_file,100);
                }
                if(
$destination_extension == "gif"){
                   
imagegif($rotated_image$destination_file);
                }
                if(
$destination_extension == "png"){
                   
imagepng($rotated_image$destination_file,9);
                }
               
               
imagedestroy($original_image);
               
imagedestroy($rotated_image);
           
            }
        }
    }
}

?>
2017-10-09 15:34:46
http://php5.kiev.ua/manual/ru/function.exif-read-data.html
The example provided for displaying exif array content is not working in recent version because not all entry values are of array type. 

This is an alternative echo loop:

 <?php
echo "test1.jpg:<br />\n";
$exif exif_read_data('tests/test1.jpg''IFD0');
echo 
$exif===false "No header data found.<br />\n" "Image contains headers<br />\n";

$exif exif_read_data('tests/test2.jpg'0true);
echo 
"test2.jpg:<br />\n";
foreach (
$exif as $key => $section) {
   
    if (!
is_array ($section)) {
        echo 
"$key$section<br />\n";
    } else {
        foreach (
$section as $name => $val) {
            echo 
"$key.$name$val<br />\n";
        }
    }

}
?>
2019-02-09 14:12:49
http://php5.kiev.ua/manual/ru/function.exif-read-data.html
Автор:
The following code:
<?php
$data 
exif_read_data('foo.jpg');
var_dump($data['Keywords']);
?>
produces string(15) "???????????????"

Adding
<?php
ini_set
('exif.decode_unicode_motorola''UCS-2LE');
?>
before the call to exif_red_data produces
string(15) "landscape;;field"
2019-10-05 23:44:15
http://php5.kiev.ua/manual/ru/function.exif-read-data.html
this error happens when get jpeg file exif information

exif_read_data(): Error reading from file: got=x3FFA(=16378) != itemlen-2=x4325(=17189)
2023-12-23 14:19:46
http://php5.kiev.ua/manual/ru/function.exif-read-data.html

    Поддержать сайт на родительском проекте КГБ