function get_exif_data($imagePath) { $exif_ifd0 = read_exif_data($imagePath, 'IFD0', 0); $exif_exif = read_exif_data($imagePath, 'EXIF', 0); $notFound = NULL; $data = array(); if ($exif_ifd0 !== FALSE) { // Make if (array_key_exists('Make', $exif_ifd0)) { $data['camMake'] = $exif_ifd0['Make']; } else { $data['camMake'] = $notFound; } // Model if (array_key_exists('Model', $exif_ifd0)) { $data['camModel'] = $exif_ifd0['Model']; } else { $data['camModel'] = $notFound; } // Exposure if (array_key_exists('ExposureTime', $exif_ifd0)) { $data['camExposure'] = $this->exif_get_fraction($exif_ifd0['ExposureTime']); } else { $data['camExposure'] = $notFound; } // Aperture - przesłona if (array_key_exists('ApertureFNumber', $exif_ifd0['COMPUTED'])) { $data['camAperture'] = $exif_ifd0['COMPUTED']['ApertureFNumber']; } else { $data['camAperture'] = $notFound; } // Date if (array_key_exists('DateTime', $exif_ifd0)) { $data['camDate'] = $exif_ifd0['DateTime']; } else { $data['camDate'] = $notFound; } // Software if (array_key_exists('Software', $exif_ifd0)) { $data['camSoftware'] = $exif_ifd0['Software']; } else { $data['camSoftware'] = $notFound; } // Focal - ogniskowa if (array_key_exists('FocalLength', $exif_ifd0)) { $data['camFocal'] = $this->exif_get_fraction($exif_ifd0['FocalLength']); } else { $data['camFocal'] = $notFound; } } if ($exif_exif !== FALSE) { // ISO if (array_key_exists('ISOSpeedRatings', $exif_exif)) { $data['camIso'] = $exif_exif['ISOSpeedRatings']; } else { $data['camIso'] = $notFound; } } return $data; }
function getInformation($imagePath) { if (isset($imagePath) and file_exists($imagePath)) { $ifdo = read_exif_data($imagePath, 'IFD0', 0); $exif = read_exif_data($imagePath, 'EXIF', 0); // Maker if (@array_key_exists('Make', $ifdo)) { $maker = $ifdo['Make']; } else { $maker = $this->unavailable; } // Model if (@array_key_exists('Model', $ifdo)) { $model = $ifdo['Model']; } else { $model = $this->unavailable; } // Exposure if (@array_key_exists('ExposureTime', $ifdo)) { $exposure = $ifdo['ExposureTime']; } else { $exposure = $this->unavailable; } // Aperture if (@array_key_exists('ApertureFNumber', $ifdo['COMPUTED'])) { $aperture = $ifdo['COMPUTED']['ApertureFNumber']; } else { $aperture = $this->unavailable; } // Created Date if (@array_key_exists('DateTime', $ifdo)) { $createDate = $ifdo['DateTime']; } else { $createDate = $this->unavailable; } // ISO if (@array_key_exists('ISOSpeedRatings', $exif)) { $iso = $exif['ISOSpeedRatings']; } else { $iso = $this->unavailable; } // Focal Length if (@array_key_exists('FocalLength', $exif)) { $focalLength = $exif['FocalLength']; } else { $focalLength = $this->unavailable; } $infoArray = array(); $infoArray['maker'] = $maker; $infoArray['model'] = $model; $infoArray['exposure'] = $exposure; $infoArray['aperture'] = $aperture; $infoArray['date'] = $createDate; $infoArray['iso'] = $iso; $infoArray['focalLength'] = $focalLength; return $infoArray; } else { return false; } }
public static 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; } }
public function __construct($fileName) { // *** Open up the file $this->image = $this->openImage($fileName); logr($this->image, 'openIMage'); // *** Get width and height $this->width = imagesx($this->image); $this->height = imagesy($this->image); // *** Get EXIF data if the exif module is installed if (function_exists('read_exif_data')) { $this->exif = read_exif_data($fileName); } else { error_log("Please install the exif module in order to support image orientation"); } }
/** * Remove EXIF data if needed * * @param $file * @return bool * @throws Exception */ private static function removeExif($file) { if ($exif = @read_exif_data($file)) { if (!empty($exif['Orientation'])) { $img = new SimpleImage($file); if ($img->save()) { return true; } else { return false; } } else { return true; } } else { return false; } }
/** * @param Image $image */ protected function update_exif(Image $image) { $tmpFilename = tempnam(sys_get_temp_dir(), 'upload_image_'); // Fixes error reading gaufrette streaf for read_exif_data file_put_contents($tmpFilename, file_get_contents($this->getFilepath($image))); $exif = new ExifDataParser(@read_exif_data($tmpFilename) ?: array()); unlink($tmpFilename); $exif_parsed = $exif->getParsed(); $image->setExifData($exif_parsed); $datetime = null; try { $datetime = new \DateTime(@$exif_parsed['DateTimeOriginal']); } catch (\Exception $e) { $datetime = new \DateTime($exif_parsed['DateTime']); } $image->setTakenAt($datetime); $this->em->persist($image); }
/** * Initialize a layer from a given image path * * From an upload form, you can give the "tmp_name" path * * @param string $path * @param bool $fixOrientation * * @return ImageWorkshopLayer */ public static function initFromPath($path, $fixOrientation = false) { if (!file_exists($path)) { throw new ImageWorkshopException(sprintf('File "%s" not exists.', $path), static::ERROR_IMAGE_NOT_FOUND); } if (false === ($imageSizeInfos = @getImageSize($path))) { throw new ImageWorkshopException('Can\'t open the file at "' . $path . '" : file is not readable, did you check permissions (755 / 777) ?', static::ERROR_NOT_READABLE_FILE); } $mimeContentType = explode('/', $imageSizeInfos['mime']); if (!$mimeContentType || !isset($mimeContentType[1])) { throw new ImageWorkshopException('Not an image file (jpeg/png/gif) at "' . $path . '"', static::ERROR_NOT_AN_IMAGE_FILE); } $mimeContentType = $mimeContentType[1]; $exif = array(); switch ($mimeContentType) { case 'jpeg': $image = imageCreateFromJPEG($path); if (false === ($exif = @read_exif_data($path))) { $exif = array(); } break; case 'gif': $image = imageCreateFromGIF($path); break; case 'png': $image = imageCreateFromPNG($path); break; default: throw new ImageWorkshopException('Not an image file (jpeg/png/gif) at "' . $path . '"', static::ERROR_NOT_AN_IMAGE_FILE); break; } if (false === $image) { throw new ImageWorkshopException('Unable to create image with file found at "' . $path . '"'); } $layer = new ImageWorkshopLayer($image, $exif); if ($fixOrientation) { $layer->fixOrientation(); } return $layer; }
/** * Constructor function * Sets the values for a list of variabhles * Also grabs the image dimensions and orientation during the process * * @param object $image */ public function __construct($image) { $this->temp_name = $image; $image = getimagesize($this->temp_name); $this->orig_x = $image[0]; $this->orig_y = $image[1]; $this->file_type = strtolower(preg_replace('/^.*?\\//', '', $image['mime'])); $this->thumb_size = 200; $this->med_size = 300; $this->large_size = 450; $this->quality = 100; //default if ($this->file_type == 'jpg' || $this->file_type == 'jpeg') { $exif = @read_exif_data($this->temp_name); if (isset($exif['Orientation'])) { $this->orientation = $exif['Orientation']; } else { $this->orientation = 1; } } else { $this->orientation = 1; } }
/** * Populates the metadata of a photo based on the EXIF data of the photo * * @param \Photo\Model\Photo $photo the photo to add the metadata to. * @param string $path The path where the actual image file is stored * * @return \Photo\Model\Photo the photo with the added metadata */ public function populateMetadata($photo, $path) { $exif = read_exif_data($path, 'EXIF'); if ($exif) { $photo->setArtist($exif['Artist']); $photo->setCamera($exif['Model']); $photo->setDateTime(new \DateTime($exif['DateTimeOriginal'])); $photo->setFlash($exif['Flash'] != 0); $photo->setFocalLength($this->frac2dec($exif['FocalLength'])); $photo->setExposureTime($this->frac2dec($exif['ExposureTime'])); if (isset($exif['ShutterSpeedValue'])) { $photo->setShutterSpeed($this->exifGetShutter($exif['ShutterSpeedValue'])); } if (isset($exif['ShutterSpeedValue'])) { $photo->setAperture($this->exifGetFstop($exif['ApertureValue'])); } $photo->setIso($exif['ISOSpeedRatings']); } else { // We must have a date/time for a photo // Since no date is known, we use the current one $photo->setDateTime(new \DateTime()); } return $photo; }
function process() { $site_id = $this->site_id; $counts = array(); for ($i = 1; $i <= $this->max_upload_number; $i++) { $element = $this->get_element('upload_' . $i); if (!empty($element->tmp_full_path) and file_exists($element->tmp_full_path)) { $filename = $this->get_value('upload_' . $i . '_filename'); if ($this->verify_image($element->tmp_full_path)) { if (empty($counts[$filename])) { $this->files[$filename] = $element->tmp_full_path; $counts[$filename] = 1; } else { $counts[$filename]++; $this->files[$filename . '.' . $counts[$filename]] = $element->tmp_full_path; } } else { $this->invalid_files[$filename] = $element->tmp_full_path; } } } if (count($this->files)) { $page_id = (int) $this->get_value('attach_to_page'); $max_sort_order_value = 0; if ($page_id) { $max_sort_order_value = $this->_get_max_sort_order_value($page_id); } $sort_order_value = $max_sort_order_value; $tables = get_entity_tables_by_type(id_of('image')); $valid_file_html = '<ul>' . "\n"; foreach ($this->files as $entry => $cur_name) { $sort_order_value++; $valid_file_html .= '<li><strong>' . $entry . ':</strong> processing '; $date = ''; // get suffix $type = strtolower(substr($cur_name, strrpos($cur_name, '.') + 1)); $ok_types = array('jpg'); // get exif data if ($this->get_value('exif_override') && in_array($type, $ok_types) && function_exists('read_exif_data')) { // read_exif_data() does not obey error supression $exif_data = @read_exif_data($cur_name); if ($exif_data) { // some photos may have different fields filled in for dates - look through these until one is found $valid_dt_fields = array('DateTimeOriginal', 'DateTime', 'DateTimeDigitized'); foreach ($valid_dt_fields as $field) { // once we've found a valid date field, store that and break out of the loop if (!empty($exif_data[$field])) { $date = $exif_data[$field]; break; } } } } else { $date = $this->get_value('datetime'); } $keywords = $entry; if ($this->get_value('keywords')) { $keywords .= ', ' . $this->get_value('keywords'); } // insert entry into DB with proper info $values = array('datetime' => $date, 'image_type' => $type, 'author' => $this->get_value('author'), 'state' => 'Pending', 'keywords' => $keywords, 'description' => $this->get_value('description'), 'name' => $this->get_value('name') ? $this->get_value('name') : $entry, 'content' => $this->get_value('content'), 'original_image_format' => $this->get_value('original_image_format'), 'new' => 0, 'no_share' => $this->get_value('no_share')); //tidy values $no_tidy = array('state', 'new'); foreach ($values as $key => $val) { if (!in_array($key, $no_tidy) && !empty($val)) { $values[$key] = trim(get_safer_html(tidy($val))); } } $id = reason_create_entity($site_id, id_of('image'), $this->user_id, $entry, $values); if ($id) { //assign to categories $categories = $this->get_value('assign_to_categories'); if (!empty($categories)) { foreach ($categories as $category_id) { create_relationship($id, $category_id, relationship_id_of('image_to_category')); } } //assign to gallery page if ($page_id) { create_relationship($page_id, $id, relationship_id_of('minisite_page_to_image'), array('rel_sort_order' => $sort_order_value)); } // resize and move photos $new_name = PHOTOSTOCK . $id . '.' . $type; $orig_name = PHOTOSTOCK . $id . '_orig.' . $type; $tn_name = PHOTOSTOCK . $id . '_tn.' . $type; // Support for new fields; they should be set null by default, but will be // changed below if a thumbnail/original image is created. This is very messy... $thumbnail_image_type = null; $original_image_type = null; // atomic move the file if possible, copy if necessary if (is_writable($cur_name)) { rename($cur_name, $new_name); } else { copy($cur_name, $new_name); } // create a thumbnail if need be list($width, $height, $type, $attr) = getimagesize($new_name); if ($width > REASON_STANDARD_MAX_IMAGE_WIDTH || $height > REASON_STANDARD_MAX_IMAGE_HEIGHT) { copy($new_name, $orig_name); resize_image($new_name, REASON_STANDARD_MAX_IMAGE_WIDTH, REASON_STANDARD_MAX_IMAGE_HEIGHT); $original_image_type = $this->image_types[$type]; } $thumb_dimensions = get_reason_thumbnail_dimensions($site_id); if ($width > $thumb_dimensions['width'] || $height > $thumb_dimensions['height']) { copy($new_name, $tn_name); resize_image($tn_name, $thumb_dimensions['width'], $thumb_dimensions['height']); $thumbnail_image_type = $this->image_types[$type]; } // real original $my_orig_name = $this->add_name_suffix($cur_name, '-unscaled'); if (file_exists($my_orig_name)) { // move the original image into the photostock directory if (is_writable($my_orig_name)) { rename($my_orig_name, $orig_name); } else { copy($my_orig_name, $orig_name); } $original_image_type = $this->image_types[$type]; } $info = getimagesize($new_name); $size = round(filesize($new_name) / 1024); // now we have the size of the resized image. $values = array('width' => $info[0], 'height' => $info[1], 'size' => $size, 'thumbnail_image_type' => $thumbnail_image_type, 'original_image_type' => $original_image_type); // update with new info - don't archive since this is really just an extension of the creation of the item // we needed that ID to do something reason_update_entity($id, $this->user_id, $values, false); $valid_file_html .= 'completed</li>'; } else { trigger_error('Unable to create image entity'); $valid_file_html .= '<li>Unable to import ' . $entry . '</li>'; } sleep(1); } $valid_file_html .= '</ul>' . "\n"; $num_image_string = count($this->files) == 1 ? '1 image has ' : count($this->files) . ' images have '; $valid_file_html .= '<p>' . $num_image_string . 'been successfully imported into Reason.</p>'; $valid_file_html .= '<p>They are now pending.</p>'; $next_steps[] = '<a href="?site_id=' . $site_id . '&type_id=' . id_of('image') . '&user_id=' . $this->user_id . '&cur_module=Lister&state=pending">review & approve imported images</a>'; } if (isset($this->invalid_files)) { $invalid_files = array_keys($this->invalid_files); $invalid_file_html = '<p>The following could not be validated as image files and were not successfully imported.</p>'; $invalid_file_html .= '<ul>'; foreach ($invalid_files as $file) { $invalid_file_html .= '<li><strong>' . reason_htmlspecialchars($file) . '</strong></li>'; } $invalid_file_html .= '</ul>'; } $next_steps[] = '<a href="' . get_current_url() . '">Import another set of images</a>'; if (!isset($this->invalid_files) && !isset($this->files)) { echo '<p>You did not select any files for upload</p>'; } if (isset($valid_file_html)) { echo $valid_file_html; } if (isset($invalid_file_html)) { echo $invalid_file_html; } echo '<p>Next Steps:</p><ul><li>' . implode('</li><li>', $next_steps) . '</li></ul>'; $this->show_form = false; }
/** * Gets Longitude and Latitude information from a photo exif data, if exists. * * @return mixed array of longitude and latitude or false otherwise */ public function getLongLat() { try { $exif = read_exif_data('upload/photos/' . $this->id . '.' . $this->extension); if (isset($exif["GPSLongitude"], $exif['GPSLongitudeRef'], $exif["GPSLatitude"], $exif['GPSLatitudeRef'])) { $lon = $this->getGps($exif["GPSLongitude"], $exif['GPSLongitudeRef']); $lat = $this->getGps($exif["GPSLatitude"], $exif['GPSLatitudeRef']); return array('lat' => $lat, 'long' => $lon); } } catch (Exception $e) { } return false; }
/** * Pareses and stores all relevant exif data */ protected function parse() { // read the exif data of the media object if possible $this->data = @read_exif_data($this->media->root()); // stop on invalid exif data if (!is_array($this->data)) { return false; } // store the timestamp when the picture has been taken if (isset($this->data['DateTime'])) { $this->timestamp = strtotime($this->data['DateTime']); } else { $this->timestamp = a::get($this->data, 'FileDateTime', $this->media->modified()); } // exposure $this->exposure = a::get($this->data, 'ExposureTime'); // iso $this->iso = a::get($this->data, 'ISOSpeedRatings'); // focal length if (isset($this->data['FocalLength'])) { $this->focalLength = $this->data['FocalLength']; } else { if (isset($this->data['FocalLengthIn35mmFilm'])) { $this->focalLength = $this->data['FocalLengthIn35mmFilm']; } } // aperture $this->aperture = @$this->data['COMPUTED']['ApertureFNumber']; // color or bw $this->isColor = @$this->data['COMPUTED']['IsColor'] == true; }
public function saveFileToDB($filepath, $userid) { ini_set('exif.encode_unicode', 'UTF-8'); error_log($filepath); try { try { $exif_ifd0 = read_exif_data($filepath, 'IFD0', 0); $exif_exif = read_exif_data($filepath, 'EXIF', 0); $exif_file = read_exif_data($filepath, 'FILE', 0); } catch (Exception $e) { } $timetaken = null; $filename = $exif_file['FileName']; if (isset($exif_exif['DateTimeOriginal'])) { //We get the date and time the picture was taken try { $exif_date = $exif_exif['DateTimeOriginal']; error_log("EXIF TIME TAKEN : " . $exif_date); $exif_timetaken = date("Y-m-d H:i:s", strtotime($exif_date)); } catch (Exception $e) { error_log($e->getMessage()); } } if (isset($exif_ifd0['DateTime'])) { //We get the date and time the picture was taken try { $ifd0_date = $exif_ifd0['DateTime']; error_log("IFDO TIME TAKEN : " . $ifd0_date); $ifd0_timetaken = date("Y-m-d H:i:s", strtotime($ifd0_date)); } catch (Exception $e) { error_log($e->getMessage()); } } //We chose the earliest date of the 2 if (isset($exif_date) && isset($ifd0_date)) { $rawTimeTaken = $exif_date < $ifd0_date ? $exif_date : $ifd0_date; error_log("FINAL TIME TAKEN : " . $rawTimeTaken); $timetaken = date("Y-m-d H:i:s", strtotime($rawTimeTaken)); } else { if (isset($exif_date)) { $rawTimeTaken = $exif_date; error_log("FINAL TIME TAKEN : " . $rawTimeTaken); $timetaken = date("Y-m-d H:i:s", strtotime($rawTimeTaken)); } else { if (isset($ifd0_date)) { $rawTimeTaken = $ifd0_date; error_log("FINAL TIME TAKEN : " . $rawTimeTaken); $timetaken = date("Y-m-d H:i:s", strtotime($rawTimeTaken)); } else { $rawTimeTaken = $exif_file['FileDateTime']; $timetaken = date("Y-m-d H:i:s", $rawTimeTaken); } } } error_log("TIME TAKEN : " . $timetaken); $fileType = $exif_file['MimeType']; //$payload = file_get_contents($filepath); $picture = new Picture(0, "", "", $timetaken, $fileType, null, $filename); $picture->latitude = ""; $picture->longitude = ""; $dao = new PictureDAO(); $dayId = $dao->createDay($userid, $timetaken); $dao->savePicture($dayId, $picture); error_log("File saved successfully."); //unlink($filepath); } catch (Exception $e3) { print "Error!: " . $e3->getMessage() . "<br/>"; //unlink($filepath); } }
<?php /* Prototype : array read_exif_data ( string $filename [, string $sections [, bool $arrays [, bool $thumbnail ]]] ) * Description: Alias of exif_read_data() * Source code: ext/exif/exif.c */ echo "*** Testing read_exif_data() : basic functionality ***\n"; print_r(read_exif_data(dirname(__FILE__) . '/test2.jpg')); ?> ===Done===
/** * returns informations from EXIF metadata, mapping is done in this function. * * @param string $filename * @param array $map * @return array */ function get_exif_data($filename, $map) { global $conf; $result = array(); if (!function_exists('read_exif_data')) { die('Exif extension not available, admin should disable exif use'); } // Read EXIF data if ($exif = @read_exif_data($filename) or $exif2 = trigger_change('format_exif_data', $exif = null, $filename, $map)) { if (!empty($exif2)) { $exif = $exif2; } else { $exif = trigger_change('format_exif_data', $exif, $filename, $map); } // configured fields foreach ($map as $key => $field) { if (strpos($field, ';') === false) { if (isset($exif[$field])) { $result[$key] = $exif[$field]; } } else { $tokens = explode(';', $field); if (isset($exif[$tokens[0]][$tokens[1]])) { $result[$key] = $exif[$tokens[0]][$tokens[1]]; } } } // GPS data $gps_exif = array_intersect_key($exif, array_flip(array('GPSLatitudeRef', 'GPSLatitude', 'GPSLongitudeRef', 'GPSLongitude'))); if (count($gps_exif) == 4) { if (is_array($gps_exif['GPSLatitude']) and in_array($gps_exif['GPSLatitudeRef'], array('S', 'N')) and is_array($gps_exif['GPSLongitude']) and in_array($gps_exif['GPSLongitudeRef'], array('W', 'E'))) { $result['latitude'] = parse_exif_gps_data($gps_exif['GPSLatitude'], $gps_exif['GPSLatitudeRef']); $result['longitude'] = parse_exif_gps_data($gps_exif['GPSLongitude'], $gps_exif['GPSLongitudeRef']); } } } if (!$conf['allow_html_in_metadata']) { foreach ($result as $key => $value) { // in case the origin of the photo is unsecure (user upload), we remove // HTML tags to avoid XSS (malicious execution of javascript) $result[$key] = strip_tags($value); } } return $result; }
function getExifCaption($image) { global $baseURL, $scriptPath, $dir; $exif = @read_exif_data($scriptPath . $dir . $image); return $exif['COMMENT'][0]; }
function exif($file) { $file_parts = pathinfo($file['file']); if (in_array(strtolower($file_parts['extension']), array('jpg', 'jpeg', 'tiff'))) { $exif = @read_exif_data($file['file']); $exif_orient = isset($exif['Orientation']) ? $exif['Orientation'] : 0; $rotate_image = 0; $exif_orient = intval($exif_orient); if (6 === intval($exif_orient)) { $rotate_image = 90; $image_orientation = 1; } elseif (3 === $exif_orient) { $rotate_image = 180; $image_orientation = 1; } elseif (8 === $exif_orient) { $rotate_image = 270; $image_orientation = 1; } if ($rotate_image) { if (class_exists('Imagick')) { $imagick = new Imagick(); $imagick->readImage($file['file']); $imagick->rotateImage(new ImagickPixel(), $rotate_image); $imagick->setImageOrientation($image_orientation); $imagick->writeImage($file['file']); $imagick->clear(); $imagick->destroy(); } else { $rotate_image = -$rotate_image; switch ($file['type']) { case 'image/jpeg': $source = imagecreatefromjpeg($file['file']); $rotate = imagerotate($source, $rotate_image, 0); imagejpeg($rotate, $file['file']); break; case 'image/png': $source = imagecreatefrompng($file['file']); $rotate = imagerotate($source, $rotate_image, 0); imagepng($rotate, $file['file']); break; case 'image/gif': $source = imagecreatefromgif($file['file']); $rotate = imagerotate($source, $rotate_image, 0); imagegif($rotate, $file['file']); break; default: break; } } } } return $file; }
/** * Adds image to Album * @param string $image_file * @param string $default_title * @param Entity\Album $album * @param array $options * @param UserInterface $user */ private function addImageToAlbum($image_file, $default_title, Entities\Album $album, array $options = array(), UserInterface $user = null) { $image = new Entities\Image(); $image->setAlbum($album); $image->setFilename(sprintf("%s.%s", md5(uniqid()), strtolower(pathinfo($default_title ?: $image_file, PATHINFO_EXTENSION)))); $name = pathinfo($image_file, PATHINFO_FILENAME); if ($default_title) { $name = $default_title; } if (@$options['default_name']) { $name = $options['default_name']; } $image->setName($name); // create folder if not exists if (!file_exists($image->getUploadRootDir())) { mkdir($image->getUploadRootDir(), 0777, true); chmod($image->getUploadRootDir(), 0777); } copy($image_file, $image->getAbsolutePath()); $image->setUser($user); $exif = new ExifParsers\ExifDataParser(@read_exif_data($image->getAbsolutePath())); $exif_parsed = $exif->getParsed(); $datetime = null; try { $datetime = new \DateTime(@$exif_parsed['DateTimeOriginal']); } catch (\Exception $e) { $datetime = new \DateTime($exif_parsed['DateTime']); } $image->setTakenAt($datetime); Converter::exif_rotate($image->getAbsolutePath(), @$exif_parsed['IFD0']['Orientation']); $iptc = new ExifParsers\IptcDataParser($image->getAbsolutePath()); $image->setExifData($exif_parsed); if (@$options['keywords']) { $keywords = array_filter(array_map('trim', explode(',', $options['keywords']))); foreach ($keywords as $keyword) { $tag = $this->tag($keyword); $image->addTag($tag); } } if (@$options['private']) { $image->setPrivate(true); } $this->em->persist($image); }
private function saveFileToDB($filepath) { ini_set('exif.encode_unicode', 'UTF-8'); error_log($filepath); try { try { $exif_ifd0 = read_exif_data($filepath, 'IFD0', 0); $exif_exif = read_exif_data($filepath, 'EXIF', 0); $exif_file = read_exif_data($filepath, 'FILE', 0); } catch (Exception $e) { } var_dump($exif_ifd0); var_dump($exif_exif); $timetaken = null; $filename = $exif_file['FileName']; if (isset($exif_exif['DateTimeOriginal'])) { //We get the date and time the picture was taken try { $exif_date = $exif_exif['DateTimeOriginal']; error_log("EXIF TIME TAKEN : " . $exif_date); $exif_timetaken = date("Y-m-d H:i:s", strtotime($exif_date)); } catch (Exception $e) { error_log($e->getMessage()); } } if (isset($exif_ifd0['DateTime'])) { //We get the date and time the picture was taken try { $ifd0_date = $exif_ifd0['DateTime']; error_log("IFDO TIME TAKEN : " . $ifd0_date); $ifd0_timetaken = date("Y-m-d H:i:s", strtotime($ifd0_date)); } catch (Exception $e) { error_log($e->getMessage()); } } //We chose the earliest date of the 2 if (isset($exif_date) && isset($ifd0_date)) { $rawTimeTaken = $exif_date < $ifd0_date ? $exif_date : $ifd0_date; error_log("FINAL TIME TAKEN : " . $rawTimeTaken); $timetaken = date("Y-m-d H:i:s", strtotime($rawTimeTaken)); } else { if (isset($exif_date)) { $rawTimeTaken = $exif_date; error_log("FINAL TIME TAKEN : " . $rawTimeTaken); $timetaken = date("Y-m-d H:i:s", strtotime($rawTimeTaken)); } else { if (isset($ifd0_date)) { $rawTimeTaken = $ifd0_date; error_log("FINAL TIME TAKEN : " . $rawTimeTaken); $timetaken = date("Y-m-d H:i:s", strtotime($rawTimeTaken)); } else { $rawTimeTaken = $exif_file['FileDateTime']; $timetaken = date("Y-m-d H:i:s", $rawTimeTaken); } } } error_log("TIME TAKEN : " . $timetaken); $fileType = $exif_file['MimeType']; /* $exif = exif_read_data($filepath, 'IFD0'); foreach ($exif as $key => $section) { foreach ($section as $name => $val) { error_log("$key.$name: $val"); } } */ //Reduce file size $img = imagecreatefromjpeg($filepath); $quality = 100; $currentFileSize = filesize($filepath); switch ($currentFileSize) { case $currentFileSize > 3000000: $quality = 7; break; case $currentFileSize > 2000000: $quality = 14; break; case $currentFileSize > 1000000: $quality = 21; break; case $currentFileSize > 500000: $quality = 70; break; } imagejpeg($img, $filepath, $quality); imagedestroy($img); //$payload = file_get_contents($filepath); $picture = new Picture(0, "", "", $timetaken, $fileType, null, $filename); $picture->latitude = ""; $picture->longitude = ""; $dao = new PictureDAO(); if (isset($_SESSION['name'])) { $userid = $_SESSION["userid"]; $dayId = $dao->createDay($userid, $timetaken); $dao->savePicture($dayId, $picture); } else { error_log("COULD NOT SAVE PICTURES, NO USER IN SESSION!!!"); unlink($filepath); } //unlink($filepath); } catch (Exception $e3) { print "Error!: " . $e3->getMessage() . "<br/>"; unlink($filepath); } }
/** * Read Exif data attached to image * * @param string $path * * @return array */ private function readExifData($path) { $exif_data = read_exif_data($path); return $exif_data; }
/** * Supplies a JPEG/TIFF image file. * * @author Jérôme Pierre <*****@*****.**> * @version V1 - July 28th 2010 * * @param string $path The absolute path to a JPEG/TIFF image file. * * @return s6yExifDataManager $this An instance of the current class. * * @throws sfException Throws an exception in case of unexisting file. * @throws sfException Throws an exception in case of unreadable file. */ public function supplyImage($path = null) { if (!empty($path)) { if (!is_file($this->_file_path = $path)) { throw new sfException('The supplied file does not exist or is not a file.'); } if (!($this->_exif_data = @read_exif_data($path))) { throw new sfException('No Exif data can be read from the supplied file.'); } } return $this; }
$imginfo = array(); getimagesize($filename, $imginfo); if (isset($imginfo['APP13'])) { $iptc = iptcparse($imginfo['APP13']); if (is_array($iptc)) { foreach (array_keys($iptc) as $iptc_key) { if (isset($iptc[$iptc_key][0])) { if ($iptc_key == '2#025') { $value = implode(',', array_map('clean_iptc_value', $iptc[$iptc_key])); } else { $value = clean_iptc_value($iptc[$iptc_key][0]); } $iptc_result[$iptc_key] = $value; } } } echo 'IPTC Fields in ' . $filename . '<br>'; $keys = array_keys($iptc_result); sort($keys); foreach ($keys as $key) { echo '<br>' . $key . ' = ' . $iptc_result[$key]; } } else { echo 'no IPTC information'; } echo '<br><br><br>'; echo 'EXIF Fields in ' . $filename . '<br>'; $exif = read_exif_data($filename); echo '<pre>'; print_r($exif); echo '</pre>';
/** * Fixes image orientation. * * @since 1.0.0 * @package GeoDirectory * @param array $file The image file. * @return mixed Image file. */ function geodir_exif($file) { //This line reads the EXIF data and passes it into an array $file['file'] = $file['tmp_name']; if ($file['type'] == "image/jpg" || $file['type'] == "image/jpeg" || $file['type'] == "image/pjpeg") { } else { return $file; } if (!function_exists('read_exif_data')) { return $file; } $exif = read_exif_data($file['file']); //We're only interested in the orientation $exif_orient = isset($exif['Orientation']) ? $exif['Orientation'] : 0; $rotateImage = 0; //We convert the exif rotation to degrees for further use if (6 == $exif_orient) { $rotateImage = 90; $imageOrientation = 1; } elseif (3 == $exif_orient) { $rotateImage = 180; $imageOrientation = 1; } elseif (8 == $exif_orient) { $rotateImage = 270; $imageOrientation = 1; } //if the image is rotated if ($rotateImage) { //WordPress 3.5+ have started using Imagick, if it is available since there is a noticeable difference in quality //Why spoil beautiful images by rotating them with GD, if the user has Imagick if (class_exists('Imagick')) { $imagick = new Imagick(); $imagick->readImage($file['file']); $imagick->rotateImage(new ImagickPixel(), $rotateImage); $imagick->setImageOrientation($imageOrientation); $imagick->writeImage($file['file']); $imagick->clear(); $imagick->destroy(); } else { //if no Imagick, fallback to GD //GD needs negative degrees $rotateImage = -$rotateImage; switch ($file['type']) { case 'image/jpeg': $source = imagecreatefromjpeg($file['file']); $rotate = imagerotate($source, $rotateImage, 0); imagejpeg($rotate, $file['file']); break; case 'image/png': $source = imagecreatefrompng($file['file']); $rotate = imagerotate($source, $rotateImage, 0); imagepng($rotate, $file['file']); break; case 'image/gif': $source = imagecreatefromgif($file['file']); $rotate = imagerotate($source, $rotateImage, 0); imagegif($rotate, $file['file']); break; default: break; } } } // The image orientation is fixed, pass it back for further processing return $file; }
function pictures_post() { $this->validate_data('apiv1/pictures_post'); $data = $this->post('picture', false); $crop = $this->post('crop'); $top = $crop['top']; $left = $crop['left']; $width = $crop['width']; $height = $crop['height']; // DEBUT DE A supprimer au passage à CodeIgniter 3 de form_validation if (preg_match('#^data:image/([^;]+);base64,(.+)$#', $data, $matches, PREG_OFFSET_CAPTURE) != 1) { //print_r($matches); $this->response(['error' => 'Not a picture', 'picture' => $this->post('picture')], 403); } log_message('debug', 'Payload mime : ' . $matches[1][0]); $data = $matches[2][0]; // FIN DE A supprimer au passage à CodeIgniter 3 de form_validation $picture = @imagecreatefromstring(base64_decode($data)); //remove error $exif_data = read_exif_data($this->post('picture', false)); $exif_orientation = 1; if ($exif_data !== FALSE && isset($exif_data['Orientation'])) { $exif_orientation = $exif_data['Orientation']; } if ($picture !== false) { $this->load->model('Report'); //check if reports exists $report = $this->Report->get_report($this->get('id_reports')); if ($report) { log_message('debug', 'Call update_report_picture with : id_reports ' . $this->get('id_reports') . ' crop : top : ' . $top . ' left : ' . $left . ' width : ' . $width . ' height : ' . $height . ''); $url = $this->config->base_url() . $this->Report->update_report_picture($this->get('id_reports'), $picture, $top, $left, $width, $height, $exif_orientation); $this->response(['success' => $url], 200); } else { $this->response(['error' => 'report not found'], 404); } //@imagedestroy($picture); //done in the model processing } else { $this->response(['error' => 'Cannot manage the picture', 'picture' => $this->post('picture')], 500); } }
private function setTmpImage($upload_file) { $image_types = array('image/png', 'image/gif', 'image/jpeg', 'image/jpg'); if (in_array(\File::mimeType($upload_file), $image_types)) { switch (\File::mimeType($upload_file)) { case 'image/png': $img = imagecreatefrompng($upload_file->getRealPath()); break; case 'image/gif': $img = imagecreatefromgif($upload_file->getRealPath()); break; case 'image/jpeg': case 'image/jpg': default: $img = imagecreatefromjpeg($upload_file->getRealPath()); $exif = read_exif_data($upload_file->getRealPath()); if (isset($exif['Orientation'])) { switch ($exif['Orientation']) { case 8: $img = imagerotate($img, 90, 0); break; case 3: $img = imagerotate($img, 180, 0); break; case 6: $img = imagerotate($img, -90, 0); break; } } } imagepng($img, $upload_file->getRealPath()); return $img; } else { return null; } }
public function regenerate_image_size($image_id = 0) { $o = array('success' => 'no', 'body' => ''); if ($image_id == FALSE) { $o['body'] = 'MISSING IMAGE ID'; exit($this->EE->image_helper->generate_json($o)); } // Grab image info $query = $this->EE->db->select('field_id, entry_id, filename, extension')->from('exp_channel_images')->where('image_id', $image_id)->limit(1)->get(); $field_id = $query->row('field_id'); // Grab settings $settings = $this->EE->image_helper->grabFieldSettings($field_id); $filename = $query->row('filename'); $extension = '.' . substr(strrchr($filename, '.'), 1); $entry_id = $query->row('entry_id'); // ----------------------------------------- // Load Location // ----------------------------------------- $location_type = $settings['upload_location']; $location_class = 'CI_Location_' . $location_type; // Load Settings if (isset($settings['locations'][$location_type]) == FALSE) { $o['body'] = $this->EE->lang->line('ci:location_settings_failure'); exit($this->EE->image_helper->generate_json($o)); } $location_settings = $settings['locations'][$location_type]; // Load Main Class if (class_exists('Image_Location') == FALSE) { require PATH_THIRD . 'channel_images/locations/image_location.php'; } // Try to load Location Class if (class_exists($location_class) == FALSE) { $location_file = PATH_THIRD . 'channel_images/locations/' . $location_type . '/' . $location_type . '.php'; if (file_exists($location_file) == FALSE) { $o['body'] = $this->EE->lang->line('ci:location_load_failure'); exit($this->EE->image_helper->generate_json($o)); } require $location_file; } // Init $LOC = new $location_class($location_settings); // Temp Dir $temp_dir = $this->EE->channel_images->cache_path . 'channel_images/'; // ----------------------------------------- // Copy Image to temp location // ----------------------------------------- $response = $LOC->download_file($entry_id, $filename, $temp_dir); if ($response !== TRUE) { exit($response); } // ----------------------------------------- // Load Actions :O // ----------------------------------------- $actions = $this->EE->image_helper->get_actions(); $limit_sizes = array(); if (isset($_POST['sizes'][$field_id]) === true) { $limit_sizes = $_POST['sizes'][$field_id]; } // ----------------------------------------- // Loop over all action groups! // ----------------------------------------- $metadata = array(); foreach ($settings['action_groups'] as $group) { $size_name = $group['group_name']; $size_filename = str_replace($extension, "__{$size_name}{$extension}", $filename); if (!in_array($size_name, $limit_sizes) && $limit_sizes != false) { $LOC->download_file($entry_id, $size_filename, $temp_dir); } else { // Make a copy of the file @copy($temp_dir . $filename, $temp_dir . $size_filename); @chmod($temp_dir . $size_filename, 0777); // ----------------------------------------- // Loop over all Actions and RUN! OMG! // ----------------------------------------- foreach ($group['actions'] as $action_name => $action_settings) { // RUN! $actions[$action_name]->settings = $action_settings; $actions[$action_name]->settings['field_settings'] = $settings; $res = $actions[$action_name]->run($temp_dir . $size_filename, $temp_dir); if ($res !== TRUE) { @unlink($temp_dir . $size_filename); $o['body'] = 'ACTION ERROR: ' . $res; exit($this->EE->image_helper->generate_json($o)); } } if (is_resource($this->EE->channel_images->image) == TRUE) { imagedestroy($this->EE->channel_images->image); } } // Parse Image Size $imginfo = @getimagesize($temp_dir . $size_filename); $filesize = @filesize($temp_dir . $size_filename); $metadata[$size_name] = array('width' => @$imginfo[0], 'height' => @$imginfo[1], 'size' => $filesize); // ----------------------------------------- // Upload the file back! // ----------------------------------------- $res = $LOC->upload_file($temp_dir . $size_filename, $size_filename, $entry_id); if ($res !== TRUE) { $o['body'] = $res; exit($this->EE->image_helper->generate_json($o)); } // Delete @unlink($temp_dir . $size_filename); } // ----------------------------------------- // Parse Size Metadata! // ----------------------------------------- $mt = ''; foreach ($settings['action_groups'] as $group) { $name = strtolower($group['group_name']); $mt .= $name . '|' . implode('|', $metadata[$name]) . '/'; } // ----------------------------------------- // Parse Original Image Info // ----------------------------------------- $imginfo = @getimagesize($temp_dir . $filename); $filesize = @filesize($temp_dir . $filename); $width = @$imginfo[0]; $height = @$imginfo[1]; // ----------------------------------------- // IPTC // ----------------------------------------- $iptc = array(); if ($settings['parse_iptc'] == 'yes') { getimagesize($temp_dir . $filename, $info); if (isset($info['APP13'])) { $iptc = iptcparse($info['APP13']); } } // ----------------------------------------- // EXIF // ----------------------------------------- $exif = array(); if ($settings['parse_exif'] == 'yes') { if (function_exists('exif_read_data') === true) { $exif = @read_exif_data($temp_dir . $filename); } } // ----------------------------------------- // XMP // ----------------------------------------- $xmp = ''; if ($settings['parse_xmp'] == 'yes') { $xmp = $this->getXmpData($temp_dir . $filename, 102400); } // ----------------------------------------- // Update Image // ----------------------------------------- $this->EE->db->set('sizes_metadata', $mt); $this->EE->db->set('filesize', $filesize); $this->EE->db->set('width', $width); $this->EE->db->set('height', $height); $this->EE->db->set('extension', trim($extension, '.')); $this->EE->db->set('iptc', base64_encode(serialize($iptc))); $this->EE->db->set('exif', base64_encode(serialize($exif))); $this->EE->db->set('xmp', base64_encode($xmp)); $this->EE->db->where('image_id', $image_id); $this->EE->db->update('exp_channel_images'); // Delete Temp File @unlink($temp_dir . $filename); $o['success'] = 'yes'; exit($this->EE->image_helper->generate_json($o)); }
/** * Pareses and stores all relevant Exif data */ protected function parse() { // read the Exif data of the asset object if possible $this->data = @read_exif_data($this->filepath); // stop on invalid Exif data if (!is_array($this->data)) { return false; } // store the timestamp when the picture has been taken if (isset($this->data['DateTimeOriginal'])) { $this->timestamp = strtotime($this->data['DateTimeOriginal']); } else { $this->timestamp = $this->data['FileDateTime']; if (empty($this->timestamp)) { $stat = stat($this->filepath); $this->timestamp = $stat['mtime']; } } // exposure if (array_key_exists('ExposureTime', $this->data)) { $this->exposure = $this->data['ExposureTime']; } // iso if (array_key_exists('ISOSpeedRatings', $this->data)) { $this->iso = $this->data['ISOSpeedRatings']; } // focal length if (isset($this->data['FocalLength'])) { $this->focalLength = $this->data['FocalLength']; } else { if (isset($this->data['FocalLengthIn35mmFilm'])) { $this->focalLength = $this->data['FocalLengthIn35mmFilm']; } } // aperture $this->aperture = @$this->data['COMPUTED']['ApertureFNumber']; // color or bw $this->isColor = @$this->data['COMPUTED']['IsColor'] == true; }
private function saveFileToDB($filepath) { ini_set('exif.encode_unicode', 'UTF-8'); error_log($filepath); try { try { $exif_ifd0 = read_exif_data($filepath, 'IFD0', 0); $exif_exif = read_exif_data($filepath, 'EXIF', 0); $exif_file = read_exif_data($filepath, 'FILE', 0); } catch (Exception $e) { } $timetaken = null; $filename = $exif_file['FileName']; if (isset($exif_ifd0['DateTime'])) { //We get the date and time the picture was taken try { $rawTimeTaken = $exif_ifd0['DateTime']; error_log("IFDO TIME TAKEN : " . $rawTimeTaken); $timetaken = date("Y-m-d H:i:s", strtotime($rawTimeTaken)); } catch (Exception $e) { } } else { if (isset($exif_exif['DateTimeOriginal'])) { //We get the date and time the picture was taken try { $rawTimeTaken = $exif_exif['DateTimeOriginal']; error_log("EXIF TIME TAKEN : " . $rawTimeTaken); $timetaken = date("Y-m-d H:i:s", strtotime($rawTimeTaken)); } catch (Exception $e) { } } else { $rawTimeTaken = $exif_file['FileDateTime']; $timetaken = date("Y-m-d H:i:s", $rawTimeTaken); } } error_log("NEW TIME TAKEN : " . $timetaken); $fileType = $exif_file['MimeType']; /* $exif = exif_read_data($filepath, 'IFD0'); foreach ($exif as $key => $section) { foreach ($section as $name => $val) { error_log("$key.$name: $val"); } } */ //Reduce file size $img = imagecreatefromjpeg($filepath); $quality = 100; $currentFileSize = filesize($filepath); switch ($currentFileSize) { case $currentFileSize > 3500000: $quality = 15; break; case $currentFileSize > 2000000: $quality = 30; break; case $currentFileSize > 1000000: $quality = 60; break; case $currentFileSize > 500000: $quality = 70; break; } imagejpeg($img, $filepath, $quality); imagedestroy($img); $payload = file_get_contents($filepath); $picture = new Picture(0, "", "", $timetaken, $fileType, $payload, $filename); $picture->latitude = ""; $picture->longitude = ""; $dao = new PictureDAO(); $dayId = $dao->createDay(1, $timetaken); $dao->savePicture($dayId, $picture); unlink($filepath); } catch (Exception $e) { error_log("Exception!!! --- " . $e); //unlink($filepath); } }
function GetImgSize($srcFile, $srcExt = null) { empty($srcExt) && ($srcExt = strtolower(substr(strrchr($srcFile, '.'), 1))); $srcdata = array(); $exts = array('jpg', 'jpeg', 'jpe', 'jfif'); if (function_exists('read_exif_data') && in_array($srcExt, $exts)) { $datatemp = @read_exif_data($srcFile); $srcdata['width'] = $datatemp['COMPUTED']['Width']; $srcdata['height'] = $datatemp['COMPUTED']['Height']; $srcdata['type'] = 2; unset($datatemp); } !$srcdata['width'] && (list($srcdata['width'], $srcdata['height'], $srcdata['type']) = @getimagesize($srcFile)); if (!$srcdata['type'] || $srcdata['type'] == 1 && in_array($srcExt, $exts)) { //noizy fix return false; } return $srcdata; }
/** * 图像处理-获取图像信息 * @param string $source 源文件图片 * @return array(图片的宽、高、类型) */ private function get_img_info($source) { $imginfo = array(); $ext = strtolower(substr(strrchr($source, '.'), 1)); //获取图片类型 $image_type = array(1 => 'gif', 2 => 'jpeg', 3 => 'png', 6 => 'bmp'); if (function_exists('read_exif_data') && in_array($ext, array('jpg', 'jpeg', 'jpe', 'jfif'))) { //jpeg情况 $temp = @read_exif_data($source); $imginfo['width'] = $temp['COMPUTED']['Width']; $imginfo['height'] = $temp['COMPUTED']['Height']; $imginfo['type'] = 2; unset($temp); } if (empty($imginfo)) { //png,gif,bmp list($imginfo['width'], $imginfo['height'], $imginfo['type']) = @getimagesize($source); } $imginfo['type'] = $image_type[$imginfo['type']]; return $imginfo; }