function AkImage($image_path = null, $tranform_using = AK_IMAGE_DRIVER) { $this->Transform =& Image_Transform::factory($tranform_using); if (!empty($image_path)) { $this->load($image_path); } }
function AkImage($image_path = null, $tranform_using = AK_IMAGE_DRIVER) { $this->Transform =& Image_Transform::factory($tranform_using); if (PEAR::isError($this->Transform)) { trigger_error($this->Transform->getMessage(), E_USER_ERROR); } if (!empty($image_path)) { $this->load($image_path); } }
protected function creaateTransform() { if (!defined('IMAGE_TRANSFORM_IM_PATH') && sfConfig::has('op_imagemagick_path')) { // follow 2.x format (for BC reason) $path = dirname(sfConfig::get('op_imagemagick_path')) . DIRECTORY_SEPARATOR; define('IMAGE_TRANSFORM_IM_PATH', $path); } $result = Image_Transform::factory('IM'); if (PEAR::isError($result)) { throw new RuntimeException($result->getMessage()); } return $result; }
public static function transform_image($srcSpec, $destSpec, $size = '') { $config = cmsms()->GetConfig(); require_once $config['root_path'] . '/lib/filemanager/ImageManager/Classes/Transform.php'; if ($size == '') { $cge = cge_utils::get_cge(); $size = $cge->GetPreference('thumbnailsize'); } $it = new Image_Transform(); $img = $it->factory($config['image_manipulation_prog']); $img->load($srcSpec); if ($img->img_x < $img->img_y) { $long_axis = $img->img_y; } else { $long_axis = $img->img_x; } if ($long_axis > $size) { $img->scaleByLength($size); $img->save($destSpec, 'jpeg'); } else { $img->save($destSpec, 'jpeg'); } $img->free(); }
function _prepareUpload() { if ($this->imageDir !== null && $this->_isValidUploadDir($this->imageDir)) { $dir1 = substr($this->destFile, 0, 2); $dir2 = $dir1 . '/' . substr($this->destFile, 2, 2); $dir1 = $this->imageDir . '/' . $dir1; $dir2 = $this->imageDir . '/' . $dir2; if (!is_dir($dir1)) { if (!mkdir($dir1, 0777)) { return PEAR::raiseError('Could not create: ' . $dir1); } } if (!is_dir($dir2)) { if (!mkdir($dir2, 0777)) { return PEAR::raiseError('Could not create: ' . $dir2); } } $im = Image_Transform::factory($this->transformDriver); if (!PEAR::isError($im)) { $result = $im->load($this->sourceFile); if (!PEAR::isError($result)) { $result = $im->scale($this->thumbSize); if (!PEAR::isError($result)) { $thumb = $dir2 . '/t_' . $this->destFile; $result = $im->save($thumb); if (!PEAR::isError($result)) { $im->free(); } else { return $result; } } else { return $result; } } else { return $result; } } else { return $im; } $this->destFile = $dir2 . '/' . $this->destFile; return true; } else { return PEAR::raiseError('Invalid image directory: ' . $this->imageDir); } }
function manipulate($img_file, $action, $values) { global $path, $save_file, $BASE_DIR, $BASE_ROOT; $img_location = $BASE_DIR . $BASE_ROOT . '/'; //Load the Image Manipulation Driver $img = Image_Transform::factory(IMAGE_CLASS); $img->load($img_location . $img_file); switch ($action) { case 'crop': $img->crop(intval($values[0]), intval($values[1]), intval($values[2]), intval($values[3])); break; case 'scale': $img->resize(intval($values[0]), intval($values[1])); break; case 'rotate': $img->rotate(floatval($values[0])); break; case 'flip': if ($values[0] == 'hoz') { $img->flip(true); } else { if ($values[0] == 'ver') { $img->flip(false); } } break; case 'save': if (isset($save_file)) { $quality = intval($values[1]); if ($quality < 0) { $quality = 85; } $img->save($img_location . $save_file, $values[0], $quality); } break; } //get the unique file name $filename = $img->createUnique($img_location); //save the manipulated image $img->save($img_location . $filename); $img->free(); $imagesize = @getimagesize($filename); return array($filename, $imagesize[3]); }
function make_thumbs($img) { global $BASE_DIR, $BASE_URL; $path_info = pathinfo($img); $path = $path_info['dirname'] . "/"; $img_file = $path_info['basename']; $thumb = $path . '.' . $img_file; $img_info = getimagesize($BASE_DIR . $path . $img_file); $w = $img_info[0]; $h = $img_info[1]; $nw = 96; $nh = 96; if ($w <= $nw && $h <= $nh) { header('Location: ' . $BASE_URL . $path . $img_file); exit; } if (is_file($BASE_DIR . $thumb)) { $t_mtime = filemtime($BASE_DIR . $thumb); $o_mtime = filemtime($BASE_DIR . $img); if ($t_mtime > $o_mtime) { //echo $BASE_URL.$path.'.'.$img_file; header('Location: ' . $BASE_URL . $path . '.' . $img_file); exit; } } $img_thumbs = Image_Transform::factory(IMAGE_CLASS); $img_thumbs->load($BASE_DIR . $path . $img_file); if ($w > $h) { $nh = unpercent(percent($nw, $w), $h); } else { if ($h > $w) { $nw = unpercent(percent($nh, $h), $w); } } $img_thumbs->resize($nw, $nh); $img_thumbs->save($BASE_DIR . $thumb); $img_thumbs->free(); chmod($BASE_DIR . $thumb, 0666); if (is_file($BASE_DIR . $thumb)) { //echo "Made:".$BASE_URL.$path.'.'.$img_file; header('Location: ' . $BASE_URL . $path . '.' . $img_file); exit; } }
/** * Perfoms manipulation * */ public function manipulate($from, $to, $options) { if (!isset($options['geometry'])) { throw new Yag_Manipulator_Adapter_Exception('ImageTransform requires the \'geometry\' option to be set'); } $matches = array(); preg_match('/(c)?([0-9]+)x([0-9]+)/', $options['geometry'], $matches); if (empty($matches[2])) { throw new Yag_Manipulator_Adapter_Exception('Invalid geometry pattern \'' . $options['geometry'] . '\''); } if (empty($matches[3])) { throw new Yag_Manipulator_Adapter_Exception('Invalid geometry pattern \'' . $options['geometry'] . '\''); } /* * Needs to be required here, otherwise getting "Cannot access self:: when * no class scope is active" from PEAR, probably only in autoload context. */ require_once 'Image/Transform.php'; /* * Here comes the ugly pear integration... */ $imageTransform = Image_Transform::factory('GD'); if (PEAR::isError($imageTransform)) { throw new Yag_Manipulator_Adapter_Exception($imageTransform->getMessage()); } $response = $imageTransform->load($from); if (PEAR::isError($response)) { throw new Yag_Manipulator_Adapter_Exception($response->getMessage()); } if (empty($matches[1])) { $this->_fit($imageTransform, $matches[2], $matches[3]); } else { $this->_cropResize($imageTransform, $matches[2], $matches[3]); } $response = $imageTransform->save($to); if (PEAR::isError($response)) { throw new Yag_Manipulator_Adapter_Exception($response->getMessage()); } }
/** * Muestra la imagen en pantalla. * @param type int $width * @param type int $height */ public function display($width, $height, $crop) { require_once PEAR . 'Image/Transform.php'; $it =& \Image_Transform::factory('GD'); if (\PEAR::isError($it)) { die($it->getMessage() . '<br />' . $it->getDebugInfo()); } $cache = $this->dir_cache . $width . "x{$height}" . ($crop ? "c" : "") . DIRECTORY_SEPARATOR; if (!is_dir($cache)) { mkdir($cache); } $cache .= $this->name; //comprova si existeix catxe if (!is_file($cache)) { $it->load($this->dir_originals . $this->name); if ($crop) { if ($width > $height) { $f = $height / $width; $new_y = round($it->img_x * $f); // if ($new_y < $it->img_y) { $at = round(($it->img_y - $new_y) / 2); $it->crop($it->img_x, $new_y, 0, $at); $it->img_y = $new_y; } $it->resized = false; $it->scaleByX($width); } else { $f = $width / $height; $new_x = round($it->img_y * $f); if ($new_x < $it->img_x) { $at = round(($it->img_x - $new_x) / 2); $it->crop($new_x, $it->img_y, $at, 0); $it->img_x = $new_x; } $it->resized = false; $it->scaleByY($height); } } else { $it->fit($width, $height); } $it->save($cache); chmod($cache, 0777); } header("Content-type: " . $this->type); readfile($cache); return true; }
function _regenerateThumbUnit($photo, $v, &$obj, $field) { $firstRedim = true; if (!isset($v['x']) && !isset($v['y']) && !isset($v['maxx']) && !isset($v['maxy']) && !isset($v['overlay'])) { copy($photo, IMAGES_UPLOAD_FOLDER . $v['path'] . '/' . $obj->{$field}); $name = $obj->{$field}; } else { $ph = new traitephoto(); $ph->photo = $photo; $ph->path = IMAGES_UPLOAD_FOLDER . $v['path']; $ph->nomsouhaite = $obj->{$field}; $ph->qualite = $v['quality']; $ph->width = $v['x']; $ph->height = $v['y']; $ph->maxx = $v['maxx']; $ph->maxy = $v['maxy']; if (isset($v['overlay']) && $firstRedim) { $type = 'png'; $ph->path = FileUtils::getFolderPath(TMP_PATH); $ph->nomsouhaite = 'overlaytemp.png'; } else { $type = $v['type'] ? $v['type'] : null; } $ph->resize(); $name = $ph->save($type); if (isset($v['overlay']) && $firstRedim) { $source = $v['path'] . '/' . $name; $infosSource =& Image_Transform::factory('GD'); if (PEAR::isError($infosSource)) { throw new Exception($infosSource->getMessage()); } $tmp = FileUtils::getFolderPath(TMP_PATH); $infosSource->load($tmp . 'overlaytemp.png'); $infosOver =& Image_Transform::factory('GD'); $infosOver->load(APP_ROOT . $v['overlay'][0]); $opts = array('width' => $infosSource->getImageWidth(), 'height' => $infosSource->getImageHeight(), 'transparent' => true); $img =& Image_Canvas::factory('png', $opts); $img->image(array('filename' => TMP_PATH . 'overlaytemp.png', 'x' => 0, 'y' => 0)); switch ($v['overlay']['position']) { case 'top-left': $x = 0; $y = 0; break; case 'top-right': $x = $infosSource->getImageWidth() - $infosOver->getImageWidth(); $y = 0; break; case 'bottom-left': $x = 0; $y = $infosSource->getImageHeight() - $infosOver->getImageHeight(); break; case 'bottom-right': $x = $infosSource->getImageWidth() - $infosOver->getImageWidth(); $y = $infosSource->getImageHeight() - $infosOver->getImageHeight(); break; default: $x = 0; $y = 0; break; } $img->image(array('filename' => APP_ROOT . $v['overlay'][0], 'x' => $x, 'y' => $y)); $img->save(array('filename' => $tmp . 'overlaytemp.png')); $ph = new traitephoto(); $ph->photo = $tmp . 'overlaytemp.png'; $ph->path = IMAGES_UPLOAD_FOLDER . $v['path']; $ph->nomsouhaite = $obj->{$field}; $ph->qualite = $v['quality']; $ph->resize(); $name = $ph->save($v['type'] ? $v['type'] : null); unset($ph); } } if ($name != $obj->{$field}) { @unlink(IMAGES_UPLOAD_FOLDER . $v['path'] . '/' . $obj->{$field}); } unset($ph); return $name; }
/** * Image_Transform_Driver_IM::_get_image_details() * * @param string $image the path and name of the image file * @return none */ function _get_image_details($image) { $retval = Image_Transform::_get_image_details($image); if (PEAR::isError($retval)) { unset($retval); if (!System::which(IMAGE_TRANSFORM_IM_PATH . 'identify' . (OS_WINDOWS ? '.exe' : ''))) { $this->isError(PEAR::raiseError('Couldn\'t find "identify" binary', IMAGE_TRANSFORM_ERROR_UNSUPPORTED)); } $cmd = $this->_prepare_cmd(IMAGE_TRANSFORM_IM_PATH, 'identify', '-format %w:%h:%m ' . escapeshellarg($image)); exec($cmd, $res, $exit); if ($exit == 0) { $data = explode(':', $res[0]); $this->img_x = $data[0]; $this->img_y = $data[1]; $this->type = strtolower($data[2]); $retval = true; } else { return PEAR::raiseError("Cannot fetch image or images details.", true); } } return $retval; }
/** * Frontendausgabe CMS:tag image * * @Args: int type_container -> id von cms:tag <cms:lay type="container" id="XX" /> * int type_number -> Entspricht der Verdopplungsid eines Containers * int type_typenumber -> Eindeutige Id des Contents * array $type_config -> Attribute und deren Werte des cms:tags * @Return String Content * @Access public */ function type_output_image($type_container, $type_number, $type_typenumber, $type_config) { global $sess, $DB_cms, $cms_db, $cfg_cms, $cfg_client, $idcatside, $mod_lang, $content, $cms_side; global $client, $cms_edittype, $cms_mod, $con_side; //catch vars and arrays from the tag attributes eval(_type_get_dynamic_val_string($type_config)); // URL formatieren $mod_content = is_array($content[$type_container][$type_number]) ? $content[$type_container][$type_number]['4'][$type_typenumber]['1'] : ''; $match = array(); if (preg_match_all('#^cms://(idfile|idfilethumb)=(\\d+)$#', $mod_content, $match)) { $is_thumb = $match['1']['0'] == 'idfilethumb'; $id = $match['2']['0']; $sql = "SELECT \n\t\t\t\t\tA.*, B.filetype, C.dirname \n\t\t\t\tFROM \n\t\t\t\t\t" . $cms_db['upl'] . " A \n\t\t\t\t\tLEFT JOIN " . $cms_db['filetype'] . " B USING(idfiletype) \n\t\t\t\t\tLEFT JOIN " . $cms_db['directory'] . " C ON A.iddirectory=C.iddirectory \n\t\t\t\tWHERE \n\t\t\t\t\tA.idclient='{$client}' \n\t\t\t\t\tAND idupl='" . $id . "'"; $db = new DB_cms(); $db->query($sql); if ($db->next_record()) { $mod_url = $cfg_client['upl_htmlpath'] . $db->f('dirname') . $db->f('filename'); $mod_path = $cfg_client['upl_path'] . $db->f('dirname') . $db->f('filename'); $fileid = $db->f('idupl'); $original_x = $db->f('pictwidth'); $original_y = $db->f('pictheight'); $pic_filetype = $db->f('filetype'); $pic_dirname = $db->f('dirname'); $pic_filename = $db->f('filename'); $pic_idfiletype = $db->f('idfiletype'); $pic_iddirectory = $db->f('iddirectory'); $thumb_x = $db->f('pictthumbwidth'); $thumb_y = $db->f('pictthumbheight'); $pic_db_desc = $db->f('description'); $pic_db_titel = $db->f('titel'); $file_size = $db->f('filesize'); if (in_array($type_config['mode'], array('thumb', 'thumbamplitude', 'thumbwidth', 'thumbheight', 'thumburl', 'thumbpath')) && $pic_filetype != 'gif' && ($thumb_x != 0 || $thumb_y != 0) || $is_thumb) { $original_x = $thumb_x; $original_y = $thumb_y; $name_length = strlen($pic_filename); $extension_length = strlen($pic_filetype); $new_name = substr($pic_filename, 0, $name_length - $extension_length - 1); $new_name .= $cfg_client['thumbext'] . '.' . $pic_filetype; $mod_url = $cfg_client['upl_htmlpath'] . $db->f('dirname') . $new_name; $mod_path = $cfg_client['upl_path'] . $db->f('dirname') . $new_name; $pic_filename = $new_name; } } } if ($type_config['autoresize'] == 'true' && !empty($mod_url)) { // Extract needed data $is_aspectratio = $type_config['aspectratio'] != 'false' ? true : false; $extracted_size = _type_calculate_new_image_size($original_x, $original_y, $type_config['width'], $type_config['height'], $is_aspectratio); $new_x = $extracted_size['width']; $new_y = $extracted_size['height']; // Skip transform if new image have the same properties as the original image, if ($new_x == $original_x && $new_y == $original_y) { $skip_transform = true; } // If _type_calculate_new_image_size(..) throwed an error, new_x and new_y are not set, skip transform if (!empty($new_x) && !empty($new_y)) { $name_length = strlen($pic_filename); $extension_length = strlen($pic_filetype); // New filename for image $new_name = substr($pic_filename, 0, $name_length - $extension_length - 1); $new_name .= '_' . $new_x . 'X' . $new_y . '.' . $pic_filetype; if (file_exists($cfg_client['upl_path'] . $pic_dirname . $new_name)) { // manipulate current CMS:tag values with new transform values $mod_url = $cfg_client['upl_htmlpath'] . $pic_dirname . $new_name; $mod_path = $cfg_client['upl_path'] . $pic_dirname . $new_name; $type_config['width'] = $original_x = $new_x; $type_config['height'] = $original_y = $new_y; } else { if ($skip_transform || $cfg_cms['image_mode'] == 'gd' && $pic_filetype == 'gif') { $type_config['width'] = $original_x = $new_x; $type_config['height'] = $original_y = $new_y; } else { // Create image only if file doesn't exist, isn't GD with filetype gif // and imagedriver isn't empty if (!($cfg_cms['image_mode'] == 'gd' && $pic_filetype == 'gif') && !empty($cfg_cms['image_mode'])) { // IMAGE TRANSFORM global $cms_image; require_once 'Image/Transform.php'; $cms_image = is_object($cms_image) ? $cms_image : Image_Transform::factory($cfg_cms['image_mode']); $cms_image->load($mod_path); $cms_image->resize($new_x, $new_y); $cms_image->save($cfg_client['upl_path'] . $pic_dirname . $new_name); $cms_image->free(); global $fm; $fm->insert_file((int) $client, $new_name, (int) $pic_iddirectory, (int) $pic_idfiletype); //manipulate current CMS:tag values with new transform values $mod_url = $cfg_client['upl_htmlpath'] . $pic_dirname . $new_name; $mod_path = $cfg_client['upl_path'] . $pic_dirname . $new_name; $type_config['width'] = $original_x = $new_x; $type_config['height'] = $original_y = $new_y; } } } } } // Wenn amplitude angefordert - Ausgabe FRONTEND + BACKEND if ($type_config['mode'] == 'amplitude' || $type_config['mode'] == 'thumbamplitude') { return 'width="' . $original_x . '" height="' . $original_y . '"'; } // Wenn nur filesize gefordert, Ausgabe - FRONTEND und BACKEND if ($type_config['mode'] == 'filesize') { return $file_size; } // Wenn nur id der Datei gefordert, Ausgabe - FRONTEND und BACKEND if ($type_config['mode'] == 'id') { return $fileid; } // Wenn dateimanager titel angefordert - Ausgabe FRONTEND + BACKEND if ($type_config['mode'] == 'fmtitle') { return $pic_db_titel; } // Wenn dateimanager beschreibung angefordert - Ausgabe FRONTEND + BACKEND if ($type_config['mode'] == 'fmdesc') { return $pic_db_desc; } // Wenn Filetype angefordert - Ausgabe FRONTEND + BACKEND if ($type_config['mode'] == 'filetype') { return $pic_filetype; } // Wenn Bildhöhe angefordert - Ausgabe FRONTEND + BACKEND if ($type_config['mode'] == 'width' || $type_config['mode'] == 'thumbwidth') { return $original_x; } // Wenn Bildweite angefordert - Ausgabe FRONTEND + BACKEND if ($type_config['mode'] == 'height' || $type_config['mode'] == 'thumbheight') { return $original_y; } // Wenn nur url gefordert - Ausgabe FRONTEND + BACKEND if ($type_config['mode'] == 'url' || $type_config['mode'] == 'thumburl') { return $mod_url; } // Wenn nur pfad gefordert - Ausgabe FRONTEND + BACKEND if ($type_config['mode'] == 'path' || $type_config['mode'] == 'thumbpath') { return $mod_path; } // Beschreibung raussuchen $mod_descr = is_array($content[$type_container][$type_number]) ? htmlspecialchars($content[$type_container][$type_number]['5'][$type_typenumber]['1'], ENT_COMPAT, 'UTF-8') : ''; // Wenn nur Beschreibung gefordert - Ausgabe FRONTEND + BACKEND if ($type_config['mode'] == 'desc') { return $mod_descr; } // Bildgroesse ermitteln // Wenn defaultimage if (empty($mod_url)) { $pic_width = !empty($type_config['defaultwidth']) ? $type_config['defaultwidth'] : $type_config['width']; $pic_height = !empty($type_config['defaultheight']) ? $type_config['defaultheight'] : $type_config['height']; // wenn schon ausgewaehltes Bild } else { $pic_width = empty($type_config['width']) ? '' : $type_config['width']; $pic_height = empty($type_config['height']) ? '' : $type_config['height']; // Bildgroesse soll automatisch ermittelt werden } if ((empty($type_config['width']) || $type_config['width'] == 'true' || empty($type_config['height']) || $type_config['height'] == 'true') && !empty($mod_url)) { //Bildweite aus der DB if ($type_config['width'] == 'true' || empty($type_config['width'])) { $pic_width = $original_x; } //Bildhoehe aus der DB if ($type_config['height'] == 'true' || empty($type_config['height'])) { $pic_height = $original_y; } } // defaultimage, wenn nicht gesetzt dann transparentes bild einsetzen if ($type_config['defaultimage']) { $mod_def = $type_config['defaultimage']; } else { $mod_def = $cfg_client['space']; } if (!$mod_url) { $mod_url = $mod_def; } // make global edit_all url if (_type_check_editall($cms_side, $type_config)) { $cms_edittype[$type_container][$type_number][] = '4-' . $type_typenumber . ',5-' . $type_typenumber; } // CSS ausfindig machen $css = _type_get_style($type_config['styleclass'], $type_config['styleid'], $type_config['styledb']); // Wenn style angefordert oder default if ($type_config['mode'] == 'style') { return $css['style']; } // Wenn styletype angefordert oder default if ($type_config['mode'] == 'styletype') { return $css['type']; } // Wenn fullstyle angefordert oder default if ($type_config['mode'] == 'fullstyle') { return $css['fullstyle']; } // Bild generieren if (_type_check_editable($cms_side['edit'], $type_config['editable'], $cms_side['view'], isset($cms_side['edit_all']))) { // Bearbeitungsbutton / layer erzeugen if ($type_config['menuoptions'] != 'false') { $title = empty($type_config['title']) ? $mod_lang['type_image'] : $type_config['title']; // advanced Modus if ($type_config['menuoptions'] == 'advanced') { $new = false; $delete = false; $up = false; $down = false; // neu anlegen & loeschen if ($type_number != '1' || $mod_url != $mod_def) { $new = true; $delete = true; } // nach oben verschieben if ($type_number != '1') { $up = true; } // nach unten verschieben if ($mod_url != $mod_def && $cms_mod['modul']['lastentry'] != 'true') { $down = true; } } $ids = array(4, 5); $infos = array('container_number' => $type_container, 'cmstag_id' => $type_typenumber, 'mod_repeat_id' => $type_number, 'title' => $title, 'base_url' => $con_side[$idcatside]['link'], 'mode' => $type_config['menuoptions']); //menu erstellen $editbutton_image = _type_get_layer_menu($ids, $infos, $delete, $new, $up, $down); //Wenn nur editbutton gefordert - Ausgabe BACKEND if ($type_config['mode'] == 'editbutton') { return $editbutton_image; } } // if ($type_config['menuoptions'] != 'false') { $mod_content = sprintf("<img src=\"{$mod_url}\"%s%s%s " . $css['fullstyle'] . " />", $mod_descr != '' ? ' alt="' . $mod_descr . '" title="' . $mod_descr . '"' : " alt=\"\"", $pic_width ? ' width="' . ($pic_width - 29) . '"' : '', $pic_height ? ' height="' . ($pic_height - 8) . '"' : ''); $mod = '<span style="background-color: #DBE3EF; border: 1px solid black; padding: 3px;">' . $mod_content . '<span style="padding-left: 3px;">' . $editbutton_image . '</span></span>'; $mod = $editbutton . $mod; } else { if ($type_config['mode'] == 'editbutton') { return; } return sprintf("<img src=\"{$mod_url}\"%s%s%s " . $css['fullstyle'] . " />", $mod_descr != '' ? ' alt="' . $mod_descr . '" title="' . $mod_descr . '"' : " alt=\"\"", $pic_width ? ' width="' . $pic_width . '"' : '', $pic_height ? ' height="' . $pic_height . '"' : ''); } } else { // Wenn nur editbutton gefordert - keine Ausgabe Frontend if ($type_config['mode'] == 'editbutton') { return; } // Ausgabe image - Frontend $mod = sprintf("<img src=\"{$mod_url}\"%s%s%s " . $css['fullstyle'] . " />", $mod_descr != '' ? ' alt="' . $mod_descr . '" title="' . $mod_descr . '"' : " alt=\"\"", $pic_width ? ' width="' . $pic_width . '"' : '', $pic_height ? ' height="' . $pic_height . '"' : ''); } return $mod; }
protected function creaateTransform() { $transform = Image_Transform::factory('GD'); $transform->setOption('scaleMethod', 'pixel'); return $transform; }
function smarty_function_image($params, &$smarty) { require_once $smarty->_get_plugin_filepath('modifier', 'curlang'); $src = ""; $width = 0; $height = 0; $bevel = A_MODE == 1 ? 4 : 0; $attr = ""; $DOMAIN = !empty($params['domain']) ? preg_replace("/[^a-zA-Z0-9]+/i", "", $params['domain']) : A::$DOMAIN; if (!empty($params['data']) && is_array($params['data'])) { if (array_key_exists('path', $params['data'])) { $row = $params['data']; unset($params['data']); } elseif (isset($params['data'][0]) && array_key_exists('path', $params['data'][0])) { $row = array_shift($params['data']); } if (!empty($row['path'])) { $src = $row['path']; } } elseif (!empty($params['id'])) { if ($row = A::$DB->getRowById($params['id'], $DOMAIN . "_images")) { $src = $row['path']; } } $alt = !empty($row['caption']) ? $row['caption'] : ""; foreach ($params as $_key => $_val) { switch ($_key) { case "id": case "data": case "domain": case "lightbox": case "popup": case "noimgheight": case "empty": break; case "src": $src = $_val; break; case "width": $width = $_val; if (!isset($row['width'])) { $attr .= " {$_key}=\"{$width}\""; } elseif ($width <= $row['width']) { if (!empty($scale)) { $_width = ceil($row['width'] / $scale); if ($_width < $width) { $width = (int) $_width; } //$attr.=" $_key=\"$width\""; $width = 0; } else { $scale = $row['width'] / $width; $attr .= " {$_key}=\"{$width}\""; } } elseif ($width > $row['width'] && !empty($scale)) { $_width = ceil($row['width'] / $scale); if ($_width < $width) { $width = (int) $_width; } $attr .= " {$_key}=\"{$width}\""; $width = 0; } break; case "height": $height = $_val; if (!isset($row['height'])) { $attr .= " {$_key}=\"{$height}\""; } elseif ($height <= $row['height']) { if (!empty($scale)) { $_height = ceil($row['height'] / $scale); if ($_height < $height) { $height = (int) $_height; } //$attr.=" $_key=\"$height\""; } elseif ($row['height'] > $row['width']) { $scale = $row['height'] / $height; $attr .= " {$_key}=\"{$height}\""; } } break; case "bevel": $bevel = (int) $_val; break; case "imgid": $attr .= " id=\"{$_val}\""; break; case "alt": $alt = $_val; break; default: $attr .= " {$_key}=\"{$_val}\""; } } $attr .= " alt=\"" . htmlspecialchars($alt) . "\""; if (!empty($src)) { $src = preg_replace("/^\\//i", "", $src); } elseif (!empty($params['empty'])) { $src = "templates/" . $DOMAIN . "/images/" . preg_replace("/[.]{2..}/i", "", $params['empty']); if (is_file($src)) { return "<img src=\"/{$src}\"{$attr}/>"; } } else { return ""; } if ($width > 0 && (!isset($row['width']) || $width < $row['width']) || $height > 0 && (!isset($row['height']) || $height < $row['height'])) { $path = pathinfo($src); if (preg_match("/^[.\\/]*(files|images)\\/([a-zA-Z0-9-_]+)\\//i", $src, $matches)) { $cachename = 'cache/images/' . $matches[2] . '/' . $path['filename']; } else { $cachename = 'cache/images/' . $path['filename']; } if ($width > 0) { $cachename .= '_w' . $width; } if ($height > 0) { $cachename .= '_h' . $height; } if ($bevel > 0) { $cachename .= '_b' . $bevel; } $cachename .= '.' . mb_strtolower($path['extension']); if (!is_file($cachename) && is_file($src)) { require_once "Image/Transform.php"; $it = Image_Transform::factory('GD'); $it->load($src); if ($width > 0 && $height > 0 && ($it->img_x > $width || $it->img_y > $height)) { if ($width < 0 || $height < 0) { return ""; } if ($it->img_x > $width) { $it->scaleByX($width); } if ($it->new_y > $height) { $it->crop($width, $height, 0, 0); } } elseif ($width > 0 && $it->img_x > $width) { $it->scaleByX($width); } elseif ($height > 0 && $it->img_y > $height) { $it->scaleByY((int) $height); } if (!empty($matches[2])) { if (!is_dir('cache/images/' . $matches[2])) { mkdir('cache/images/' . $matches[2]); } } $it->save($cachename, '', 100); if ($bevel > 0 && $bevel <= 5) { require_once "Image/Tools.php"; $border = Image_Tools::factory('border'); $border->set('image', $cachename); $border->set('style', 'bevel'); $border->set('params', array($bevel, '#ffffff', '#000000')); switch ($it->type) { case 'jpg': case 'jpeg': $border->save($cachename, IMAGETYPE_JPEG); break; case 'gif': $border->save($cachename, IMAGETYPE_GIF); break; case 'png': $border->save($cachename, IMAGETYPE_PNG); break; } } } if (is_file($cachename)) { $image = "<img src=\"/{$cachename}\"{$attr}/>"; } else { $image = "<img src=\"/image.php?src=" . urlencode($src) . "&x={$width}&y={$height}&b={$bevel}\"{$attr}/>"; } } elseif (isset($row)) { $attr = str_replace(" width=\"{$row['width']}\"", "", $attr); $attr = str_replace(" height=\"{$row['height']}\"", "", $attr); $image = "<img src=\"/{$src}\" width=\"{$row['width']}\" height=\"{$row['height']}\"{$attr}/>"; $params['popup'] = false; if (empty($params['data'])) { $params['lightbox'] = false; } } else { $image = "<img src=\"/{$src}\"{$attr}/>"; $params['popup'] = false; if (empty($params['data'])) { $params['lightbox'] = false; } } if (!empty($params['popup']) && !empty($row)) { if ($params['popup'] === true) { $params['popup'] = "Увеличить"; } $caption = !empty($params['alt']) ? $params['alt'] : $row['caption']; $caption = preg_replace("/[^a-zA-Zа-яА-Я0-9 ]+/iu", " ", smarty_modifier_curlang($caption)); if (A_MODE == A_MODE_FRONT && is_file($css = "templates/" . A::$DOMAIN . "/imagewin.css")) { $image = "<a href=\"javascript:open_imgwindow('/{$src}','{$caption}',{$row['width']},{$row['height']},'/{$css}')\" title=\"{$params['popup']}\">{$image}</a>"; } else { $image = "<a href=\"javascript:open_imgwindow('/{$src}','{$caption}',{$row['width']},{$row['height']})\" title=\"{$params['popup']}\">{$image}</a>"; } } elseif (!empty($params['lightbox']) && !empty($row)) { $caption = !empty($params['alt']) ? $params['alt'] : $row['caption']; $caption = smarty_modifier_curlang($caption); $group = !empty($params['group']) ? "[{$params['group']}]" : "[default]"; $image = "<a href=\"/{$src}\" rel=\"lightbox{$group}\" title=\"{$caption}\">{$image}</a>"; if (!empty($params['data'])) { while ($row = array_shift($params['data'])) { $row['caption'] = smarty_modifier_curlang($row['caption']); $image .= "<a href=\"/{$row['path']}\" rel=\"lightbox{$group}\" title=\"{$row['caption']}\" style=\"display:none\"></a>"; } } } return $image; }
public function __construct() { $this->photo = ""; $this->nomimg = ""; $this->width = 0; $this->height = 0; $this->path = ""; $this->pourcent = 0; $this->maxx = 0; $this->maxy = 0; $this->perimetre = 0; $this->gauche = 0; $this->haut = 0; $this->droit = 0; $this->bas = 0; $this->angle = 0; $this->surface = 0; $this->qualite = 60; $this->nomsouhaite = ""; $this->gd = 1; $this->server = ""; if (extension_loaded('imagick') || function_exists('dl') && @dl('imagick')) { $this->imgT = Image_Transform::factory("Imagick3"); if (PEAR::isError($this->imgT)) { Log::error($this->imgT->getMessage()); } Log::info('Using Imagick3 as image driver'); } else { $this->imgT = Image_Transform::factory("GD"); Log::info('Using GD as image driver'); } }
function resizeImage($fName, $newName, $maxWidth, $maxHeigth) { $resized = false; print "resize {$fName} to {$newName}\n"; //$img = Image_Transform::factory("GD"); $img = Image_Transform::factory("IM"); if (PEAR::isError($img)) { print $img->getMessage(); return $resized; } $img->load($fName); if ($img->getImageWidth() > $maxWidth) { $resized = true; $img->scaleByX($maxWidth); } $img->save($newName, "", 100); $img->load($newName); if ($img->getImageHeight() > $maxHeigth) { $resized = true; $img->scaleByY($maxHeigth); } $img->save($newName, "", 100); $img->free(); return $resized; }
/** * Create a thumbnail for an image. * This is a fairly smart routine that first detects if a thumbnail already exists, or if one can be written anyways, and then uses the system preferences * to generate the thumbnail file. * * @param string complete file specification to a source image * @author calguy1000 * @since 1.11 * @returns string complete file specification to a thumbnail for an image. Or null. */ public static function generate_thumbnail($srcfile) { if (!file_exists($srcfile)) { return; } $ext = strtolower(strrchr($srcfile, '.')); while (startswith($ext, '.')) { $ext = substr($ext, 1); } if (!in_array($ext, array('jpg', 'jpeg', 'png', 'bmp', 'gif'))) { return; // not gonna create a thumb on anything but an image. } $dn = dirname($srcfile); $bn = basename($srcfile); if (startswith($bn, 'thumb_')) { return; // not gonna create a thumb on a thumb. } $thumb = cms_join_path($dn, 'thumb_' . $bn); if (file_exists($thumb) && filemtime($thumb) > filemtime($srcfile)) { // nothing to do, thumb exists and is newer than the source. return $thumb; } if (!is_writable($dn)) { // can't write. return; } $config = cmsms()->GetConfig(); require_once $config['root_path'] . '/lib/filemanager/ImageManager/Classes/Transform.php'; $width = get_site_preference('thumbnail_width', 96); $height = get_site_preference('thumbnail_height', 96); $transform = new Image_Transform(); $img = $transform->factory($config['image_manipulation_prog']); $img->load($srcfile); $img->resize($width, $height); $img->save($thumb); return $thumb; }
/** * Process the actions, crop, scale(resize), rotate, flip, and save. * When ever an action is performed, the result is save into a * temporary image file, see createUnique on the filename specs. * It does not return the saved file, alway returning the tmp file. * @param string $action, should be 'crop', 'scale', 'rotate','flip', or 'save' * @param string $relative the relative image filename * @param string $fullpath the fullpath to the image file * @return array with image information * <code>array('src'=>'url of the image', 'dimensions'=>'width="xx" height="yy"', * 'file'=>'image file, relative', 'fullpath'=>'full path to the image');</code> */ function processAction($action, $relative, $fullpath) { $params = ''; if (isset($_GET['params'])) { $params = $_GET['params']; } $values = explode(',', $params, 4); $saveFile = $this->getSaveFileName($values[0]); $img = Image_Transform::factory(IMAGE_CLASS); $img->load($fullpath); switch ($action) { case 'replace': // 'ImageManager.php' handled the uploaded file, it's now on the server. // If maximum size is specified, constrain image to it. $dimensionsIndex = isset($_REQUEST['uploadSize']) ? $_REQUEST['uploadSize'] : 0; if ($this->manager->config['maxWidth'][$dimensionsIndex] > 0 && $this->manager->config['maxHeight'][$dimensionsIndex] > 0 && ($img->img_x > $this->manager->config['maxWidth'][$dimensionsIndex] || $img->img_y > $this->manager->config['maxHeight'][$dimensionsIndex])) { $percentage = min($this->manager->config['maxWidth'][$dimensionsIndex] / $img->img_x, $this->manager->config['maxHeight'][$dimensionsIndex] / $img->img_y); $img->scale($percentage); } break; case 'watermark': // loading target image $functionName = 'ImageCreateFrom' . $img->type; if (function_exists($functionName)) { $imageResource = $functionName($fullpath); } else { echo "<script>alert(\"Error when loading '" . basename($fullpath) . "' - Loading '" . $img->type . "' files not supported\");</script>"; return false; } // loading watermark $watermarkFullPath = $_GET['watermarkFullPath']; $watermarkImageType = strtolower(substr($watermarkFullPath, strrpos($watermarkFullPath, ".") + 1)); if ($watermarkImageType == "jpg") { $watermarkImageType = "jpeg"; } if ($watermarkImageType == "tif") { $watermarkImageType = "tiff"; } $functionName = 'ImageCreateFrom' . $watermarkImageType; if (function_exists($functionName)) { $watermarkResource = $functionName($watermarkFullPath); } else { echo "<script>alert(\"Error when loading '" . basename($watermarkFullPath) . "' - Loading '" . $img->type . "' files not supported\");</script>"; return false; } $numberOfColors = imagecolorstotal($watermarkResource); $watermarkX = isset($_GET['watermarkX']) ? $_GET['watermarkX'] : -1; $watermarkY = isset($_GET['watermarkY']) ? $_GET['watermarkY'] : -1; $opacity = $_GET['opacity']; // PNG24 watermark on GIF target needs special handling // PNG24 watermark with alpha transparency on other targets need also this handling if ($watermarkImageType == "png" && $numberOfColors == 0 && ($img->type == "gif" || $opacity < 100)) { require_once 'Classes/api.watermark.php'; $watermarkAPI = new watermark(); $imageResource = $watermarkAPI->create_watermark($imageResource, $watermarkResource, $opacity, $watermarkX, $watermarkY); } elseif ($watermarkImageType == "png" && $numberOfColors == 0 && $opacity == 100) { $watermark_width = imagesx($watermarkResource); $watermark_height = imagesy($watermarkResource); imagecopy($imageResource, $watermarkResource, $watermarkX, $watermarkY, 0, 0, $watermark_width, $watermark_height); } else { $watermark_width = imagesx($watermarkResource); $watermark_height = imagesy($watermarkResource); imagecopymerge($imageResource, $watermarkResource, $watermarkX, $watermarkY, 0, 0, $watermark_width, $watermark_height, $opacity); } break; case 'crop': $img->crop(intval($values[0]), intval($values[1]), intval($values[2]), intval($values[3])); break; case 'scale': $img->resize(intval($values[0]), intval($values[1])); break; case 'rotate': $img->rotate(floatval($values[0])); break; case 'flip': if ($values[0] == 'hoz') { $img->flip(true); } else { if ($values[0] == 'ver') { $img->flip(false); } } break; case 'save': if (!is_null($saveFile)) { $quality = intval($values[1]); if ($quality < 0) { $quality = 85; } $newSaveFile = $this->makeRelative($relative, $saveFile); $oldSaveFile = $newSaveFile; if ($this->manager->config['allow_newFileName'] && !$this->manager->config['allow_overwrite']) { // check whether a file already exist and if there is, create a variant of the filename $newName = $this->getUniqueFilename($newSaveFile); //get unique filename just returns the filename, so //we need to make the relative path again. $newSaveFile = $this->makeRelative($relative, $newName); } // forced new name? if ($oldSaveFile != $newSaveFile) { $this->forcedNewName = $newName; } else { $this->forcedNewName = false; } $newSaveFullpath = $this->manager->getFullPath($newSaveFile); $img->save($newSaveFullpath, $values[0], $quality); if (is_file($newSaveFullpath)) { $this->filesaved = 1; } else { $this->filesaved = -1; } } break; } //create the tmp image file $filename = $this->createUnique($fullpath); $newRelative = $this->makeRelative($relative, $filename); $newFullpath = $this->manager->getFullPath($newRelative); $newURL = $this->manager->getFileURL($newRelative); // when uploaded and not resized, rename and don't save if ($action == "replace" && $percentage <= 0) { rename($fullpath, $newFullpath); } elseif ($action == "watermark") { // save image $functionName = 'image' . $img->type; if (function_exists($functionName)) { if ($type == 'jpeg') { $functionName($imageResource, $newFullpath, 100); } else { $functionName($imageResource, $newFullpath); } } else { echo "<script>alert(\"Error when saving '" . basename($newFullpath) . "' - Saving '" . $img->type . "' files not supported\");</script>"; return false; } } else { //save the file. $img->save($newFullpath); $img->free(); } // when uploaded was resized and saved, remove original if ($action == "replace" && $percentage > 0) { unlink($fullpath); } //get the image information $imgInfo = @getimagesize($newFullpath); $image['src'] = $newURL; $image['dimensions'] = $imgInfo[3]; $image['width'] = $imgInfo[0]; $image['height'] = $imgInfo[1]; $image['file'] = $newRelative; $image['fullpath'] = $newFullpath; return $image; }
function SF_ASSETS_DbFileAddonImage() { global $cfg_client, $cfg_cms, $cms_image, $fm; require_once 'Image/Transform.php'; $this->thumbext = $cfg_client['thumbext']; $this->size = $cfg_client['thumb_size']; $this->aspect_ratio = (int) $cfg_client['thumb_aspectratio']; $this->chmod_enabled = $cfg_cms['chmod_enabled'] == '1'; $this->chmod_value = intval($cfg_cms['chmod_value'], 8); $this->img_lib_type = 'gd'; $this->img_lib = Image_Transform::factory($this->img_lib_type); if (!$this->thumbext) { $this->thumbext = "_cms_thumb"; } }
function loadItemImages($bigImgUrl, $smallImgUrl, $destName) { if (file_exists(getNormImagePath($destName))) { print "Image already exists - {$destName}\n"; return; } // Загрузка большого изображения $fName = loadImage($bigImgUrl, getNormImagePath($destName, false)); if (PEAR::isError($fName)) { print "Can't load image: " . $fName->getMessage() . "\n"; $fName = loadImage($smallImgUrl, getSmallImagePath($destName, false)); if (PEAR::isError($fName)) { print "Can't load thumb image: " . $fName->getMessage() . "\n"; return; } // Конвертирование в используемый нами формат $newName = replaceExt($fName, IMAGE_EXT); $img = Image_Transform::factory("GD"); if (PEAR::isError($img)) { print $img->getMessage(); return; } // Создание уменьшенного изображения $img->load($newName); // Если изображение больше стандартных размеров - обработать if ($img->getImageWidth() > MAX_WIDTH_THUMBIMAGE || $img->getImageHeight() > MAX_HEIGHT_THUMBIMAGE) { $img->scaleByX(MAX_WIDTH_THUMBIMAGE); $img->scaleByY(MAX_HEIGHT_THUMBIMAGE); } $img->save(getSmallImagePath($destName), IMAGE_EXT, 100); $img->free(); // Удаление временного загруженного файла if (strcmp($fName, $newName) != 0) { unlink($fName); } return; } // Конвертирование в используемый нами формат $newName = replaceExt($fName, IMAGE_EXT); $img = Image_Transform::factory("GD"); if (PEAR::isError($img)) { print $img->getMessage(); return; } $img->load($fName); // Если изображение больше стандартных размеров - обработать if ($img->getImageWidth() > MAX_WIDTH_NORMIMAGE || $img->getImageHeight() > MAX_HEIGHT_NORMIMAGE) { $img->scaleByX(MAX_WIDTH_NORMIMAGE); $img->scaleByY(MAX_HEIGHT_NORMIMAGE); } $img->save($newName, IMAGE_EXT, 100); $img->free(); // Удаление временного загруженного файла if (strcmp($fName, $newName) != 0) { unlink($fName); } // Создание уменьшенного изображения $img->load($newName); if ($img->getImageWidth() > MAX_WIDTH_THUMBIMAGE || $img->getImageHeight() > MAX_HEIGHT_THUMBIMAGE) { $img->scaleByX(MAX_WIDTH_THUMBIMAGE); $img->scaleByY(MAX_HEIGHT_THUMBIMAGE); } $img->save(getSmallImagePath($destName), IMAGE_EXT, 100); $img->free(); }
/** * Обработчик действия: Импорт каталога. */ function Import() { @set_time_limit(0); require_once "Structures/DataGrid.php"; require_once "Structures/DataGrid/DataSource/Excel.php"; require_once "Structures/DataGrid/DataSource/CSV.php"; require_once 'Image/Transform.php'; mk_dir("files/" . DOMAIN . "/tmp"); clearDir("files/" . DOMAIN . "/tmp"); if (isset($_FILES['file']['tmp_name']) && file_exists($_FILES['file']['tmp_name'])) { $path_parts = pathinfo($_FILES['file']['name']); $ext = preg_replace("/[^a-z0-9]+/i", "", mb_strtolower($path_parts['extension'])); if ($ext == 'xls' || $ext == 'csv' || $ext == 'gz') { if ($ext == 'gz') { if (extractArchive($_FILES['file']['tmp_name'], "files/" . DOMAIN . "/tmp")) { $sourcefile1 = preg_replace("/tar\\.gz\$/i", "xls", $_FILES['file']['name']); $sourcefile2 = preg_replace("/tar\\.gz\$/i", "csv", $_FILES['file']['name']); if (is_file("files/" . DOMAIN . "/tmp/{$sourcefile1}")) { $sourcefile = "files/" . DOMAIN . "/tmp/{$sourcefile1}"; $ext = "xls"; } elseif (is_file("files/" . DOMAIN . "/tmp/{$sourcefile2}")) { $sourcefile = "files/" . DOMAIN . "/tmp/{$sourcefile2}"; $content = @file_get_contents($sourcefile); if ($content && !mb_check_encoding($content, 'UTF-8')) { file_put_contents($sourcefile, mb_convert_encoding($content, 'UTF-8', 'Windows-1251')); } $ext = "csv"; } else { return false; } } else { return false; } } elseif ($ext == 'csv') { $sourcefile = $_FILES['file']['tmp_name']; $content = @file_get_contents($sourcefile); if ($content && !mb_check_encoding($content, 'UTF-8')) { file_put_contents($sourcefile, mb_convert_encoding($content, 'UTF-8', 'Windows-1251')); } } else { $sourcefile = $_FILES['file']['tmp_name']; } if (!empty($_REQUEST['clear'])) { switch ($_REQUEST['clear']) { case 1: A::$DB->execute("TRUNCATE " . SECTION . "_categories"); case 2: A::$DB->execute("TRUNCATE " . SECTION . "_catalog"); A::$DB->execute("DELETE FROM " . DOMAIN . "_images WHERE idsec=" . SECTION_ID . " AND iditem>0"); A::$DB->execute("DELETE FROM " . DOMAIN . "_files WHERE idsec=" . SECTION_ID . " AND iditem>0"); A::$DB->execute("DELETE FROM " . DOMAIN . "_comments WHERE idsec=" . SECTION_ID); A_SearchEngine::getInstance()->deleteSection(SECTION_ID); break; } } A::$OPTIONS['imgpath'] = !empty(A::$OPTIONS['imgpath']) ? preg_replace("/[^a-zA-Z0-9-_\\/]/i", "", A::$OPTIONS['imgpath']) : "ifiles"; A::$OPTIONS['filepath'] = !empty(A::$OPTIONS['filepath']) ? preg_replace("/[^a-zA-Z0-9-_\\/]/i", "", A::$OPTIONS['filepath']) : "ifiles"; $categories = array(); $fields = array(); $cfiles = array(); A::$DB->query("SELECT * FROM " . SECTION . "_cols ORDER BY sort"); $i = 0; while ($row = A::$DB->fetchRow()) { if ($row['type'] == 'select' || $row['type'] == 'mselect') { if ($row['idvar'] = A::$DB->getOne("SELECT property FROM " . DOMAIN . "_fields WHERE item='" . SECTION . "' AND field='{$row['field']}'")) { if (isset($vars[$row['idvar']])) { $row['vars'] =& $vars[$row['idvar']]; } else { $row['vars'] = array(); $_vars = loadList($row['idvar']); foreach ($_vars as $key => $name) { $row['vars'][$key] = is_array($name) ? $name['name'] : $name; } $vars[$row['idvar']] =& $row['vars']; } } } $row['id'] = $i++; if (preg_match("/^category[0-9]{1}\$/i", $row['field'])) { $categories[$row['field']] = $row; } elseif ($row['type'] == 'image' || $row['type'] == 'file') { $cfiles[$row['field']] = $row; } else { $fields[$row['field']] = $row; } } A::$DB->free(); if ($ext == 'xls') { $datasource = new Structures_DataGrid_DataSource_Excel(); $datasource->bind($sourcefile); } elseif ($ext == 'csv') { $datasource = new Structures_DataGrid_DataSource_CSV(); $datasource->bind($sourcefile, array('delimiter' => ';', 'enclosure' => '"')); } else { return false; } $datagrid = new Structures_DataGrid(); $datagrid->bindDataSource($datasource); A::$DB->caching = false; $prevgoods = A::$DB->getCount(SECTION . "_catalog", "active='Y'"); $curgoods = 0; $arts = array(); $catn = array(); $catr = array(); $cats = array(); $i = 0; $gsort = A::$DB->getOne("SELECT MAX(sort) FROM " . SECTION . "_catalog") + 1; foreach ($datagrid->recordSet as $row) { $i++; if ($i == 1) { continue; } if (empty($row)) { continue; } if ($ext == 'xls') { $trow = array(); foreach ($row as $j => $value) { if (!empty($value)) { $trow[$j - 1] = $value; } } $row = $trow; } $idcat = 0; for ($j = 0; $j < 3; $j++) { if (isset($categories['category' . $j]) && !empty($row[$categories['category' . $j]['id']])) { if ($cname = strip_tags(trim($row[$categories['category' . $j]['id']]))) { $ch = md5($idcat . '|' . $cname); if (isset($catn[$ch])) { $idcat = $catn[$ch]; } elseif ($_idcat = A::$DB->getOne("SELECT id FROM " . SECTION . "_categories WHERE idker={$idcat} AND name=?", $cname)) { $idcat = $catn[$ch] = $_idcat; } else { if (!isset($catr[$idcat])) { $catr[$idcat] = A::$DB->getRowById($idcat, SECTION . "_categories"); } $category = array(); $category['name'] = $cname; $category['urlname'] = getURLName($cname); $category['idker'] = $idcat; $category['level'] = isset($catr[$idcat]['level']) ? $catr[$idcat]['level'] + 1 : 0; $category['sort'] = A::$DB->getOne("SELECT MAX(sort) FROM " . SECTION . "_categories WHERE idker={$idcat}") + 1; $idcat = $catn[$ch] = A::$DB->Insert(SECTION . "_categories", $category); } } } } if ($idcat == 0 && empty($row[$fields['art']['id']])) { continue; } $data = array(); $data['date'] = time(); if ($idcat > 0) { $data['idcat'] = $idcat; if (!isset($cats[$idcat])) { $cats[$idcat] = 1; } else { $cats[$idcat]++; } } $data['idcat1'] = 0; $data['idcat2'] = 0; foreach ($fields as $field => $frow) { if (!isset($_REQUEST['iempty']) || !empty($row[$frow['id']])) { switch ($frow['type']) { default: $data[$field] = !empty($row[$frow['id']]) ? trim($row[$frow['id']]) : ""; break; case 'int': $data[$field] = !empty($row[$frow['id']]) ? (int) $row[$frow['id']] : 0; break; case 'float': $data[$field] = !empty($row[$frow['id']]) ? (double) str_replace(',', '.', $row[$frow['id']]) : 0; break; case 'select': if (!empty($row[$frow['id']])) { if (isset($frow['vars'])) { $row[$frow['id']] = trim($row[$frow['id']]); $key = array_search($row[$frow['id']], $frow['vars']); if (empty($key) && !empty($row[$frow['id']])) { $key = addToList($frow['idvar'], $row[$frow['id']]); $fields[$field]['vars'][$key] = $frow['vars'][$key] = $row[$frow['id']]; } if (!empty($key)) { $data[$field] = $key; } } } break; case 'mselect': if (!empty($row[$frow['id']])) { if (isset($frow['vars'])) { $row[$frow['id']] = explode(',', $row[$frow['id']]); $data[$field] = array(); foreach ($row[$frow['id']] as $value) { $value = trim($value); $key = array_search($value, $frow['vars']); if (empty($key) && !empty($value)) { $key = addToList($frow['idvar'], $value); $fields[$field]['vars'][$key] = $frow['vars'][$key] = $value; } if (!empty($key)) { $data[$field][] = sprintf("%04d", $key); } } $data[$field] = implode(",", $data[$field]); } } break; case 'bool': $data[$field] = !empty($row[$frow['id']]) && $row[$frow['id']] != 'N' ? "Y" : "N"; break; } } } if (isset($data['name'])) { $data['name'] = strip_tags(trim($data['name'])); } if (!empty(A::$OPTIONS['idrule'])) { $_data = $data; prepareValues(SECTION, $_data); $litems = array(); $idrule = A::$OPTIONS['idrule']; $idrule = explode("+", $idrule); foreach ($idrule as $fname) { if (!empty($_data[$fname])) { $litems[] = getURLName($_data[$fname]); } } $data['urlname'] = implode(!empty($GLOBALS['A_URL_SEPARATOR']) ? $GLOBALS['A_URL_SEPARATOR'] : "_", $litems); } elseif (!empty($data['art'])) { $data['urlname'] = getURLName($data['art']); } if (empty($data['urlname'])) { $data['urlname'] = getURLName($data['name']); } if (!empty($data['content']) && empty($data['description'])) { $data['description'] = truncate($data['content'], A::$OPTIONS['anonslen']); } if (!empty($data['art'])) { $grow = A::$DB->getRow("SELECT id,mprices FROM " . SECTION . "_catalog WHERE art=? LIMIT 0,1", $data['art']); if (A::$OPTIONS['usecats']) { if (!empty($arts[$data['art']]) && !empty($data['idcat'])) { if ($arts[$data['art']] < 3) { $data['idcat' . $arts[$data['art']]] = $data['idcat']; unset($data['idcat']); } $arts[$data['art']]++; } else { $arts[$data['art']] = 1; } } } else { $grow = A::$DB->getRow("SELECT id,mprices FROM " . SECTION . "_catalog WHERE idcat=? AND name=? LIMIT 0,1", array($data['idcat'], $data['name'])); } if ($grow) { $id = $grow['id']; $mprices = !empty($grow['mprices']) ? unserialize($grow['mprices']) : array(); } else { $id = 0; } if ($id) { if (isset($fields['mprice']) && !empty($data['mprice'])) { $inm = false; foreach ($mprices as $mp) { if ($mp['name'] == trim($data['mprice'])) { $inm = true; break; } } if (!$inm) { $mprices[] = array('name' => $data['mprice'], 'price' => !empty($data['price']) ? $data['price'] : ''); } $data['mprices'] = serialize($mprices); unset($data['price']); $cats[$idcat]--; $curgoods--; } if (isset($data['mprice'])) { unset($data['mprice']); } A::$DB->Update(SECTION . "_catalog", $data, "id={$id}"); $images = A::$DB->getAssoc("SELECT sort,id,path FROM " . DOMAIN . "_images\r\r\n\t\t\tWHERE idsec=" . SECTION_ID . " AND iditem={$id}"); $images = array_values($images); $files = A::$DB->getAssoc("SELECT sort,id,path FROM " . DOMAIN . "_files\r\r\n\t\t\tWHERE idsec=" . SECTION_ID . " AND iditem={$id}"); $files = array_values($files); $curgoods++; } elseif (!empty($data['idcat'])) { if (isset($fields['mprice']) && !empty($data['mprice'])) { $mprices = array(array('name' => $data['mprice'], 'price' => !empty($data['price']) ? $data['price'] : '')); $data['mprices'] = serialize($mprices); } if (isset($data['mprice'])) { unset($data['mprice']); } if (empty($data['name'])) { continue; } $data['sort'] = $gsort++; $id = A::$DB->Insert(SECTION . "_catalog", $data); $images = array(); $files = array(); $curgoods++; } else { continue; } foreach ($cfiles as $field => $frow) { if (!empty($row[$frow['id']])) { switch ($frow['type']) { case 'image': $row[$frow['id']] = preg_replace("/[^a-zA-Zа-яА-Я0-9-_.]/iu", "", $row[$frow['id']]); $path0 = A::$AUTH->isSuperAdmin() ? "ifiles/" . $row[$frow['id']] : ""; $path1 = "files/" . DOMAIN . "/" . A::$OPTIONS['imgpath'] . "/" . $row[$frow['id']]; $path2 = "files/" . DOMAIN . "/reg_images/" . $row[$frow['id']]; $path = is_file($path0) ? $path0 : (is_file($path1) ? $path1 : (is_file($path2) ? $path2 : "")); if ($path) { preg_match("/^idimg([0-9]+)\$/i", $field, $mathes); $sort = $mathes[1]; if (!isset($images[$sort]) || $images[$sort]['path'] != $path) { $image = array(); $image['path'] = $path; $image['name'] = basename($row[$frow['id']]); $image['mime'] = getMimeByFile($row[$frow['id']]); $image['caption'] = !empty($data['name']) ? $data['name'] : ""; $it = Image_Transform::factory('GD'); $it->load($path); $image['width'] = $it->img_x; $image['height'] = $it->img_y; $image['idsec'] = SECTION_ID; $image['iditem'] = $id; $image['sort'] = $sort; if (isset($images[$sort])) { A::$DB->Update(DOMAIN . "_images", $image, "id=" . $images[$sort]['id']); } else { A::$DB->Insert(DOMAIN . "_images", $image); } } } break; case 'file': $row[$frow['id']] = preg_replace("/[^a-zA-Zа-яА-Я0-9-_.]/iu", "", $row[$frow['id']]); $path0 = A::$AUTH->isSuperAdmin() ? "ifiles/" . $row[$frow['id']] : ""; $path1 = "files/" . DOMAIN . "/" . A::$OPTIONS['filepath'] . "/" . $row[$frow['id']]; $path2 = "files/" . DOMAIN . "/reg_files/" . $row[$frow['id']]; $path = is_file($path0) ? $path0 : (is_file($path1) ? $path1 : (is_file($path2) ? $path2 : "")); if ($path) { preg_match("/^idfile([0-9]+)\$/i", $field, $mathes); $sort = $mathes[1]; if (!isset($files[$sort]) || $files[$sort]['path'] != $path) { $file = array(); $file['path'] = $path; $file['name'] = basename($row[$frow['id']]); $file['mime'] = getMimeByFile($row[$frow['id']]); $file['caption'] = !empty($data['name']) ? $data['name'] : ""; $file['idsec'] = SECTION_ID; $file['iditem'] = $id; $file['sort'] = $sort; $file['size'] = filesize($path); $file['dwnl'] = 0; if (isset($files[$sort])) { A::$DB->Update(DOMAIN . "_files", $file, "id=" . $files[$sort]['id']); } else { A::$DB->Insert(DOMAIN . "_files", $file); } } } break; } } } } if ($prevgoods > 0 && $prevgoods != $curgoods) { $this->updateCItems(); } else { A::$DB->Update(SECTION . "_categories", array('citems' => 0)); foreach ($cats as $id => $count) { A::$DB->Update(SECTION . "_categories", array('citems' => $count), "id={$id}"); } $this->updateCItems(0, true); } A::$CACHE->resetSection(SECTION); delDir("files/" . DOMAIN . "/tmp"); return true; } } return false; }
/** * Process upload files. The file must be an * uploaded file. If 'validate_images' is set to * true, only images will be processed. Any duplicate * file will be renamed. See Files::copyFile for details * on renaming. * @param string $relative the relative path where the file * should be copied to. * @param array $file the uploaded file from $_FILES * @return boolean true if the file was processed successfully, * false otherwise */ function _processFiles($relative, $file) { global $_course; if ($file['error'] != 0) { return false; } if (!is_file($file['tmp_name'])) { return false; } if (!is_uploaded_file($file['tmp_name'])) { Files::delFile($file['tmp_name']); return false; } $file['name'] = replace_dangerous_char($file['name'], 'strict'); $file_name = $file['name']; $extension = explode('.', $file_name); $count = count($extension); if ($count == 1) { $extension = ''; } else { $extension = strtolower($extension[$count - 1]); } // Checking for image by file extension first, using the configuration file. if (!in_array($extension, $this->config['accepted_extensions'])) { Files::delFile($file['tmp_name']); return false; } // Second, filtering using a special function of the system. $result = filter_extension($file_name); if ($result == 0 || $file_name != $file['name']) { Files::delFile($file['tmp_name']); return false; } // Checking for a valid image by reading binary file (partially in most cases). if ($this->config['validate_images']) { $imgInfo = @getImageSize($file['tmp_name']); if (!is_array($imgInfo)) { Files::delFile($file['tmp_name']); return false; } } //now copy the file $path = Files::makePath($this->getBaseDir(), $relative); $result = Files::copyFile($file['tmp_name'], $path, $file['name']); //no copy error if (!is_int($result)) { if (isset($_course) && !empty($_course) && isset($_course['code'])) { //adding the document to the DB global $to_group_id; // looking for the /document/ folder $document_path = substr($path, strpos($path, '/document/') + 9, strlen($path)); // /shared_folder/4/name $document_path .= $result; $chamiloFile = $file['name']; $chamiloFileSize = $file['size']; if (!empty($group_properties['directory'])) { $chamiloFolder = $group_properties['directory'] . $chamiloFolder; } $doc_id = add_document($_course, $document_path, 'file', $chamiloFileSize, $chamiloFile); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', api_get_user_id(), $to_group_id, null, null, null, api_get_session_id()); } $dimensionsIndex = isset($_REQUEST['uploadSize']) ? $_REQUEST['uploadSize'] : 0; // If maximum size is specified, constrain image to it. if ($this->config['maxWidth'][$dimensionsIndex] > 0 && $this->config['maxHeight'][$dimensionsIndex] > 0) { $img = Image_Transform::factory(IMAGE_CLASS); $img->load($path . $result); // image larger than max dimensions? if ($img->img_x > $this->config['maxWidth'][$dimensionsIndex] || $img->img_y > $this->config['maxHeight'][$dimensionsIndex]) { $percentage = min($this->config['maxWidth'][$dimensionsIndex] / $img->img_x, $this->config['maxHeight'][$dimensionsIndex] / $img->img_y); $img->scale($percentage); } $img->save($path . $result); $img->free(); } } // Delete tmp files. Files::delFile($file['tmp_name']); return false; }
/** * Process upload files. The file must be an * uploaded file. If 'validate_images' is set to * true, only images will be processed. Any duplicate * file will be renamed. See Files::copyFile for details * on renaming. * @param string $relative the relative path where the file * should be copied to. * @param array $file the uploaded file from $_FILES * @return boolean true if the file was processed successfully, * false otherwise */ function _processFiles($relative, $file) { if ($file['error'] != 0) { return false; } if (!is_file($file['tmp_name'])) { return false; } if (!is_uploaded_file($file['tmp_name'])) { Files::delFile($file['tmp_name']); return false; } if ($this->config['validate_images'] == true) { $imgInfo = @getImageSize($file['tmp_name']); if (!is_array($imgInfo)) { Files::delFile($file['tmp_name']); return false; } } //now copy the file $path = Files::makePath($this->getBaseDir(), $relative); $result = Files::copyFile($file['tmp_name'], $path, $file['name']); //no copy error if (!is_int($result)) { $dimensionsIndex = isset($_REQUEST['uploadSize']) ? $_REQUEST['uploadSize'] : 0; // If maximum size is specified, constrain image to it. if ($this->config['maxWidth'][$dimensionsIndex] > 0 && $this->config['maxHeight'][$dimensionsIndex] > 0) { $img = Image_Transform::factory(IMAGE_CLASS); $img->load($path . $result); // image larger than max dimensions? if ($img->img_x > $this->config['maxWidth'][$dimensionsIndex] || $img->img_y > $this->config['maxHeight'][$dimensionsIndex]) { $percentage = min($this->config['maxWidth'][$dimensionsIndex] / $img->img_x, $this->config['maxHeight'][$dimensionsIndex] / $img->img_y); $img->scale($percentage); } $img->save($path . $result); $img->free(); } } //delete tmp files. Files::delFile($file['tmp_name']); return false; }
<?php /** * This script provides a simple example of using the Image_Resize library and * is designed to be used as a test of your setup. */ error_reporting(E_ALL); require_once 'Image/Transform.php'; define('IMAGE_TRANSFORM_LIB_PATH', '/usr/local/ImageMagick/bin/'); // Change 'IM' to 'GD' to test using the GD library. $im = Image_Transform::factory('IM'); $im->load('/www/php_lib/Image_Resize/Examples/test.jpg'); // next will resize so that the largest length is 300px - height or width $im->resize(300, 50); // next is a subclass call that calls the above with a set size. $im->addText(array('text' => 'Annotated')); //$im->display(); $im->save('/www/htdocs/test.jpg'); // Now free the memory - should be called free? $im->free(); ?> <img src="test.jpg">
static function keepSettingsOnSave($bool) { self::$keep_settings_on_save = $bool; }
/** * Create a new Thumbnail instance. * @param int $width thumbnail width * @param int $height thumbnail height */ function Thumbnail($width=96, $height=96) { $this->driver = Image_Transform::factory(IMAGE_CLASS); $this->width = $width; $this->height = $height; }
function generate_scaled_image($src, $dest, $width = 300, $height = 500) { $a = Image_Transform::factory('GD'); $a->load($src); $a->fit($width, $height); $a->save($dest); }
function imgStart($a){ //print_r($a); // scale the image ! $this->flushBlurb(); if ($a['STYLE']) { //print_r($a); preg_match('/width: ([0-9]+)px; height: ([0-9]+)px/i', $a['STYLE'],$ar); print_r($ar); $it = Image_Transform::factory('GD'); list($filename,$ext) = explode('.',$a['SRC']); $it->load( getenv('PWD'). '/'.$a['SRC'] ); print_r($it); $it->scaleMaxX( $ar[1]); $newfilename = $filename . '_'.$ar[1] .'.'. $ext; $it->save(getenv('PWD').'/'.$this->outputDir .'/'.$newfilename); } else { copy( getenv('PWD'). '/'.$a['SRC'], getenv('PWD').'/'.$this->outputDir .'/'.$a['SRC']); $newfilename = $a['SRC']; } $this->add(' <image align="center" scale="30%" filename="'. $newfilename.'" />',TRUE); }
/** * Process the actions, crop, scale(resize), rotate, flip, and save. * When ever an action is performed, the result is save into a * temporary image file, see createUnique on the filename specs. * It does not return the saved file, alway returning the tmp file. * @param string $action, should be 'crop', 'scale', 'rotate','flip', or 'save' * @param string $relative the relative image filename * @param string $fullpath the fullpath to the image file * @return array with image information * <code>array('src'=>'url of the image', 'dimensions'=>'width="xx" height="yy"', * 'file'=>'image file, relative', 'fullpath'=>'full path to the image');</code> */ function processAction($action, $relative, $fullpath) { $params = ''; if (isset($_GET['params'])) { $params = $_GET['params']; } $values = explode(',', $params, 4); $saveFile = $this->getSaveFileName($values[0]); $img = Image_Transform::factory(IMAGE_CLASS); $img->load($fullpath); switch ($action) { case 'crop': $img->crop(intval($values[0]), intval($values[1]), intval($values[2]), intval($values[3])); break; case 'scale': $img->resize(intval($values[0]), intval($values[1])); break; case 'rotate': $img->rotate(floatval($values[0])); break; case 'flip': if ($values[0] == 'hoz') { $img->flip(true); } else { if ($values[0] == 'ver') { $img->flip(false); } } break; case 'save': if (!is_null($saveFile)) { $quality = intval($values[1]); if ($quality < 0) { $quality = 85; } $newSaveFile = $this->makeRelative($relative, $saveFile); $newSaveFile = $this->getUniqueFilename($newSaveFile); //get unique filename just returns the filename, so //we need to make the relative path once more. $newSaveFile = $this->makeRelative($relative, $newSaveFile); $image['saveFile'] = $newSaveFile; $newSaveFullpath = $this->manager->getFullPath($newSaveFile); $img->save($newSaveFullpath, $values[0], $quality); if (is_file($newSaveFullpath)) { $this->filesaved = 1; } else { $this->filesaved = -1; } } break; } //create the tmp image file $filename = $this->createUnique($fullpath); $newRelative = $this->makeRelative($relative, $filename); $newFullpath = $this->manager->getFullPath($newRelative); $newURL = $this->manager->getFileURL($newRelative); //save the file. $img->save($newFullpath); $img->free(); //get the image information $imgInfo = @getimagesize($newFullpath); $image['src'] = $newURL; $image['width'] = $imgInfo[0]; $image['height'] = $imgInfo[1]; $image['dimensions'] = $imgInfo[3]; $image['file'] = $newRelative; $image['fullpath'] = $newFullpath; return $image; }
function EditBanner() { $dataset = new A_DataSet(STRUCTURE); $dataset->fields = array("name", "idcat", "url", "showurl", "date", "target", "text", "width", "height", "show", "active"); $_REQUEST['name'] = strclear($_REQUEST['name']); $_REQUEST['idcat'] = $_REQUEST['idcat2']; $_REQUEST['active'] = isset($_REQUEST['active']) ? 'Y' : 'N'; $_REQUEST['url'] = urldecode($_REQUEST['url']); if (isset($_REQUEST['showall'])) { $_REQUEST['showurl'] = ""; } elseif ($_REQUEST['showurl']) { $showurls = explode("\n", $_REQUEST['showurl']); foreach ($showurls as $i => $url) { if ($url = urldecode($url)) { $showurls[$i] = $url; } else { unset($showurls[$i]); } } $_REQUEST['showurl'] = implode("\n", $showurls); } if (isset($_REQUEST['date'])) { $_REQUEST['date'] = "Y"; array_push($dataset->fields, "date1", "date2"); } else { $_REQUEST['date'] = "N"; } if (!isset($_REQUEST['showall'])) { $_REQUEST['show'] = !empty($_REQUEST['show']) ? serialize($_REQUEST['show']) : ""; } else { $_REQUEST['show'] = ""; } $banner_ext = array("gif", "jpg", "jpeg", "png", "swf"); if (isset($_FILES['bannerfile']['tmp_name']) && file_exists($_FILES['bannerfile']['tmp_name'])) { $ext = $basename = ""; escapeFileName($_FILES['bannerfile']['name'], $ext, $basename); $basename = translit($basename); if (in_array($ext, $banner_ext)) { delfile($dataset->data['filepath']); mk_dir($path = "files/" . DOMAIN . "/rek_images"); $_REQUEST["filepath"] = $path . "/{$basename}.{$ext}"; $i = 1; while (is_file($_REQUEST["filepath"])) { $_REQUEST["filepath"] = $path . "/{$basename}_" . sprintf("%02d", $i++) . ".{$ext}"; } copyfile($_FILES['bannerfile']['tmp_name'], $_REQUEST["filepath"]); $_REQUEST["type"] = $ext == "swf" ? "flash" : "image"; array_push($dataset->fields, "filepath", "type"); if ($_REQUEST["type"] == "image") { require_once 'Image/Transform.php'; $it = Image_Transform::factory('GD'); $it->load($_FILES['bannerfile']['tmp_name']); $_REQUEST["width"] = $it->img_x; $_REQUEST["height"] = $it->img_y; } } } return $dataset->Update(); }