downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

exif_tagname> <exif_imagetype
[edit] Last updated: Fri, 24 Feb 2012

view this page in

exif_read_data

(PHP 4 >= 4.2.0, PHP 5)

exif_read_dataLê os cabeçalhos EXIF de imagens JPEG ou TIFF. Deste modo você poderá ler meta dados gerados por camêras digitais.

Descrição

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

A função exif_read_data() lê os cabeçalhos EXIF de um arquivo de imagem JPEG ou TIFF. Retorna uma matriz associativa aonde os índices são os nomes dos cabeçalhos e os valores são os valores associados a estes cabeçalhos. Se nenhum dado puder ser retornado, então o resultado é FALSE.

filename é o nome do arquivo a ser lido. Este não pode ser um URL.

sections é uma lista das seções separadas por vírgula que devem estar presentes em um arquivo para produzir a matriz com os resultados. Se nenhuma das seções não puder ser encontradas, o valor de retorno será FALSE.

FILE FileName, FileSize, FileDateTime, SectionsFound
COMPUTED html, Width, Height, IsColor e algo mais se disponível.
ANY_TAG Qualquer informação que tenha uma Tag ex. IFD0, EXIF, ...
IFD0 Todas as informações marcadas de IFD0. Em arquivos de imagens normais isto contém o tamanho e assim por diante.
THUMBNAIL Supostamente um arquivo contém uma miniatura de tver um segundo IFD. Toda a informação marcada sobre esta miniatura embutida é guardada nesta seção.
COMMENT Cabeçalhos de comentários de imagens JPEG.
EXIF A seção EXIF é uma subseção de IFD0. Ela contém informação mais detalhada sobre uma imagem. A maioria destas é relacionada a camêras digitais.

arrays especifica quando cada seção se torna ou não uma matriz. As seções COMPUTED, THUMBNAIL e COMMENT sempre se tornam matrizes já que podem conter valores os quais os nomes conflitem com outras seções.

thumbnail quando ler ou não a miniatura em sí ou apenas os dados marcados.

Nota:

Cabeçalhos Exif tendem a estar presentes em imagens JPEG/TIFF geradas por camêras digitais, mas infelizmente, cada fabricante de camêra digital tem uma idéia diferente de como marcar as suas imagens, então você não pode confiar em um cabeçalho EXIF especifico estar presente.

Windows ME/XP podem limpar os cabeçalhos Exif quando estiverem conectados a uma camêra. Maiores informações estão disponíveis em » http://www.canon.co.jp/Imaging/NOTICE/011214-e.html.

Exemplo #1 Exemplo exif_read_data()

<?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 />";

$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";
    }
}
?>

A primeira chamada falha porque a imagem não tem informações no cabeçalho.

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

Nota:

Se a imagem conter qualquer dado IFDO então COMPUTED contém a entrada ByteOrderMotorola a qual é 0 para little-endian (intel) e 1 para big-endian (motorola), relativo a ordem dos byte. Isto foi adicionado no PHP 4.3.

Quando um cabeçalho Exif contém uma nota de Copyright pode conter dois valores. Como a solução é inconsistente no padrão Exif 2.10 a seção COMPUTED irá retornar ambas as entradas Copyright.Photographer e Copyright.Editor enquando as seções IFD0 contém uma matriz de byte onde o caractere NULL separa as duas entradas. Ou apenas a primeira entrada se o tipo de dados estiver errado (funcionamento normal do Exif). O COMPUTED irá conter também uma entrada Copyright a qual será a string original do copyright ou uma lista separada por vírgula da foto e do copyright do editor.

Nota:

A tag UserComment tem o mesmo problema que a tag de Copyright. Ela pode guardar dois valores, primeiro a codificação usada e em segundo o valor em sí. Então a seção IFD contém somente a codificação ou uma matriz de byte. A seção COMPUTED irá guardar ambos nas entradas UserCommentEncoding e UserComment. A entrada UserComment esta disponível em ambos os casos então deve ser usada em preferencia ao valor da seção IFD0.

Se o comentário do usuário usar Unicode ou codificação JIS e o módulo mbstring estiver disponível esta codificação será automaticamente modificada de acordo com a definição do exif que estiver no php.ini. Isto foi adicionado no PHP 4.3.

