©
This document uses PHP Chinese website manual Release
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
exif_read_data — 从 JPEG 或 TIFF 文件中读取 EXIF 头信息
$filename
[, string $sections
= NULL
[, bool $arrays
= false
[, bool $thumbnail
= false
]]] )exif_read_data() 函数从 JPEG 或 TIFF 图像文件中读取 EXIF 头信息。这样就可以读取数码相机产生的元数据。
EXIF 头信息往往存在于数码相机生成的 JPEG/TIFF 图像中,但不幸的是每个数码相机制造商的标记都不同,因此(编写代码时)不能依赖于某个特定的 Exif 头信息。
Height 和 Width 是用和 getimagesize() 一样的方法计算的,因此它们的值不能是任何返回的头信息的部分。此外 html 是一个 height/width 的文本字符串可以用于普通的 HTML 中。
当一个 Exif 头信息包含有一个 Copyright 时注意它本身可以包含两个值。解决方案和 Exif 2.10 标准不一致,COMPUTED 区段会同时返回 Copyright.Photographer 和 Copyright.Editor,但是 IFD0 区段则包含有一个字节数组用 NULL 字符分隔开两个项目。或者只有第一项如果数据类型错误的话(Exif 的正常行为)。COMPUTED 也会包含 Copyright,要么是原始的版权字符串,要么是逗号分隔的摄像与编辑的版权信息。
UserComment 标记和 Copyright 有同样的问题。它也可以存储两个值,第一个是使用的编码方式,第二个是其值本身。如果这样则 IFD0 区段仅包含编码方式或者一个字节数组。COMPUTED 区段将存储两个值到 UserCommentEncoding 和 UserComment。UserComment 在两种情况下都可用因此应该优先使用它而不是 IFD0 区段中的该值。
exif_read_data() 还会根据 EXIF 规范(» http://exif.org/Exif2-2.PDF,第 20 页)来验证 EXIF 数据。
Note:
Windows ME/XP 在连接到数码相机时能清除掉 Exif 头信息。
filename
被读取的图像文件名。不能是 URL。
sections
是需要存在于文件中的逗号分隔的区段列表用来产生结果数组。如果未找到所请求的区段则返回值为
FALSE
。
FILE | FileName, FileSize, FileDateTime, SectionsFound |
COMPUTED | html,Width,Height,IsColor,可能有更多其它的。Height 和 Width 是用和 getimagesize() 一样的方法计算的,因此它们的值不能是任何返回的头信息的部分。此外 html 是一个 height/width 的文本字符串可以用于普通的 HTML 中。 |
ANY_TAG | 任何包含有标记的信息,例如 IFD0,EXIF,... |
IFD0 | 所有 IFD0 的标记数据。在标准的图像文件中这包含了图像大小及其它。 |
THUMBNAIL | 如果有第二个 IFD,文件应该包含有缩略图。所有有关嵌入缩略图的标记信息都存储在本区。 |
COMMENT | JPEG 图像的注释头信息。 |
EXIF | EXIF 区段是 IFDO 的子区,包含有图像的更多详细信息。大多数内容都是数码相机相关的。 |
arrays
指定了是否每个区段都成为一个数组。sections
COMPUTED,THUMBNAIL
和COMMENT
区段总是成为数组,因为它们里面包含的名字和其它区段冲突。
thumbnail
当设定为 TRUE
时,读取缩略图本身。否则只读取标记数据。
返回一个关联数组,键名是头信息名,值为与其相应的值。如果没有可供返回的数据, exif_read_data()
将返回 FALSE
。
版本 | 说明 |
---|---|
4.3.0 | 可以读取所有嵌入的 IFD 数据,包括数组(也返回数组)。此外嵌入的缩略图的大小包括在 THUMBNAIL 子数组中并且 exif_read_data() 可以将缩略图按照 TIFF 格式返回。最后,不再有返回值最大长度的限制了(直到达到内存限定)。 |
4.3.0 | 如果 PHP 有 mbstring 支持,则用户注释可以自动改变编码。此外,如果用户注释使用 Unicode 或 JIS 编码,将会根据 EXIF 在 php.ini 中的 设置被自动改变。 |
4.3.0 | 如果图像包含任何 IFD0 数据,则 COMPUTED 会包含有一项 ByteOrderMotorola,对于 little-endian (intel) 字节顺序,其值为 0,对于 big-endian (motorola) 字节顺序,其值为 1。此外,COMPUTED 和 UserComment 在数据类型出错时也不再仅包含第一个版权条目。 |
Example #1 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 />\n" ;
$exif = exif_read_data ( 'tests/test2.jpg' , 0 , true );
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
[#1] b at asdflolinternet dot de [2015-10-18 00:42:21]
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));
//
[#2] Eion Robb [2015-05-26 20:56:14]
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]);
}
?>
[#3] Ray.Paseur Sometimes Uses Gmail [2015-01-13 14:13:12]
The now-defunct EXIF web site referenced above is archived here:
http://web.archive.org/web/20131018091152/http://exif.org/Exif2-2.PDF
[#4] sakib dot farid at gmail dot com [2014-10-23 09:33:54]
Thanks to chadsmith729 at gmail dot com for the orientation fix.
Just small error, it should be
case 8, rotate -90
case 6, rotate 90
[#5] Shiva [2014-09-10 09:56:37]
Hi all,
I used this function for reading exif data from images. Turns out that if some metadata fields are empty then the function reports unidentified tags with garbage data.
Hope this helps someone.
[#6] iam at thatguy dot co dot za [2013-12-20 08:15:53]
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;
}
?>
[#7] Clive dot Moore at ma-design dot com [2013-12-06 09:19:08]
Following up on darkain at darkain dot com script for grabbing the ShutterSpeedValue from exif data...
@http://php.net/manual/en/function.exif-read-data.php
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';
};
[#8] hoangvu4000 at gmail dot com [2013-05-26 17:47:40]
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);
}
?>
[#9] kurt at mandella dot biz [2013-04-25 06:34:14]
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??????Cl???? ???x? ???????????(?(?T?U???d?C~??????? ?????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);
}
[#10] chadsmith729 at gmail dot com [2012-12-20 13:34:30]
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.
[#11] drpain at webster dot org dot za [2012-03-13 11:40:33]
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.
[#12] michael [at[ thisiswilson [dot[ com [2008-11-20 21:01:23]
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/
[#13] lincolnzsilva at gmail dot com [2008-09-26 16:57:07]
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'];
?>
[#14] darkain at darkain dot com [2008-07-28 23:33:47]
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);
}
?>
[#15] wdierkes at 5dollarwhitebox dot org [2007-09-04 18:20:39]
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.
[#16] mafo at mafo removethis dot sk [2007-08-08 01:57:31]
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)
[#17] [2007-03-05 11:50:54]
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.
[#18] gimpster at gimpster dot com [2004-05-17 16:24:06]
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/
[#19] noway at nowaysoft dot com [2004-02-23 20:44:12]
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