static function rotate_item($item) { // Only try to rotate photos based on EXIF if ($item->is_photo() && $item->mime_type == "image/jpeg") { require_once MODPATH . "exif/lib/exif.php"; $exif_raw = read_exif_data_raw($item->file_path(), false); if (isset($exif_raw['ValidEXIFData'])) { $orientation = $exif_raw["IFD0"]["Orientation"]; $degrees = 0; if ($orientation == '3: Upside-down') { $degrees = 180; } else { if ($orientation == '8: 90 deg CW') { $degrees = -90; } else { if ($orientation == '6: 90 deg CCW') { $degrees = 90; } } } if ($degrees) { $tmpfile = tempnam(TMPPATH, "rotate"); gallery_graphics::rotate($item->file_path(), $tmpfile, array("degrees" => $degrees)); $item->set_data_file($tmpfile); $item->save(); unlink($tmpfile); } } } return; }
/** * This callback method extract exif data from image and sets fields as customized in settings. * * @param Model $model Object of model * * @return boolean Return method's status */ function beforeValidate(&$model) { // If photo is uploaded if (isset($model->data[$model->name][$this->settings[$model->name]['filename']]) && 0 == $model->data[$model->name][$this->settings[$model->name]['filename']]['error']) { // Name of image file //$filename = $model->data[$model->name][$this->settings[$model->name]['filename']]['tmp_name']; $filename = WWW_ROOT . 'files' . DS . 'pictures' . DS . $model->data[$model->name][$this->settings[$model->name]['filename']]; // Read exif data from file $exif = read_exif_data_raw($filename, 0); // If exif data contains maker note then set it empty if (isset($exif['SubIFD']['MakerNote'])) { $exif['SubIFD']['MakerNote'] = ''; } // Create new sanitize object and clean exif data Sanitize::clean($exif); if (isset($exif['SubIFD']['DateTimeOriginal']) && isset($this->settings[$model->name]['exifDateField'])) { $model->data[$model->name][$this->settings[$model->name]['exifDateField']] = date($this->settings[$model->name]['exifDateFormat'], strtotime($exif['SubIFD']['DateTimeOriginal'])); } // If the GPS Latitude and Longitude is set then add to proper fields if (isset($exif['GPS'])) { if (isset($this->settings[$model->name]['gpsLattitudeField'])) { $model->data[$model->name][$this->settings[$model->name]['gpsLattitudeField']] = $exif['GPS']['Latitude']; } if (isset($this->settings[$model->name]['gpsLattitudeField'])) { $model->data[$model->name][$this->settings[$model->name]['gpsLongitudeField']] = $exif['GPS']['Longitude']; } } // Store serialized exif data in model's data if (isset($this->settings[$model->name]['exifField'])) { $model->data[$model->name][$this->settings[$model->name]['exifField']] = serialize($exif); } } return true; }
public function read() { $exif = array(); $exif_raw = read_exif_data_raw($this->filename, false); $this->exif_raw = $exif_raw; if (isset($exif_raw['ValidEXIFData'])) { foreach ($this->exif_vars as $field => $exif_var) { switch (count($exif_var)) { case 1: if (array_key_exists($exif_var[0], $exif_raw)) { $exif[$field] = $exif_raw[$exif_var[0]]; } break; case 2: if (array_key_exists($exif_var[0], $exif_raw) && array_key_exists($exif_var[1], $exif_raw[$exif_var[0]])) { $exif[$field] = $exif_raw[$exif_var[0]][$exif_var[1]]; } break; case 3: if (array_key_exists($exif_var[0], $exif_raw) && array_key_exists($exif_var[1], $exif_raw[$exif_var[0]]) && array_key_exists($exif_var[2], $exif_raw[$exif_var[0]][$exif_var[1]])) { $exif[$field] = $exif_raw[$exif_var[0]][$exif_var[1]][$exif_var[2]]; } break; } } } $this->exif = $exif; return $exif; }
function serialize_exif($uploaded_file) { //$exif_tmp = read_exif_data_raw($_FILES['upload_file']['tmp_name'],0); $exif_tmp = read_exif_data_raw($uploaded_file, 0); $flat_exif_tmp = flatten_array($exif_tmp); if (in_array("DataDumpMakerNote", $flat_exif_tmp)) { // this field is set to empty because it causes trouble $flat_exif_tmp['DataDumpMakerNote'] = NULL; } //search for all "unknown:*" fields because like the MakerNote it causes trouble. // Thanks to erdbeerbaum for pointing this out. foreach ($flat_exif_tmp as $key => $value) { $pos = strpos($key, "unknown:"); if ($pos === 0) { $flat_exif_tmp[$key] = NULL; } } foreach ($flat_exif_tmp as $key => $value) { $flat_exif_tmp[$key] = trim($value); } $exif_info = serialize($flat_exif_tmp); // we need to escape the string before saving it to the db $exif_info = mysql_real_escape_string($exif_info); return $exif_info; }
function exif_parse_file($filename) { global $CONFIG, $lang_picinfo; //String containing all the available exif tags. $exif_info = "AFFocusPosition|Adapter|ColorMode|ColorSpace|ComponentsConfiguration|CompressedBitsPerPixel|Contrast|CustomerRender|DateTimeOriginal|DateTimedigitized|DigitalZoom|DigitalZoomRatio|ExifImageHeight|ExifImageWidth|ExifInteroperabilityOffset|ExifOffset|ExifVersion|ExposureBiasValue|ExposureMode|ExposureProgram|ExposureTime|FNumber|FileSource|Flash|FlashPixVersion|FlashSetting|FocalLength|FocusMode|GainControl|IFD1Offset|ISOSelection|ISOSetting|ISOSpeedRatings|ImageAdjustment|ImageDescription|ImageSharpening|LightSource|Make|ManualFocusDistance|MaxApertureValue|MeteringMode|Model|NoiseReduction|Orientation|Quality|ResolutionUnit|Saturation|SceneCaptureMode|SceneType|Sharpness|Software|WhiteBalance|YCbCrPositioning|xResolution|yResolution"; if (!is_readable($filename)) { return false; } $size = @getimagesize($filename); if ($size[2] != 2) { return false; } // Not a JPEG file $exifRawData = explode("|", $exif_info); $exifCurrentData = explode("|", $CONFIG['show_which_exif']); //Let's build the string of current exif values to be shown $showExifStr = ""; foreach ($exifRawData as $key => $val) { if ($exifCurrentData[$key] == 1) { $showExifStr .= "|" . $val; } } //Check if we have the data of the said file in the table $sql = "SELECT * FROM {$CONFIG['TABLE_EXIF']} " . "WHERE filename='" . addslashes($filename) . "'"; $result = cpg_db_query($sql); if (mysql_num_rows($result) > 0) { $row = mysql_fetch_array($result); mysql_free_result($result); $exifRawData = unserialize($row["exifData"]); } else { // No data in the table - read it from the image file $exifRawData = read_exif_data_raw($filename, 0); // Insert it into table for future reference $sql = "INSERT INTO {$CONFIG['TABLE_EXIF']} " . "VALUES ('" . addslashes($filename) . "', '" . addslashes(serialize($exifRawData)) . "')"; $result = cpg_db_query($sql); } $exif = array(); if (is_array($exifRawData['IFD0'])) { $exif = array_merge($exif, $exifRawData['IFD0']); } if (is_array($exifRawData['SubIFD'])) { $exif = array_merge($exif, $exifRawData['SubIFD']); } if (is_array($exifRawData['SubIFD']['MakerNote'])) { $exif = array_merge($exif, $exifRawData['SubIFD']['MakerNote']); } $exif['IFD1OffSet'] = $exifRawData['IFD1OffSet']; $exifParsed = array(); foreach ($exif as $key => $val) { if (strpos($showExifStr, "|" . $key) && isset($val)) { $exifParsed[$lang_picinfo[$key]] = $val; //$exifParsed[$key] = $val; } } ksort($exifParsed); return $exifParsed; }
static function extract($item) { $keys = array(); // Only try to extract EXIF from photos if ($item->is_photo() && $item->mime_type == "image/jpeg") { $data = array(); require_once MODPATH . "exif/lib/exif.php"; $exif_raw = read_exif_data_raw($item->file_path(), false); if (isset($exif_raw['ValidEXIFData'])) { foreach (self::_keys() as $field => $exifvar) { if (isset($exif_raw[$exifvar[0]][$exifvar[1]])) { $value = $exif_raw[$exifvar[0]][$exifvar[1]]; if (function_exists("mb_detect_encoding") && mb_detect_encoding($value) != "UTF-8") { $value = utf8_encode($value); } $keys[$field] = Input::clean($value); if ($field == "DateTime") { $time = strtotime($value); if ($time > 0) { $item->captured = $time; } } else { if ($field == "Caption" && !$item->description) { $item->description = $value; } } } } } $size = getimagesize($item->file_path(), $info); if (is_array($info) && !empty($info["APP13"])) { $iptc = iptcparse($info["APP13"]); foreach (array("Keywords" => "2#025", "Caption" => "2#120") as $keyword => $iptc_key) { if (!empty($iptc[$iptc_key])) { $value = implode(" ", $iptc[$iptc_key]); if (function_exists("mb_detect_encoding") && mb_detect_encoding($value) != "UTF-8") { $value = utf8_encode($value); } $keys[$keyword] = Input::clean($value); if ($keyword == "Caption" && !$item->description) { $item->description = $value; } } } } } $item->save(); $record = ORM::factory("exif_record")->where("item_id", "=", $item->id)->find(); if (!$record->loaded()) { $record->item_id = $item->id; } $record->data = serialize($keys); $record->key_count = count($keys); $record->dirty = 0; $record->save(); }
/** * Provides an [not] error protected read of image EXIF/IPTC data for PHP 4 * * @param string $path image path * @return array */ function read_exif_data_protected($path) { if (DEBUG_EXIF) { debugLog("Begin read_exif_data_protected({$path})"); } $rslt = read_exif_data_raw($path, false); if (DEBUG_EXIF) { debugLog("End read_exif_data_protected({$path})"); } return $rslt; }
static function rotate_item($item) { require_once MODPATH . 'autorotate/lib/pel/PelDataWindow.php'; require_once MODPATH . 'autorotate/lib/pel/PelJpeg.php'; require_once MODPATH . 'autorotate/lib/pel/PelTiff.php'; // Only try to rotate photos based on EXIF if ($item->is_photo() && $item->mime_type == "image/jpeg") { require_once MODPATH . "exif/lib/exif.php"; $exif_raw = read_exif_data_raw($item->file_path(), false); if (isset($exif_raw['ValidEXIFData'])) { $orientation = $exif_raw["IFD0"]["Orientation"]; $degrees = 0; if ($orientation == '3: Upside-down') { $degrees = 180; } else { if ($orientation == '8: 90 deg CW') { $degrees = -90; } else { if ($orientation == '6: 90 deg CCW') { $degrees = 90; } } } if ($degrees) { $tmpfile = tempnam(TMPPATH, "rotate"); gallery_graphics::rotate($item->file_path(), $tmpfile, array("degrees" => $degrees)); // Update EXIF info $data = new PelDataWindow(file_get_contents($tmpfile)); if (PelJpeg::isValid($data)) { $jpeg = $file = new PelJpeg(); $jpeg->load($data); $exif = $jpeg->getExif(); if ($exif !== null) { $tiff = $exif->getTiff(); $ifd0 = $tiff->getIfd(); $orientation = $ifd0->getEntry(PelTag::ORIENTATION); $orientation->setValue(1); file_put_contents($tmpfile, $file->getBytes()); } } $item->set_data_file($tmpfile); $item->save(); unlink($tmpfile); } } } return; }
/** * Provides an error protected read of image EXIF/IPTC data * * @param string $path image path * @return array * */ function read_exif_data_protected($path) { if (DEBUG_EXIF) { debugLog("Begin read_exif_data_protected({$path})"); $start = microtime(true); } try { $rslt = read_exif_data_raw($path, false); } catch (Exception $e) { debugLog("read_exif_data({$path}) exception: " . $e->getMessage()); $rslt = array(); } if (DEBUG_EXIF) { $time = microtime(true) - $start; debugLog(sprintf("End read_exif_data_protected({$path}) [%f]", $time)); } return $rslt; }
function exif_parse_file($filename, $pid) { global $CONFIG, $lang_picinfo; if (!is_readable($filename)) { return false; } $size = cpg_getimagesize($filename); if ($size[2] != 2) { return false; // Not a JPEG file } //String containing all the available exif tags. $exif_info = "AFFocusPosition|Adapter|ColorMode|ColorSpace|ComponentsConfiguration|CompressedBitsPerPixel|Contrast|CustomerRender|DateTimeOriginal|DateTimedigitized|DigitalZoom|DigitalZoomRatio|ExifImageHeight|ExifImageWidth|ExifInteroperabilityOffset|ExifOffset|ExifVersion|ExposureBiasValue|ExposureMode|ExposureProgram|ExposureTime|FNumber|FileSource|Flash|FlashPixVersion|FlashSetting|FocalLength|FocusMode|GainControl|IFD1Offset|ISOSelection|ISOSetting|ISOSpeedRatings|ImageAdjustment|ImageDescription|ImageSharpening|LightSource|Make|ManualFocusDistance|MaxApertureValue|MeteringMode|Model|NoiseReduction|Orientation|Quality|ResolutionUnit|Saturation|SceneCaptureMode|SceneType|Sharpness|Software|WhiteBalance|YCbCrPositioning|xResolution|yResolution"; $exif_names = explode("|", $exif_info); //Check if we have the data of the said file in the table $result = cpg_db_query("SELECT exifData FROM {$CONFIG['TABLE_EXIF']} WHERE pid = {$pid}"); if (mysql_num_rows($result) > 0) { $row = mysql_fetch_assoc($result); mysql_free_result($result); $exif = unserialize($row['exifData']); // Convert old EXIF data style to new one if (array_key_exists('Errors', $exif)) { $exif = cpg_exif_strip_data($exif, $exif_names); cpg_db_query("UPDATE {$CONFIG['TABLE_EXIF']} SET exifData = '" . addslashes(serialize($exif)) . "' WHERE pid = '{$pid}'"); } } else { // No data in the table - read it from the image file $exifRawData = read_exif_data_raw($filename, 0); $exif = cpg_exif_strip_data($exifRawData, $exif_names); // Insert it into table for future reference cpg_db_query("INSERT INTO {$CONFIG['TABLE_EXIF']} (pid, exifData) VALUES ({$pid}, '" . addslashes(serialize($exif)) . "')"); } $exifParsed = array(); $exifCurrentData = array_keys(array_filter(explode("|", $CONFIG['show_which_exif']))); foreach ($exifCurrentData as $i) { $name = $exif_names[$i]; if (isset($exif[$name])) { $exifParsed[$lang_picinfo[$name]] = $exif[$name]; } } ksort($exifParsed); return $exifParsed; }
function actionDefault() { // Get the ID from the URL $id = $_GET['id']; // Redirect if empty if (empty($id)) { die('No image selected.'); } // Get the post ID $item_id = substr($id, 5, strpos($id, '/') - 5); // Get the weblog item $item = @$this->weblog->getItemById($item_id); if (!$item) { die('Invalid image specified'); } // Get the image object $image = null; foreach ($item['images'] as $key => $i) { if ($i->relative_path == $id) { $image = $i; $image->previous = $key <= 0 ? null : $item['images'][$key - 1]; $image->next = $key >= sizeof($item['images']) - 1 ? null : $item['images'][$key + 1]; $image->num = $key + 1; $image->total_images = sizeof($item['images']); } } // Get the EXIF info for the image $result = read_exif_data_raw($image->getAbsolutePath(), false); $image->exif = array(); if (isset($result['IFD0'])) { $image->exif = array_merge($image->exif, $result['IFD0']); } if (isset($result['SubIFD'])) { $image->exif = array_merge($image->exif, $result['SubIFD']); } // Add them to the template $this->tpl->assign('item', $item); $this->tpl->assign('image', $image); // Display the template $this->display(); }
function thumb_caption_mgr($rowset) { global $CONFIG; foreach ($rowset as $ind => $val) { $pic_data = $rowset[$ind]; $pic_data['title'] = 'Filename - title: ' . $pic_data['filename'] . ', no: ' . $i; $fullpath = $CONFIG['fullpath'] . $val['filepath'] . $val['filename']; $exif = read_exif_data_raw($fullpath, true); $str = ''; foreach ($exif as $key => $val) { if ($key == 'SubIFD') { $str = substr($val['UserCommentOld'], 5); } } $pic_data['caption'] = ''; $pic_data['caption_text'] = $str; $pic_data['title'] = $str; $rowset[$ind] = $pic_data; } return $rowset; }
/** * Get associative array with exif info from a photo * * @param string $path Path to the photo. * @return array Exif info in associative array. */ function readExif($path) { //include and call the exifixer script require_once realpath(PHOTOQ_PATH . 'lib/exif/exif.php'); $fullexif = read_exif_data_raw($path, 0); //we now retain only the useful (whatever it means ;-) ) info $ifd0 = PhotoQExif::_filterUseless($fullexif['IFD0']); $subIfd = PhotoQExif::_filterUseless($fullexif['SubIFD']); $makerNote = $subIfd['MakerNote']; unset($subIfd['MakerNote']); $gps = PhotoQExif::_filterUseless($fullexif['GPS']); //bring all the arrays to single dimension $ifd0 = PhotoQHelper::flatten($ifd0); $subIfd = PhotoQHelper::flatten($subIfd); $makerNote = PhotoQHelper::flatten($makerNote); $gps = PhotoQHelper::flatten($gps); //and finally merge them into a single array $exif = array_merge($ifd0, $subIfd, $makerNote, $gps); //update discovered tags PhotoQExif::_discoverTags($exif); return $exif; }
static function extract($item) { $keys = array(); // Extract Latitude and Longitude from the image (if they exist). if ($item->is_photo() && $item->mime_type == "image/jpeg") { $data = array(); require_once MODPATH . "exif/lib/exif.php"; $exif_raw = read_exif_data_raw($item->file_path(), false); if (isset($exif_raw['ValidEXIFData'])) { foreach (self::_keys() as $field => $exifvar) { if (isset($exif_raw[$exifvar[0]][$exifvar[1]])) { $value = $exif_raw[$exifvar[0]][$exifvar[1]]; if (function_exists("mb_detect_encoding") && mb_detect_encoding($value) != "UTF-8") { $value = utf8_encode($value); } $keys[$field] = Input::clean($value); } } } } // If coordinates were extracted, save them to the database. if (isset($keys["Latitude"]) && isset($keys["Longitude"])) { $record = ORM::factory("exif_coordinate"); $record->item_id = $item->id; $record->latitude = str_replace(",", ".", $keys["Latitude"]); $record->longitude = str_replace(",", ".", $keys["Longitude"]); // Represent N/S/E/W as postive and negative numbers if (substr(strtoupper($keys["Latitude Reference"]), 0, 1) == "S") { $record->latitude = "-" . $record->latitude; } if (substr(strtoupper($keys["Longitude Reference"]), 0, 1) == "W") { $record->longitude = "-" . $record->longitude; } $record->save(); } }
function GetFileAngle($filename) { $result = read_exif_data_raw($filename, 0); $angle = 0; if (isset($result['IFD0']['Orientation'])) { if ($result['IFD0']['Orientation'] != "Normal (O deg)") { $angle_array = explode(" ", $result['IFD0']['Orientation']); if ($angle_array[2] == "CCW") $angle = 360 - $angle_array[0]; else $angle = $angle_array[0]; } } if (isset($result['IFD1']['Orientation'])) { if ($result['IFD1']['Orientation'] != "Normal (O deg)") { $angle_array = explode(" ", $result['IFD1']['Orientation']); if ($angle_array[2] == "CCW") $angle = 360 - $angle_array[0]; else $angle = $angle_array[0]; } else $angle = 0; } if ($angle >= 360) $angle = 0; return $angle; }
function getOriginationTimestamp($file) { $rawExifData = array(); $rawExifData = read_exif_data_raw($file, false); /* * The method name indicates, that we want the earliest date available for the img. * As of specs and practice with raw camera images and Adobe manipulated ones it seems, * that SubIFD.DateTimeOriginal and SubIFD.DateTimeDigitized indicate creation time: * both are set to shot time by cameras, scanners set only SubIFD.DateTimeDigitized. * Adobe sets IFD0.DateTime to the last modification date/time. So we prefer creation * dates. */ foreach (array('SubIFD.DateTimeOriginal', 'SubIFD.DateTimeDigitized', 'IFD0.DateTime') as $tag) { $value = getExifValue($rawExifData, explode('.', $tag)); if (isset($value)) { if (preg_match('#(\\d+):(\\d+):(\\d+)\\s+(\\d+):(\\d+):(\\d+)#', $value, $m)) { $time = mktime((int) $m[4], (int) $m[5], (int) $m[6], (int) $m[2], (int) $m[3], (int) $m[1]); } else { if (preg_match('#(\\d+)-(\\d+)-(\\d+)T(\\d+):(\\d+):(\\d+)(([-+])(\\d+)(:(\\d+))?)?#', $value, $m)) { $time = mktime((int) $m[4], (int) $m[5], (int) $m[6], (int) $m[2], (int) $m[3], (int) $m[1]); } } if (!empty($time)) { if (isset($m[8])) { $offset = ((int) $m[9] * 60 + (isset($m[11]) ? (int) $m[11] : 0)) * 60; if ($m[8] == '+') { $time += $offset; } else { $time -= $offset; } } return $time; } } } return null; }
<?php include_once 'exifer/exif.php'; // Takeing info about image... $imgPath = $gallery_root . $currentdir . $slide; $file_infos = pathinfo($imgPath); echo '<div class="imageData"><b>Image data</b><br />'; // ...and check if it's a valid jpg for exif data parsing if ($file_infos["extension"] == "jpeg" || $file_infos["extension"] == "jpg") { // Let's build exif array data $verbose = 0; $exif_array = read_exif_data_raw($imgPath, $verbose); echo '<table summary="displaying" border="0" class="imageDataTable" cellpadding="0" cellspacing="0">'; if (get_option('lg_exif_print_error') == "TRUE") { echo '<tr><th scope="row">Errors: </th><td>'; echo $exif_array['Errors']; echo '</td></tr>'; } if (get_option('lg_exif_valid_jpeg') == "TRUE") { echo '<tr><th scope="row">Valid Jpeg: </th><td>'; echo $exif_array['ValidJpeg']; echo '</td></tr>'; } if (get_option('lg_exif_valid_jfif_data') == "TRUE") { echo '<tr><th scope="row">Valid JFIF Data: </th><td>'; echo $exif_array['ValidJFIFData']; echo '</td></tr>'; } if (get_option('lg_exif_jfif_size') == "TRUE" || get_option('lg_exif_jfif_identifier') == "TRUE" || get_option('lg_exif_jfif_extension_code') == "TRUE" || get_option('lg_exif_jfif_data') == "TRUE") { echo '<tr><th scope="row">JFIF Data: </th><td>'; echo '<table summary="Image SubData" border="0" cellpadding="0" cellspacing="0" class="imageSubTable">';
<HTML><BODY> <?php //This page just shows how you would use my library. //Look in exif.php for more information //Enjoy. include 'exif.php'; $path = "image.jpg"; $verbose = 0; $result = read_exif_data_raw($path, $verbose); echo "<PRE>"; print_r($result); echo "</PRE>"; ?> </BODY></HTML>
function add_picture($album_id, $tmpname, $filename, $caption, $desc) { global $config; $filename_parts = explode(".", strrev($filename), 2); $filename_base = strrev($filename_parts[1]); $filename_ext = strrev($filename_parts[0]); $result = array('output' => '', 'picture_id' => false); $i = 0; $unique_filename_base = strtolower(sanitize_filename($filename_base)); // now get the name of the collection $sql = "SELECT c.path AS collection_path, c.id AS collection_id,\r\n\t\t\ta.path AS album_path, a.id AS album_id\r\n\t\t\tFROM " . TABLE_PREFIX . "albums a, " . TABLE_PREFIX . "collections c\r\n\t\t\tWHERE c.id = a.parent_id AND a.id = '{$album_id}'"; $sql_result = run_query($sql); $albumdata = mysql_fetch_assoc($sql_result); // this shouldn't happen in normal cases if (empty($albumdata)) { $result['errors'] .= plog_tr('No such album!'); return $result; } $dest_album_name = SmartStripSlashes($albumdata["album_path"]); $dest_collection_name = SmartStripSlashes($albumdata["collection_path"]); $create_path = $dest_collection_name . "/" . $dest_album_name; while (is_file('../images/' . $create_path . "/" . $unique_filename_base . "." . $filename_ext)) { $unique_filename_base = $filename_base . " (" . ++$i . ")"; } $final_filename = $unique_filename_base . "." . $filename_ext; // final fully qualified file name $final_fqfn = $config["basedir"] . 'images/' . $create_path . '/' . $final_filename; if (!makeDirs($config['basedir'] . 'images/' . $create_path, 0777)) { $result['errors'] .= sprintf(plog_tr('Could not create directory %s!'), $create_path); return $result; } if (is_uploaded_file($tmpname)) { if (!move_uploaded_file($tmpname, $final_fqfn)) { $result['errors'] .= sprintf(plog_tr('Could not move uploaded file! %s to %s'), $tmpname, $final_fqfn); return $result; } } else { if (!rename($tmpname, $final_fqfn)) { $result['errors'] .= sprintf(plog_tr('Could not move file! %s to %s'), $tmpname, $final_fqfn); return $result; } } @unlink($tmpname); $res = chmod($final_fqfn, 0755); // Get the EXIF data. require_once PLOGGER_DIR . "/lib/exifer1_5/exif.php"; $exif_raw = read_exif_data_raw($final_fqfn, false); $exif = array(); $exif["date_taken"] = isset($exif_raw["SubIFD"]["DateTimeOriginal"]) ? trim($exif_raw["SubIFD"]["DateTimeOriginal"]) : ''; $exif["camera"] = isset($exif_raw["IFD0"]["Make"]) && isset($exif_raw["IFD0"]["Model"]) ? trim($exif_raw["IFD0"]["Make"]) . " " . trim($exif_raw["IFD0"]["Model"]) : ''; $exif["shutter_speed"] = isset($exif_raw["SubIFD"]["ExposureTime"]) ? $exif_raw["SubIFD"]["ExposureTime"] : ''; $exif["focal_length"] = isset($exif_raw["SubIFD"]["FocalLength"]) ? $exif_raw["SubIFD"]["FocalLength"] : ''; $exif["flash"] = isset($exif_raw["SubIFD"]["Flash"]) ? $exif_raw["SubIFD"]["Flash"] : ''; $exif["aperture"] = isset($exif_raw["SubIFD"]["FNumber"]) ? $exif_raw["SubIFD"]["FNumber"] : ''; $picture_path = $create_path . "/" . $final_filename; $query = "INSERT INTO `" . TABLE_PREFIX . "pictures`\r\n\t\t(`parent_collection`,\r\n\t\t`parent_album`,\r\n\t\t`path`,\r\n\t\t`date_modified`,\r\n\t\t`date_submitted`,\r\n\t\t`allow_comments`,\r\n\t\t`EXIF_date_taken`,\r\n\t\t`EXIF_camera`,\r\n\t\t`EXIF_shutterspeed`,\r\n\t\t`EXIF_focallength`,\r\n\t\t`EXIF_flash`,\r\n\t\t`EXIF_aperture`,\r\n\t\t`caption`,\r\n\t\t`description`)\r\n\t\tVALUES\r\n ('" . $albumdata['collection_id'] . "',\r\n '" . $albumdata['album_id'] . "','" . mysql_escape_string($picture_path) . "',\r\n NOW(),\r\n NOW(),\r\n 1,\r\n '" . mysql_escape_string($exif["date_taken"]) . "',\r\n '" . mysql_escape_string($exif["camera"]) . "',\r\n '" . mysql_escape_string($exif["shutter_speed"]) . "',\r\n '" . mysql_escape_string($exif["focal_length"]) . "',\r\n '" . mysql_escape_string($exif["flash"]) . "',\r\n '" . mysql_escape_string($exif["aperture"]) . "',\r\n '" . mysql_escape_string($caption) . "',\r\n '" . mysql_escape_string($desc) . "')"; $sql_result = run_query($query); $result['output'] .= sprintf(plog_tr('Your photo (%s) was uploaded successfully.'), $filename); $result['picture_id'] = mysql_insert_id(); // let's generate the thumbnail and the large thumbnail right away. // this way, the user won't see any latency from the thumbnail generation // when viewing the gallery for the first time // this also helps with the image pre-loading problem introduced // by a javascript slideshow. $thumbpath = generate_thumb($picture_path, $result['picture_id'], THUMB_SMALL); #$thumbpath = generate_thumb($picture_path, $result['picture_id'],THUMB_LARGE); return $result; }
function add_picture($album_id, $tmpname, $filename, $caption, $desc, $allow_comm = 1) { global $config, $PLOGGER_DBH; $filename_parts = explode('.', strrev($filename), 2); $filename_base = strrev($filename_parts[1]); $filename_ext = strtolower(strrev($filename_parts[0])); $ext_array = array('jpg', 'jpeg', 'gif', 'png', 'bmp'); $result = array('output' => '', 'errors' => '', 'picture_id' => false); $i = 0; $unique_filename_base = strtolower(sanitize_filename(SmartStripSlashes($filename_base), true)); // Now get the name of the collection $sql = "SELECT c.path AS collection_path, c.id AS collection_id,\n\t\t\ta.path AS album_path, a.id AS album_id\n\t\t\tFROM " . PLOGGER_TABLE_PREFIX . "albums a, " . PLOGGER_TABLE_PREFIX . "collections c\n\t\t\tWHERE c.id = a.parent_id AND a.id = '{$album_id}'"; $sql_result = run_query($sql); $albumdata = $sql_result->fetch(); // This shouldn't happen in normal cases if (empty($albumdata)) { $result['errors'] .= plog_tr('No such album!'); return $result; } $dest_album_name = SmartStripSlashes($albumdata['album_path']); $dest_collection_name = SmartStripSlashes($albumdata['collection_path']); $create_path = $dest_collection_name . '/' . $dest_album_name; foreach ($ext_array as $ext) { while (is_file($config['basedir'] . 'plog-content/images/' . $create_path . '/' . $unique_filename_base . '.' . $ext)) { $unique_filename_base = SmartStripSlashes($filename_base) . '-' . ++$i; } } $final_filename = sanitize_filename($unique_filename_base) . '.' . $filename_ext; // Final fully qualified filename $final_fqfn = $config['basedir'] . 'plog-content/images/' . $create_path . '/' . $final_filename; if (!makeDirs($config['basedir'] . 'plog-content/images/' . $create_path)) { $result['errors'] .= sprintf(plog_tr('Could not create directory %s!'), '<strong>' . $create_path . '</strong>'); return $result; } if (is_uploaded_file($tmpname)) { // If safe_mode enabled, open the permissions if the destination path if (is_safe_mode()) { $parent_path = $config['basedir'] . 'plog-content/images/' . $create_path; chmod_ftp($parent_path, 0777); } if (!move_uploaded_file($tmpname, $final_fqfn)) { $result['errors'] .= sprintf(plog_tr('Could not move uploaded file: %s to %s'), '<strong>' . $tmpname . '</strong>', '<strong>' . $final_fqfn . '</strong>'); } // If safe_mode enabled, close the permissions back down to the default if (is_safe_mode()) { chmod_ftp($parent_path); } } else { if (!move_this($tmpname, $final_fqfn)) { $result['errors'] .= sprintf(plog_tr('Could not move file: %s to %s'), '<strong>' . $tmpname . '</strong>', '<strong>' . $final_fqfn . '</strong>'); } } if (empty($result['errors'])) { if (is_file($tmpname)) { kill_file($tmpname); } $res = @chmod($final_fqfn, PLOGGER_CHMOD_FILE); // Get the exif data. require_once PLOGGER_DIR . 'plog-includes/lib/exifer1_7/exif.php'; $exif_raw = read_exif_data_raw($final_fqfn, false); $exif = array(); $exif['date_taken'] = isset($exif_raw['SubIFD']['DateTimeOriginal']) ? trim($exif_raw['SubIFD']['DateTimeOriginal']) : ''; $exif['camera'] = isset($exif_raw['IFD0']['Make']) && isset($exif_raw['IFD0']['Model']) ? trim($exif_raw['IFD0']['Make']) . ' ' . trim($exif_raw['IFD0']['Model']) : ''; $exif['shutter_speed'] = isset($exif_raw['SubIFD']['ExposureTime']) ? $exif_raw['SubIFD']['ExposureTime'] : ''; $exif['focal_length'] = isset($exif_raw['SubIFD']['FocalLength']) ? $exif_raw['SubIFD']['FocalLength'] : ''; $exif['flash'] = isset($exif_raw['SubIFD']['Flash']) ? $exif_raw['SubIFD']['Flash'] : ''; $exif['aperture'] = isset($exif_raw['SubIFD']['FNumber']) ? $exif_raw['SubIFD']['FNumber'] : ''; $exif['iso'] = isset($exif_raw['SubIFD']['ISOSpeedRatings']) ? $exif_raw['SubIFD']['ISOSpeedRatings'] : ''; $picture_path = $create_path . '/' . $final_filename; if (empty($exif['date_taken'])) { $newdate = 'NULL'; } else { $newdate = $PLOGGER_DBH->quote(preg_replace('/:/', '-', $exif['date_taken'], 2)); } $query = "INSERT INTO \"" . PLOGGER_TABLE_PREFIX . "pictures\"\n\t\t\t(\"parent_collection\",\n\t\t\t\"parent_album\",\n\t\t\t\"path\",\n\t\t\t\"date_modified\",\n\t\t\t\"date_submitted\",\n\t\t\t\"allow_comments\",\n\t\t\t\"exif_date_taken\",\n\t\t\t\"exif_camera\",\n\t\t\t\"exif_shutterspeed\",\n\t\t\t\"exif_focallength\",\n\t\t\t\"exif_flash\",\n\t\t\t\"exif_aperture\",\n\t\t\t\"exif_iso\",\n\t\t\t\"caption\",\n\t\t\t\"description\")\n\t\t\tVALUES\n\t\t\t\t('" . $albumdata['collection_id'] . "',\n\t\t\t\t'" . $albumdata['album_id'] . "',\n\t\t\t\t" . $PLOGGER_DBH->quote($picture_path) . ",\n\t\t\t\tNOW(),\n\t\t\t\tNOW(),\n\t\t\t\t" . intval($allow_comm) . ",\n\t\t\t\t" . $newdate . ",\n\t\t\t\t" . $PLOGGER_DBH->quote($exif['camera']) . ",\n\t\t\t\t" . $PLOGGER_DBH->quote($exif['shutter_speed']) . ",\n\t\t\t\t" . $PLOGGER_DBH->quote($exif['focal_length']) . ",\n\t\t\t\t" . $PLOGGER_DBH->quote($exif['flash']) . ",\n\t\t\t\t" . $PLOGGER_DBH->quote($exif['aperture']) . ",\n\t\t\t\t" . $PLOGGER_DBH->quote($exif['iso']) . ",\n\t\t\t\t" . $PLOGGER_DBH->quote($caption) . ",\n\t\t\t\t" . $PLOGGER_DBH->quote($desc) . ")"; $sql_result = run_query($query); $result['output'] .= sprintf(plog_tr('Your image %s was uploaded successfully.'), '<strong>' . $filename . '</strong>'); $serialobj = getSerialObj('pictures'); $result['picture_id'] = $PLOGGER_DBH->lastInsertID($serialobj); // Let's generate the thumbnail and the large thumbnail right away. // This way, the user won't see any latency from the thumbnail generation // when viewing the gallery for the first time // This also helps with the image pre-loading problem introduced // by a javascript slideshow. $thumbpath = generate_thumb($picture_path, $result['picture_id'], THUMB_SMALL); //$thumbpath = generate_thumb($picture_path, $result['picture_id'],THUMB_LARGE); } return $result; }
/** * Provides an error protected read of image EXIF/IPTC data * (requires PHP version 5 to protect the read) * * @param string $path image path * @return array */ function read_exif_data_protected($path) { if (version_compare(PHP_VERSION, '5.0.0') === 1) { eval(' try { $rslt = read_exif_data_raw($path, false); } catch (Exception $e) { $rslt = array(); }'); return $rslt; } else { return read_exif_data_raw($path, false); } }
/** * This function inserts EXIF data embedded by cameras. * * @global OBJECT $db * @global OBJECT $cbphoto * @param ARRAY $photo * @return INT */ function insert_exif_data($photo) { global $db, $cbphoto; if (!is_array($photo)) { $ph = $cbphoto->get_photo($photo); } else { $ph = $photo; } if (is_array($ph) && isset($ph['photo_id'])) { $dir = PHOTOS_DIR . '/' . get_photo_date_folder($ph) . '/'; if (strtolower($ph['ext']) != 'jpg') { /* return if photo is not jpg */ return; } $file = get_original_photo($ph); $path = $dir . $file; if (file_exists($path)) { /* File exists. read the exif data. Thanks to CopperMine, Love you */ $data = read_exif_data_raw($path, 0); if (isset($data['SubIFD'])) { $exif_to_include = array('IFD0', 'SubIFD', 'IFD1', 'InteroperabilityIFD'); foreach ($exif_to_include as $eti) { if (isset($data[$eti])) { $exif[$eti] = $data[$eti]; } } /* Removing unknown tags from exif data */ foreach ($exif as $parent => $tags) { foreach ($tags as $tag => $value) { if ($tag == 'MakerNote') { if (is_array($value)) { foreach ($value as $mtag => $mvalue) { if (strpos($mtag, 'unknown') !== false) { unset($exif[$parent][$tag][$mtag]); } else { $exif[$parent][$tag][$mtag] = trim($mvalue); } } } } if (is_array($value)) { continue; } if (strpos($tag, 'unknown') !== false) { unset($exif[$parent][$tag]); } else { $exif[$parent][$tag] = trim($value); } } } $jexif = json_encode($exif); $jexif = preg_replace('/\\\\(u000)(.){1}/', '', $jexif); /* add new meta of exif_data for current photo */ $insert_id = $db->insert(tbl('photosmeta'), array('photo_id', 'meta_name', 'meta_value'), array($ph['photo_id'], 'exif_data', "|no_mc|{$jexif}")); if ($insert_id) { /* update photo has_exif to yes, so we know that this photo has exif data */ $db->update(tbl($cbphoto->p_tbl), array('has_exif'), array('yes'), " photo_id = '" . $ph['photo_id'] . "' "); return $insert_id; } } } } }
break; } } $n++; $value_id = $object->resolveVarName("file"); $filename = $object->getVarValue("file"); $type = getfiletype(pathinfo($filename, PATHINFO_EXTENSION)); $angle = -1; $maxsize = getSetting("IMGSIZE", 640); if ($type == "image") { $result = read_exif_data_raw($filename, 0); $angle = $object->getMeta("angle", ""); $thumbnail = getThumbnail($value_id, $maxsize, $maxsize, $angle); if ($object->hasRight("write")) { if ($angle == "") $angle = 0; $angle_left = ($angle+90); if ($angle_left < 0) $angle_left = 360+$angle_left; else if ($angle_left > 360) $angle_left = 360-$angle_left; $angle_right = ($angle-90);
/** * Read EXIF data from file * * @return bool */ public function read() { $exif = array(); // Read raw EXIF data $exif_raw = read_exif_data_raw($this->filename, false); $this->exif_raw = $exif_raw; if (isset($exif_raw['ValidEXIFData'])) { // parse only wanted data foreach ($this->exif_vars as $field => $exif_var) { if (isset($exif_raw[$exif_var[0]][$exif_var[1]]) && !empty($exif_raw[$exif_var[0]][$exif_var[1]])) { $exif[$field] = $exif_raw[$exif_var[0]][$exif_var[1]]; } } } $this->exif = $exif; return $exif; }
// // fetch directory listing // $data = directory_data($PATH_BASEDIR, $IMAGE_DIR); // FS SEE FUNCTION // fetch size (file and image), exif data on current image // $image_size = getimagesize($data['files'][$INDEX]['path']); // FS READ $file_size = filesize($data['files'][$INDEX]['path']); // FS READ // optionally fetch exifer data // if ($CFG_use_exifer) { include_once 'exif.php'; $exif_data = read_exif_data_raw($data['files'][$INDEX]['path'], 0); } ////////////////////////////////////////////////////////////////////////////// // assign, display templates // $T['current'] =& $data['files'][$INDEX]; $T['current']['image_size'] =& $image_size; $T['current']['view_size'] = calculate_resize($image_size[0], $image_size[1], $CFG_image_width, $CFG_image_height); $T['current']['file_size'] = round($file_size / 1024, 0) . ' KB'; if ($CFG_use_exifer) { $T['current']['exif_data'] =& $exif_data; } $T['next'] =& $data['files'][$INDEX + 1]; $T['prev'] =& $data['files'][$INDEX - 1]; $T['path'] = path_list($IMAGE_DIR); debug('T', $T);
function copy_folder_get_exif_date($image_name) { if (file_exists("../includes/exifer1_5/exif.php")) { require_once "../includes/exifer1_5/exif.php"; } $curr_image = $image_name; if (function_exists('read_exif_data_raw')) { $exif_result = read_exif_data_raw($curr_image, "0"); $capture_date = $exif_result['SubIFD']['DateTimeOriginal']; // Date and Time if ($capture_date == '') { $capture_date = 'bad'; } else { list($exifyear, $exifmonth, $exifday, $exifhour, $exifmin, $exifsec) = split('[: ]', $capture_date); $capture_date = date("YmdHis", mktime($exifhour, $exifmin, $exifsec, $exifmonth, $exifday, $exifyear)); } } else { $capture_date = "bad"; } return $capture_date; }
/** * Read EXIF data from file * * @return bool */ public function read() { $exif = array(); // Read raw EXIF data $exif_raw = read_exif_data_raw($this->filename, false); $this->exif_raw = $exif_raw; if (isset($exif_raw['ValidEXIFData'])) { // Parse only wanted data foreach ($this->exif_vars as $field => $exif_var) { if (isset($exif_raw[$exif_var[0]][$exif_var[1]]) && !empty($exif_raw[$exif_var[0]][$exif_var[1]])) { // Parse timestamp, just in case if ($field === 'taken') { $exif[$field] = Date::format(Date::TIME_SQL, $exif_raw[$exif_var[0]][$exif_var[1]]); } else { $exif[$field] = $exif_raw[$exif_var[0]][$exif_var[1]]; } } } } $this->exif = $exif; return $exif; }
function reindex() { $this->reindexed = true; $to_delete = 0; $images_changed = 0; $dir = $this->get_listing($this->config->pathto_galleries . $this->gallery->id, "images"); usort($this->gallery->images, array($this, "quicksort")); foreach ($this->gallery->images as $key => $value) { $filenames[] = $value->filename; } if (is_array($filenames) && is_array($dir->files)) { $unset = array_diff($filenames, $dir->files); } if ($unset) { foreach ($unset as $key => $value) { for ($i = 0; $i <= count($this->gallery->images); $i++) { if ($this->gallery->images[$i]->filename == $unset[$key]) { unset($this->gallery->images[$i]); $to_delete++; $this->reindex(); } } } } if ($to_delete) { $this->reindex(); } // if there aren't any files to delete if (!$to_delete or count($dir->files) > count($this->gallery->images)) { for ($i = 0; $i < count($dir->files); $i++) { $found = true; for ($j = 0; $j < count($this->gallery->images); $j++) { if ($dir->files[$i] == $this->gallery->images[$j]->filename) { $found = false; break; } } // if changed files are found or if there is no metadata if ($found or $_REQUEST['reindex']) { // set csv path $path = $this->config->pathto_galleries . $this->gallery->id . "/" . $this->gallery->images[$j]->filename; // set new image data $this->gallery->images[$j] = new image(); $this->gallery->images[$j]->filename = $dir->files[$i]; $this->gallery->images[$j]->name = $dir->files[$i]; list($this->gallery->images[$j]->width, $this->gallery->images[$j]->height, $this->gallery->images[$j]->type) = @GetImageSize($path); /* get exif*/ $exif = read_exif_data_raw($path, 0); /* set exif time pointer */ $time = $exif['SubIFD']['DateTimeOriginal']; if (!$time) { $time = $exif['IFD0']['DateTime']; } // Parse the time if ($time != '') { preg_match('/([0-9]+):([0-9]+):([0-9]+) ([0-9]+):([0-9]+):([0-9]+)/', $time, $time_array); $time_date = mktime($time_array[4], $time_array[5], $time_array[6], $time_array[2], $time_array[3], $time_array[1]); $this->gallery->images[$j]->date = $time_date; } $images_changed++; } } } //sort the items how they originally were sorted usort($this->gallery->images, array($this, "image_sort")); if ($images_changed) { $this->reindex(); } $this->io->put_gallery($this->gallery); $this->last_error = "Could not save gallery info"; return false; }