Nota:

Height e Width(altura e largura) são compudados da mesma maneira que getimagesize() faz, então seus valores não devem ser parte de nenhum cabeçalhor retornado. Também html é uma height/width de textopara ser usado dentro de um HTML normal.

Nota:

A partir do PHP 4.3 a função pode ler dodos os dados IFD embutidos, incluindo matrizes (retornadas assim). Também o tamanho da miniatura embutida retornada na submatriz THUMBNAIL e a função exif_read_data() pode retornar miniaturas no formato TIFF. Último, mas não menos importante, não existe limite de tamanho para os valores retornados (não enquanto o limite de memória não é atingido).

Nota: Esta função esta disponível apenas no PHP 4 compilado usando --enable-exif . Sua funcionalidade e comportamento mudou no PHP 4.2. Versões anteriores são muito instaveis. A partir do PHP 4.3 comentários do usuário podem mudar a codificação automaticamente se o PHP 4 foi compilado usando --enable-mbstring . Esta função não requer a biblioteca de imagem GD. Veja também exif_thumbnail() e getimagesize().



exif_tagname> <exif_imagetype
[edit] Last updated: Fri, 24 Feb 2012
 
add a note add a note User Contributed Notes exif_read_data
drpain at webster dot org dot za 13-Mar-2012 05:40
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.
michael [at[ thisiswilson [dot[ com 20-Nov-2008 02:01
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/
lincolnzsilva at gmail dot com 26-Sep-2008 10:57
Get some EXIFs fields (easy way):

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

       
$exif_iso = exif_read_data ( $_FILES['photo']['tmp_name'] ,'EXIF' ,0 );
       
$eiso = $exif_iso['ISOSpeedRatings'];
               
       
$exif_date = exif_read_data ( $_FILES['photo']['tmp_name'] ,'IFD0' ,0 );
       
$edate = $exif_date['DateTime'];
?>
darkain at darkain dot com 28-Jul-2008 05:33
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($value, 0, $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(1 / $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);
}
?>
wdierkes at 5dollarwhitebox dot org 04-Sep-2007 12:20
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.
mafo at mafo removethis dot sk 07-Aug-2007 07:57
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($public, 2);
               
$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($public, 90);
        break;
    }

?>

$image->rotateImage() is inspired by example of http://php.net/manual/en/function.imagerotate.php
$image->flipImage() is inspired by http://php.net/manual/en/function.imagecopy.php#42803 (thank you)
05-Mar-2007 04:50
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', 0, true);
    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.
09-Aug-2004 04:11
I've just released the "PHP JPEG Metadata Toolkit" which allows reading, writing and displaying of EXIF information, and does not need the --enable-exif option in PHP4.

It has been tested on 466 different models of digital cameras!

It can decode the following EXIF makernotes:
Agfa, Canon, Casio, Contax, Epson, Fujifilm, Konica, Minolta, Kyocera, Nikon, Olympus, Panasonic, Pentax (Asahi), Ricoh and Sony

Additionaly it can decode IPTC, XMP, Photoshop IRB and many other types of JPEG metadata

Try it out, and download it at:
http://www.ozhiker.com/electronics/pjmt/index.html
gimpster at gimpster dot com 17-May-2004 10:24
I've written a library in pure PHP5 for editing EXIF tags. It deals with both reading and writing EXIF tags, and can be downloaded from http://pel.sourceforge.net/
noway at nowaysoft dot com 23-Feb-2004 01:44
Exif is very unstable under php4.1.2

If you have some problem, (the function didnt return anything, like a blocking call) try this:

$file = './image.jpg';
getimagesize ( $file , $info);

$exif = array();
if (isset($info)) {
    foreach($info as $key => $val) {
        if ($key != 'APP1') { $exif = read_exif_data($file); break; }
    }
}

-- Sharp
pekka at photography-on-the dot net 19-Nov-2003 10:50
For reading EXIF from XMP data embedded by Adobe Photoshop CS, see  http://www.photography-on-the.net/ee/beta/cs_xmp_to_exif.php

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