static public function imageResize($fname,$width,$height) { $i = new Image( $fname ); $owhr=$i->getWidth()/$i->getHeight(); $twhr=$width/$height; if( $owhr==$twhr ) { $i->resize( $width,$height ); } elseif( $owhr>$twhr ) { $i->resizeToHeight( $height ); $i->crop( ($i->getWidth()-$width)/2, 0, $width, $height); } else { $i->resizeToWidth( $width ); $i->crop( 0, ($i->getHeight()-$height)/2, $width, $height); } $i->save(); }
public function run() { $rootPath = Yii::app()->getBasePath() . '/..'; $fullpath = $rootPath . '/uploads/tmp/' . Yii::app()->request->getPost('im'); if (file_exists($fullpath)) { $image = new Image($fullpath); $image->crop(Yii::app()->request->getPost('w'), Yii::app()->request->getPost('h'), Yii::app()->request->getPost('y'), Yii::app()->request->getPost('x')); $image->save(); echo Yii::app()->request->getPost('imbox'); } }
public function process($args) { // get top/left crop offsets from query string (center is default) $top = Input::instance()->get('ctop', 'center'); $left = Input::instance()->get('cleft', 'center'); // ensure the values are valid $top = (is_numeric($top) or $top == 'top' or $top == 'center' or $top == 'bottom') ? $top : 'center'; $left = (is_numeric($left) or $left == 'left' or $left == 'center' or $left == 'right') ? $left : 'center'; // $rotate = Input::instance()->get('rotate'); $flip = Input::instance()->get('flip'); $flips = array('h' => 5, 'v' => 6); if (isset($this->row->preview_id) and $this->row->preview_id > 0) { $this->row = $this->row->preview; } if ($this->row->is_image) { $image = new Image(DATAPATH . 'uploads/' . $this->row->file_name); // if (!is_null($rotate) AND is_numeric($rotate)) { $image->rotate( (int) $rotate ); } if (!is_null($flip) and isset($flips[$flip])) { $image->flip($flips[$flip]); } $a = $image->width; $b = $image->height; if ($a != $args[0] or $b != $args[1]) { $s = $args[0] - $a; $t = $args[1] - $b; $r = max(($a + $s) / $a, ($b + $t) / $b); $x = $a * $r; $y = $b * $r; if (!is_numeric($args[0])) { die('invalid width: ' . $args[0]); } if (!is_numeric($args[1])) { die('invalid height: ' . $args[1]); } // $image->quality(75); $image->resize($x, $y, Image::NONE); $image->crop($args[0], $args[1], $top, $left); } $uniqid = '/tmp/temp_image-' . uniqid() . $this->row->file_ext; // Save to a temporary file $image->save($uniqid); $this->image->clear(); $this->image->readImage($uniqid); unlink($uniqid); $border = Input::instance()->get('border', FALSE); if ($border) { $color = Input::instance()->get('bordercolor', null); $this->addborder($border, $color); } } }
public function doCrop($input) { if (!$this->api->authorized()) { return array('error' => 'not_logged_in'); } $title = $input->title; $response = $this->api->getImageInfo($title); if ($response === false) { die('File was not found'); } $sha1 = $response->imageinfo[0]->sha1; $ext = $this->getFileExt($response->imageinfo[0]->mime); $srcPath = $this->publicPath . '/files/' . $sha1 . $ext; $destPath = $this->publicPath . '/files/' . $sha1 . '_cropped' . $ext; $new_width = intval($input->w); $new_height = intval($input->h); $new_x = intval($input->x); $new_y = intval($input->y); $cropMethod = $input->cropmethod; if ($response->imageinfo[0]->mime == 'image/gif') { $cropMethod = 'gif'; } $image = new Image($srcPath, $response->imageinfo[0]->mime); $s1 = array($image->width, $image->height); try { $res = $image->crop($cropMethod, $destPath, $new_x, $new_y, $new_width, $new_height); } catch (CropFailed $error) { return array('error' => 'Crop failed: ' . $error->getMessage()); } $s2 = array($res['width'], $res['height']); // Make thumb $image = new Image($destPath, $response->imageinfo[0]->mime); $res['thumb'] = $image->thumb($this->publicPath . '/files/' . $sha1 . '_cropped_thumb' . $ext); $dim = array(); if ($s1[0] != $s2[0]) { $cropPercentX = round(($s1[0] - $s2[0]) / $s1[0] * 100); $dim[] = ($cropPercentX ?: ' < 1') . ' % horizontally'; } if ($s1[1] != $s2[1]) { $cropPercentY = round(($s1[1] - $s2[1]) / $s1[1] * 100); $dim[] = ($cropPercentY ?: ' < 1') . ' % vertically'; } $using = 'using [[Commons:CropTool|CropTool]] with ' . $res['method'] . ' mode.'; $res['dim'] = implode(' and ', $dim) . ' ' . $using; $res['page'] = $this->analyzePage($title); $this->logger->addInfo('[main] ' . substr($sha1, 0, 7) . ' Did crop using method: ' . $cm); return $res; }
public function cropResize($x1, $x2, $y1, $y2, $w, $h) { if (!$this->id) { return null; } $path = $this->getResizePath($w, $h); if (file_exists($this->getPath())) { $image = new Image($this->getPath()); $image->crop($x2 - $x1, $y2 - $y1, $y1, $x1); $image->resize($w, $h); if (!file_exists(dirname($path))) { mkdir(dirname($path), 0777, true); } $image->save($path); } return $this->getResizeUrl($w, $h); }
function saveChanges() { $_POST->setType('filename', 'string'); $_POST->setType('cropimgx', 'numeric'); $_POST->setType('cropimgy', 'numeric'); $_POST->setType('cropimgw', 'numeric'); $_POST->setType('cropimgh', 'numeric'); $_REQUEST->setType('mkcopy', 'string'); if ($_REQUEST['filename']) { if ($_REQUEST['mkcopy']) { if ($_POST['filename'] != $this->basename && $_POST['filename']) { if (!file_exists($this->dirname . '/' . $_POST['filename'])) { $p = $this->dirname . '/' . $_POST['filename']; } else { Flash::queue(__('File exists. Please give another name or delete the conflicting file. Your changes were not saved.'), 'warning'); break; } } else { $nrofcopies = count(glob(substr($this->path, 0, -(strlen($this->extension) + 1)) . '_copy*')); if ($nrofcopies == 0) { $nrofcopies = ''; } $p = substr($this->path, 0, -(strlen($this->extension) + 1)) . '_copy' . ($nrofcopies + 1) . substr($this->path, -(strlen($this->extension) + 1)); } touch($p); $copy = File::open($p); } else { if ($_POST['filename'] != $this->basename) { $this->rename($_POST['filename']); } $p = $this->path; $img = new Image($this->path); if ($_POST['cropimgw'] && $_POST['cropimgh']) { $width = $img->width(); $s = $width / min($width, 400); $img->crop(round($s * $_POST['cropimgx']), round($s * $_POST['cropimgy']), round($s * $_POST['cropimgw']), round($s * $_POST['cropimgh'])); } if ($_REQUEST['imgrot']) { $img->rotate($_REQUEST['imgrot']); } $img->save($p); Flash::queue(__('Your changes were saved')); } } }
public function add() { $user = User_Model::current(); if ($post = $this->input->post('project')) { if (!$user->loaded) { return $this->template->content = 'You need to be logged in'; } $project = ORM::factory('project'); $validation = Projects_utils::projects_add_validation($post); if (!$project->validate($validation, true)) { return $this->template->content = Kohana::debug($validation->errors()); } $post_user_data = $this->input->post('user'); if (empty($post_user_data['role'])) { return $this->template->content = 'What was your role?!'; } $project->add_user_roles(array($user->id => $post_user_data['role'])); if (!empty($_FILES)) { $image_file = $_FILES['screenshot']; if (!$image_file['error']) { $image = new Image($image_file['tmp_name']); if ($image->width > 547) { $image->resize(547, null); } $image->save(DOCROOT . '/media/project-images/' . $project->id . '.jpg'); } $image_file = $_FILES['logo']; if (!$image_file['error']) { $image = new Image($image_file['tmp_name']); if ($image->width > 60) { $image->resize(90, 90, Image::AUTO); } $image->crop(60, 60, 'center')->save(DOCROOT . '/media/project-images/' . $project->id . '-tiny.jpg'); } } return url::redirect($project->local_url); } else { HTMLPage::add_style('forms'); $this->template->content = new View('projects/add'); $this->template->content->project_types = Projects_utils::get_project_types_dropdown_array(); $this->template->content->user = $user; } }
public function run() { if (!Yii::app()->user->isGuest) { $im = Yii::app()->request->getPost('im'); $inbase = ProductsImages::model()->findByAttributes(array('name' => $im), 'uploaded_by=' . Yii::app()->user->id); if (!$inbase) { throw new CHttpException(404, 'Ошибка.'); return true; } $rootPath = Yii::app()->getBasePath() . '/..'; $fullpath = $rootPath . '/uploads/obj/' . $im; if (file_exists($fullpath)) { $image = new Image($fullpath); $image->crop(Yii::app()->request->getPost('w'), Yii::app()->request->getPost('h'), Yii::app()->request->getPost('y'), Yii::app()->request->getPost('x')); $image->save(); MCleaner::cleanTempImg($im); $inbase->getUrl('100x75'); echo Yii::app()->request->getPost('imbox'); } } }
public function run() { if (!Yii::app()->user->isGuest) { $im = Yii::app()->request->getPost('im'); $imbox = Yii::app()->request->getPost('imbox'); $inbase = Shops::model()->findByAttributes(array($imbox => $im), 'real_admin=' . Yii::app()->user->id); $shop = new Shops(); if (!$inbase) { throw new CHttpException(404, 'Ошибка.'); return true; } $rootPath = Yii::app()->getBasePath() . '/..'; $fullpath = $rootPath . '/uploads/shops/' . $inbase->id . '/photos/' . $im; if (file_exists($fullpath)) { $image = new Image($fullpath); $image->crop(Yii::app()->request->getPost('w'), Yii::app()->request->getPost('h'), Yii::app()->request->getPost('y'), Yii::app()->request->getPost('x')); $image->save(); MCleaner::cleanTempImg($im, 'shop'); $inbase->getUrl('220x114', 'resize', false, $im); echo Yii::app()->request->getPost('imbox'); } } }
} } if (empty($originalImage)) { $originalImage = $_POST['path']; } include_once CLASS_IMAGE; $image = new Image(); if ($image->loadImage($originalImage)) { switch ($_POST['mode']) { case "resize": if (!$image->resize($_POST['width'], $_POST['height'], !empty($_POST['constraint']) ? true : false)) { $error = IMG_SAVE_RESIZE_FAILED; } break; case "crop": if (!$image->crop($_POST['x'], $_POST['y'], $_POST['width'], $_POST['height'])) { $error = IMG_SAVE_CROP_FAILED; } break; case "flip": if (!$image->flip($_POST['flip_angle'])) { $error = IMG_SAVE_FLIP_FAILED; } break; case "rotate": if (!$image->rotate(intval($_POST['angle']))) { $error = IMG_SAVE_ROTATE_FAILED; } break; default: $error = IMG_SAVE_UNKNOWN_MODE;
function resizeImages($file, $directoryExtend, $watermark = '', $watermarkOver = 0, $watermarkPosition = '') { if (trim($file) == '') { return false; } if (is_array($this->photoSizes)) { require_once ENGINE_PATH . 'classes/image.class.php'; $image = new Image(); if ($watermark != '') { require_once ENGINE_PATH . 'classes/watermark.class.php'; $wm = new watermark(DATA_SERVER_PATH . 'images/' . $watermark, $watermarkPosition); } recursive_mkdir(DATA_SERVER_PATH . "/uploads/" . $this->uploadFileDirectory . $directoryExtend); foreach ($this->photoSizes as $key => $size) { $image->enlarge = true; $resize = false; if (substr($size, 0, 1) == '_') { $resize = true; $size = substr($size, 1); } $sizes = explode('x', $size); if ($sizes[0] > 0) { if ($sizes[1] == 0) { $image->resize(DATA_SERVER_PATH . "/uploads/" . $this->uploadFileDirectory . $directoryExtend . $file, $sizes[0], 1000, DATA_SERVER_PATH . "/uploads/" . $this->uploadFileDirectory . $directoryExtend . $key . '_' . $file); } else { if ($resize) { $image->enlarge = false; $image->resize(DATA_SERVER_PATH . "/uploads/" . $this->uploadFileDirectory . $directoryExtend . $file, $sizes[0], $sizes[1], DATA_SERVER_PATH . "/uploads/" . $this->uploadFileDirectory . $directoryExtend . $key . '_' . $file); } else { $image->crop(DATA_SERVER_PATH . "/uploads/" . $this->uploadFileDirectory . $directoryExtend . $file, $sizes[0], $sizes[1], DATA_SERVER_PATH . "/uploads/" . $this->uploadFileDirectory . $directoryExtend . $key . '_' . $file); } } if ($watermark != '' && $watermarkOver <= $sizes[1]) { $wm->addWatermark(DATA_SERVER_PATH . "/uploads/" . $this->uploadFileDirectory . $directoryExtend . $key . '_' . $file); } } } } return true; }
define('CARD_DIR', dirname(__FILE__) . '/card'); define('SOURCE_DIR', dirname(__FILE__) . '/source'); define('SPOIL_CARD', '_'); define('WIDTH', 140); define('HEIGHT', 105); $cutRange = [[248, 270], [248, 540], [248, 810], [248, 1080], [1323, 270], [1323, 540], [1323, 810], [1323, 1080]]; $images = ['img51.jpg', 'img54.jpg', 'img57.jpg', 'img60.jpg', 'img63.jpg']; $cardnum = [0, 0, 2, 3, 4, 0, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 14, 16, 19, 17, 18, 20, 22, 23, 24, 25, 26, 28, 29, 27, 31, 33, 35, 36, 21, 32, 30, 34, 0, 0]; $count = 0; foreach ($images as $imgname) { foreach ($cutRange as $r) { list($x, $y) = $r; $thumb = new Image(SOURCE_DIR . '/' . $imgname); $thumb->width(WIDTH); $thumb->height(HEIGHT); $thumb->crop($x, $y); $thumb->dir(CARD_DIR); $name = $cardnum[$count++]; $thumb->name($name == 0 ? SPOIL_CARD : $name); $thumb->save(); } } // 消費財 $thumb = new Image(SOURCE_DIR . '/' . 'img63.jpg'); $thumb->width(WIDTH); $thumb->height(HEIGHT); $thumb->crop(1323, 1110); $thumb->dir(CARD_DIR); $thumb->name('99'); $thumb->save(); unlink(CARD_DIR . '/' . SPOIL_CARD . '.jpg');
private function manipulate($file, $options) { // validate options $this->validateOptions($options); $targetFolder = $options['folder']; $fileName = $options['fileName']; // path for new image $path = $this->getAbsolutePath($targetFolder, $fileName); if ($this->mkdir && !file_exists(dirname($path))) { mkdir(dirname($path), 0777, true); } // image copy if should not be resized if (isset($options['resize']) && !$options['resize']) { copy($file->getTempName(), $path); return; } // width and hight for new image $targetWidth = $options['width']; $targetHeight = $options['height']; // width and hight of uploaded image list($uploadedWidth, $uploadedHeight) = getimagesize($file->getTempName()); // image copy if should not be resized if (isset($options['smartResize']) && !$options['smartResize']) { // if needed image more than uploaded image then nothing change if ($targetWidth > $uploadedWidth && $targetHeight > $uploadedHeight) { copy($file->getTempName(), $path); } else { // get image for manipulate from temp folder $image = new Image($file->getTempName()); // manipulate $image->resize($targetWidth, $targetHeight, Image::AUTO)->sharpen(1)->quality(95)->save($path); } return; } // relation of side uploaded and new image $uploadedRatio = $uploadedWidth / $uploadedHeight; $targetRatio = $targetWidth / $targetHeight; // compare the relation and calculate coordinates for clipping if ($uploadedRatio > $targetRatio) { $cropHeight = $uploadedHeight; $cropWidth = $uploadedHeight * $targetRatio; $cropLeft = ($uploadedWidth - $uploadedHeight * $targetRatio) * 0.5; $cropTop = 0; } else { $cropHeight = $uploadedWidth / $targetRatio; $cropWidth = $uploadedWidth; $cropLeft = 0; $cropTop = ($uploadedHeight - $uploadedWidth / $targetRatio) * 0.2; } // get image for manipulate from temp folder $image = new Image($file->getTempName()); // manipulate $image->crop($cropWidth, $cropHeight, $cropTop, $cropLeft)->resize($targetWidth, $targetHeight, Image::NONE)->sharpen(1)->quality(95)->save($path); }
protected function insertImage($id, $values) { $request = Request::getInstance(); // get settings $calSettings = $this->plugin->getObject(Calendar::TYPE_SETTINGS); $globalSettings = $this->plugin->getSettings(); $settings = array_merge($globalSettings, $calSettings->getSettings($values['tree_id'], $values['tag'])); $destWidth = $settings['image_width']; $destHeight = $settings['image_height']; $maxWidth = $settings['image_max_width']; // user global if tree values are not set if (!$destWidth) { $destWidth = $globalSettings['image_width']; } if (!$destHeight) { $destHeight = $globalSettings['image_height']; } if (!$maxWidth) { $maxWidth = $globalSettings['image_max_width']; } $imgX = $values['img_x']; $imgY = $values['img_y']; $path = $this->plugin->getContentPath(true); $filename = strtolower($this->getClassName()) . "_" . $id['id']; // check if image is uploaded $img = $values['image']; $upload = is_array($img) && $img['tmp_name']; if ($upload) { // image is new uploaded image $image = new Image($img); $imgWidth = $image->getWidth(); $imgHeight = $image->getHeight(); $ext = Utils::getExtension($img['name']); $originalFile = "{$filename}.{$ext}"; $croppedFile = $filename . "_thumb.{$ext}"; // delete current image if filename new filename is different $detail = $this->getDetail($id); if ($detail['image'] && $detail['image'] != $originalFile) { $this->deleteImage($detail); } // resize original image. (increase size if necessary) if ($maxWidth > 0 && $imgWidth > $maxWidth) { $image->resize($maxWidth); } elseif ($imgWidth < $destWidth || $imgHeight < $destHeight) { if ($image->getWidth() < $destWidth) { $image->resize($destWidth, 0, true); } if ($image->getHeight() < $destHeight) { $image->resize(0, $destHeight, true); } } $image->save($path . $originalFile); } else { // no image provided. check if one exists $detail = $this->getDetail($id); if (!$detail['image']) { return; } // get original image $image = new Image($detail['image'], $this->plugin->getContentPath(true)); $ext = Utils::getExtension($detail['image']); $originalFile = "{$filename}.{$ext}"; $croppedFile = $filename . "_thumb.{$ext}"; } // only crop if both width and height settings are set and image is big enough, else do a resize if ($destWidth && $destHeight) { // crop image if ($upload) { // calculate area of crop field // first assume width is smalles side $newWidth = $image->getWidth(); $newHeight = $newWidth / $destWidth * $destHeight; if ($newHeight > $image->getHeight()) { // width was larger than height, so use height as smallest side $newHeight = $image->getHeight(); $newWidth = $newHeight / $destHeight * $destWidth; } // center crop area $imgX = intval($image->getWidth() / 2 - $newWidth / 2); $imgY = intval($image->getHeight() / 2 - $newHeight / 2); } else { $newWidth = $values['img_width']; $newHeight = $values['img_height']; } // crop image $image->crop($imgX, $imgY, $newWidth, $newHeight, $destWidth, $destHeight); // save cropped and overlayed image $image->save($path . $croppedFile); } else { // resize image $image->resize($destWidth, $destHeight); $newWidth = $image->getWidth(); $newHeight = $image->getHeight(); $image->save($path . $croppedFile); } $db = $this->getDb(); $query = sprintf("update calendar set cal_image= '%s', cal_thumbnail = '%s', cal_img_x = %d, cal_img_y = %d, cal_img_width = %d, cal_img_height = %d where cal_id = %d", addslashes($originalFile), addslashes($croppedFile), $imgX, $imgY, $newWidth, $newHeight, $id['id']); $res = $db->query($query); if ($db->isError($res)) { throw new Exception($res->getDebugInfo()); } }
public function edit($id) { global $mysql, $langArray; if (!isset($_POST['name']) || trim($_POST['name']) == '') { $error['name'] = $langArray['error_fill_this_field']; } if (!isset($_POST['description']) || trim($_POST['description']) == '') { $error['description'] = $langArray['error_fill_this_field']; } if (isset($error)) { return $error; } $photo = $this->upload('photo', '', false); if (substr($photo, 0, 6) == 'error_') { $error['photo'] = $langArray[$photo]; } if (isset($error)) { return $error; } $setQuery = ''; if ($photo != '' || isset($_POST['deletePhoto'])) { $this->deletePhoto($id); } if ($photo != '') { $setQuery .= " `photo` = '" . sql_quote($photo) . "', "; } if (!isset($_POST['visible'])) { $_POST['visible'] = 'false'; } if ($photo) { #剪裁缩略图并创建预览图 require_once ENGINE_PATH . '/classes/image.class.php'; $imageClass = new Image(); if (!file_exists(DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . '/260x140/')) { mkdir(DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . '/260x140/', 0777, true); } if (!file_exists(DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . '/192x64/')) { mkdir(DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . '/192x64/', 0777, true); } $imageClass->crop(DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . $photo, 260, 140, DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . '/260x140/' . $photo); $imageClass->crop(DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . $photo, 260, 140, DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . '/192x64/' . $photo); } $mysql->query("\n\t\t\tUPDATE `qnews`\n\t\t\tSET `name` = '" . sql_quote($_POST['name']) . "',\n\t\t\t `description` = '" . sql_quote($_POST['description']) . "',\n\t\t\t\t`url` = '" . sql_quote($_POST['url']) . "',\n\t\t\t\t\t{$setQuery}\n\t\t\t\t\t`visible` = '" . sql_quote($_POST['visible']) . "'\n\t\t\tWHERE `id` = '" . intval($id) . "'\n\t\t", __FUNCTION__); return true; }
function design($images, $border = '', $effect = '', $saveDir = '', $copyLast = false, $output = 'data') { $id = isset($images[0]['design']) && $images[0]['design'] ? $images[0]['design'] : mt_rand(); $color = strlen($images[0]['color']) == 7 ? substr($images[0]['color'], 1) : $images[0]['color']; $new_image = ($saveDir ? $saveDir : 'cache/') . 'Design-' . $id . '.png'; $path = ''; $directories = explode('/', dirname(str_replace('../', '', $new_image))); foreach ($directories as $directory) { $path = $path . '/' . $directory; if (!file_exists(DIR_IMAGE . $path)) { @mkdir(DIR_IMAGE . $path, 0777); } } $image = new Image(DIR_IMAGE . $images[0]['src']); $width = $images[0]['width']; $height = $images[0]['height']; $image->resize($width, $height, '', $color); if ($images[0]['rotation']) { $image->rotate($images[0]['rotation'] * -1); $rotate = $images[0]['rotation']; } // Look for image Mask, to trim stuff outside the target area. $imagesrc = substr($images[0]['src'], 0, -4) . '-' . $images[0]['rotation'] . substr($images[0]['src'], -4); if (file_exists(DIR_IMAGE . $imagesrc)) { $images[0]['width'] = $image->getInfo('width'); $images[0]['height'] = $image->getInfo('height'); $images[0]['mask'] = 1; $images[0]['src'] = $imagesrc; $images[0]['rotation'] = 0; } if ($copyLast || isset($images[0]['mask'])) { // Cover the top of the image with the base image $images[0]['left'] = $images[0]['top'] = 0; $images[] = $images[0]; } unset($images[0]); foreach ($images as $i => $img) { $image_temp = new Image(DIR_IMAGE . $img['src']); $size = isset($img['size']) && $img['size'] ? $img['size'] / 100 : 1; if ($img['type'] != 'text') { if (isset($images[$i]['crop']) && strpos($images[$i]['crop'], '/')) { $crop = explode('/', $images[$i]['crop']); $ratio = isset($crop[4]) ? $image_temp->getInfo('width') > $image_temp->getInfo('height') ? $image_temp->getInfo('width') / $crop[4] : $image_temp->getInfo('height') / $crop[4] : 1; $image_temp->crop($crop[0] * $ratio, $crop[1] * $ratio, $crop[2] * $ratio, $crop[3] * $ratio); } $image_temp->resize($img['width'] * $size, $img['height'] * $size, isset($img['mask']) ? '' : $effect); if ($img['rotation']) { $image_temp->rotate($img['rotation'] * -1); } } else { $image_temp->text($img['src'], $img['font'], DESIGN_TEXT_DEFAULT_SIZE * $size, DESIGN_FONT_COLOR, '', $img['rotation'] * -1); } $imgLeft = isset($img['left']) ? (int) $img['left'] : 0; $imgTop = isset($img['top']) ? (int) $img['top'] : 0; $opacity = $img['type'] != 'mainProduct' ? 80 : 100; $image->merge($image_temp->getResource(), $imgLeft, $imgTop, $opacity); } /*if ($rotate) { $image->rotate($rotate); $cx = $image->getInfo('width')/2; $cy = $image->getInfo('height')/2; $image->crop($cx - ($width/2),$cy - ($height/2), $cx + ($width/2),$cy + ($height/2)); $image->rotate($rotate*-1);*/ $width = $image->getInfo('width'); $height = $image->getInfo('height'); //} $image->resize($width, $height, $border, $color); if ($output == 'data') { return $image->getData(DIR_IMAGE . $new_image); } else { $image->save(DIR_IMAGE . $new_image); if ($this->request->server['HTTPS']) { return $this->config->get('config_ssl') . 'image/' . $new_image; } else { return $this->config->get('config_url') . 'image/' . $new_image; } } }
/** * crop image * * @return void * @author Andy Bennett */ public function crop() { // get top/left crop offsets from query string (center is default) $top = Input::instance()->get('ctop', 'center'); $left = Input::instance()->get('cleft', 'center'); // ensure the values are valid $top = (is_numeric($top) or $top == 'top' or $top == 'center' or $top == 'bottom') ? $top : 'center'; $left = (is_numeric($left) or $left == 'left' or $left == 'center' or $left == 'right') ? $left : 'center'; // $rotate = Input::instance()->get('rotate'); $flip = Input::instance()->get('flip'); $flips = array('h' => 5, 'v' => 6); $args = array_slice(Kohana::instance()->uri->segment_array(), 2); $row = $this->get_image_row($args[2]); if (isset($row->preview_id) and $row->preview_id > 0) { $row = $row->preview; } if ($row->is_image) { $image = new Image(DATAPATH . 'uploads/' . $row->file_name); // if(!is_null($rotate) && is_numeric($rotate)) { $image->rotate( (int) $rotate ); } if (!is_null($flip) and isset($flips[$flip])) { $image->flip($flips[$flip]); } $a = $image->width; $b = $image->height; if ($a != $args[0] or $b != $args[1]) { $s = $args[0] - $a; $t = $args[1] - $b; $r = max(($a + $s) / $a, ($b + $t) / $b); $x = $a * $r; $y = $b * $r; if (!is_numeric($args[0])) { die('invalid width: ' . $args[0]); } if (!is_numeric($args[1])) { die('invalid height: ' . $args[1]); } // $image->quality(75); $image->resize($x, $y, Image::NONE); $image->crop($args[0], $args[1], $top, $left); } if (!$this->use_cache) { $image->render(); die; } if ($this->border !== FALSE) { $this->add_border($image); $row->full_path = $this->cache_path; } else { // save the image to the cache, set the file path to the cache path $image->save($this->cache_path); $row->full_path = $this->cache_path; } } $this->render($row->full_path, null, $row->orig_name); }
/** * Uploades media file into auto-created folder * * @param array $data - array. Must contain elements: 'media_type', 'object_type', 'object_id', 'tmp_name', 'file', 'ext' * tmp_name - temp file to rename to media folders * real_name - if image is relocated or copied * file.ext - final name of file */ public function uploadMedia($data) { $this->clear(); $this->save($data); $id = $this->id; extract($data); // Create folders if not exists $path = $this->PHMedia->getTypePath($object_type); if (!file_exists($path)) { mkdir($path, self::MKDIR_MODE); } $path = $this->PHMedia->getPagePath($object_type, $id); if (!file_exists($path)) { mkdir($path, self::MKDIR_MODE); } $path = $this->PHMedia->getPath($object_type, $id); if (!file_exists($path)) { mkdir($path, self::MKDIR_MODE); } if (isset($real_name)) { // if image is simply relocated copy($real_name, $path . $file . $ext); $res = false; } else { // image was uploaded // TODO: handle rename error $res = rename($tmp_name, $path . $file . $ext); } if ($res) { // remove auto-thumb $path = pathinfo($tmp_name); @unlink($path['dirname'] . '/thumbnail/' . $path['basename']); } if (!isset($media_type) || $media_type == 'image') { // Save original image resolution and file size $file = $this->PHMedia->getFileName($object_type, $id, null, $file . $ext); App::uses('Image', 'Media.Vendor'); $image = new Image(); $image->load($file); $this->save(array('id' => $id, 'orig_w' => $image->getSizeX(), 'orig_h' => $image->getSizeY(), 'orig_fsize' => filesize($file))); if ($crop) { //prepare thumb for future operations list($x, $y, $sizeX, $sizeY) = explode(',', $crop); $image->crop($x, $y, $sizeX, $sizeY); $image->outputPng($this->PHMedia->getFileName($object_type, $id, null, 'thumb.png')); } // Set main image if it was first image $this->initMain($object_type, $object_id); } return $id; }
/** * Uploades media file into auto-created folder * * @param array $data - array. Must contain elements: 'media_type', 'object_type', 'object_id', 'tmp_name', 'file', 'ext' * tmp_name - temp file to rename to media folders * real_name - if image is relocated or copied * file.ext - final name of file */ public function uploadMedia($data) { $this->clear(); $this->save($data); $id = $this->id; extract($data); App::uses('CakeSession', 'Model/Datasource'); $user_id = CakeSession::read('Auth.User.id'); // Create folders if not exists $path = $this->PHMedia->getTypePath($object_type); if (!file_exists($path)) { mkdir($path, self::MKDIR_MODE); chmod($path, self::MKDIR_MODE); } $path = $this->PHMedia->getPagePath($object_type, $id); if (!file_exists($path)) { mkdir($path, self::MKDIR_MODE); chmod($path, self::MKDIR_MODE); } $path = $this->PHMedia->getPath($object_type, $id); if (!file_exists($path)) { mkdir($path, self::MKDIR_MODE); chmod($path, self::MKDIR_MODE); } $filepath = $path; if (isset($real_name)) { // if image is simply relocated copy($real_name, $path . $file . $ext); $res = false; } else { // image was uploaded // TODO: handle rename error $res = rename($tmp_name, $path . $file . $ext); } $file_size = filesize($path . $file . $ext); if ($res) { // remove auto-thumb $path = pathinfo($tmp_name); @unlink($path['dirname'] . '/thumbnail/' . $path['basename']); } if (!isset($media_type) || $media_type == 'image') { // Save original image resolution and file size $file = $this->PHMedia->getFileName($object_type, $id, null, $file . $ext); App::uses('Image', 'Media.Vendor'); $image = new Image(); $image->load($file); $this->save(array('id' => $id, 'orig_w' => $image->getSizeX(), 'orig_h' => $image->getSizeY(), 'orig_fsize' => $file_size)); $this->updateStorageData($user_id, $object_type, $file_size); if (isset($crop) and $crop) { //prepare thumb for future operations list($x, $y, $sizeX, $sizeY) = explode(',', $crop); $image->crop($x, $y, $sizeX, $sizeY); $image->outputPng($this->PHMedia->getFileName($object_type, $id, null, 'thumb.png')); } // Set main image if it was first image $this->initMain($object_type, $object_id); } else { if ('video' == $media_type) { /** @var QueuedTask $QueuedTask */ $QueuedTask = ClassRegistry::init('Queue.QueuedTask'); //480 x 360 (360p) $QueuedTask->createJob('ConvertVideo360mp4', array('filepath' => $filepath, 'filename' => $file, 'ext' => $ext, 'width' => 480, 'height' => 360, 'media_id' => $id)); $QueuedTask->createJob('ConvertVideo360ogg', array('filepath' => $filepath, 'filename' => $file, 'ext' => $ext, 'width' => 480, 'height' => 360, 'media_id' => $id)); $QueuedTask->createJob('ConvertVideo360webm', array('filepath' => $filepath, 'filename' => $file, 'ext' => $ext, 'width' => 480, 'height' => 360, 'media_id' => $id)); //858 x 480 (480p) $QueuedTask->createJob('ConvertVideo480mp4', array('filepath' => $filepath, 'filename' => $file, 'ext' => $ext, 'width' => 858, 'height' => 480, 'media_id' => $id)); $QueuedTask->createJob('ConvertVideo480ogg', array('filepath' => $filepath, 'filename' => $file, 'ext' => $ext, 'width' => 858, 'height' => 480, 'media_id' => $id)); $QueuedTask->createJob('ConvertVideo480webm', array('filepath' => $filepath, 'filename' => $file, 'ext' => $ext, 'width' => 858, 'height' => 480, 'media_id' => $id)); //1280 x 720 (720p) $QueuedTask->createJob('ConvertVideo720mp4', array('filepath' => $filepath, 'filename' => $file, 'ext' => $ext, 'width' => 1280, 'height' => 720, 'media_id' => $id)); $QueuedTask->createJob('ConvertVideo720ogg', array('filepath' => $filepath, 'filename' => $file, 'ext' => $ext, 'width' => 1280, 'height' => 720, 'media_id' => $id)); $QueuedTask->createJob('ConvertVideo720webm', array('filepath' => $filepath, 'filename' => $file, 'ext' => $ext, 'width' => 1280, 'height' => 720, 'media_id' => $id)); //1920 x 1080 (1080p) $QueuedTask->createJob('ConvertVideo1080mp4', array('filepath' => $filepath, 'filename' => $file, 'ext' => $ext, 'width' => 1920, 'height' => 1080, 'media_id' => $id)); $QueuedTask->createJob('ConvertVideo1080ogg', array('filepath' => $filepath, 'filename' => $file, 'ext' => $ext, 'width' => 1920, 'height' => 1080, 'media_id' => $id)); $QueuedTask->createJob('ConvertVideo1080webm', array('filepath' => $filepath, 'filename' => $file, 'ext' => $ext, 'width' => 1920, 'height' => 1080, 'media_id' => $id)); } $data = array('id' => $id, 'orig_fsize' => $file_size); $this->save($data); $this->updateStorageData($user_id, $object_type, $file_size); } return $id; }
/** * Creates new user photos in various sizes of a user, or deletes user photos. * Note: This method relies on configuration setting from main/inc/conf/profile.conf.php * @param int $user_id The user internal identification number. * @param string $file The common file name for the newly created photos. * It will be checked and modified for compatibility with the file system. * If full name is provided, path component is ignored. * If an empty name is provided, then old user photos are deleted only, * @see UserManager::delete_user_picture() as the prefered way for deletion. * @param string $source_file The full system name of the image from which user photos will be created. * @param string $cropParameters Optional string that contents "x,y,width,height" of a cropped image format * @return string/bool Returns the resulting common file name of created images which usually should be stored in database. * When deletion is requested returns empty string. In case of internal error or negative validation returns FALSE. */ public static function update_user_picture($user_id, $file = null, $source_file = null, $cropParameters) { if (empty($user_id)) { return false; } $delete = empty($file); if (empty($source_file)) { $source_file = $file; } // User-reserved directory where photos have to be placed. $path_info = self::get_user_picture_path_by_id($user_id, 'system'); $path = $path_info['dir']; // If this directory does not exist - we create it. if (!file_exists($path)) { mkdir($path, api_get_permissions_for_new_directories(), true); } // The old photos (if any). $old_file = $path_info['file']; // Let us delete them. if (!empty($old_file)) { if (KEEP_THE_OLD_IMAGE_AFTER_CHANGE) { $prefix = 'saved_' . date('Y_m_d_H_i_s') . '_' . uniqid('') . '_'; @rename($path . 'small_' . $old_file, $path . $prefix . 'small_' . $old_file); @rename($path . 'medium_' . $old_file, $path . $prefix . 'medium_' . $old_file); @rename($path . 'big_' . $old_file, $path . $prefix . 'big_' . $old_file); @rename($path . $old_file, $path . $prefix . $old_file); } else { @unlink($path . 'small_' . $old_file); @unlink($path . 'medium_' . $old_file); @unlink($path . 'big_' . $old_file); @unlink($path . $old_file); } } // Exit if only deletion has been requested. Return an empty picture name. if ($delete) { return ''; } // Validation 2. $allowed_types = api_get_supported_image_extensions(); $file = str_replace('\\', '/', $file); $filename = ($pos = strrpos($file, '/')) !== false ? substr($file, $pos + 1) : $file; $extension = strtolower(substr(strrchr($filename, '.'), 1)); if (!in_array($extension, $allowed_types)) { return false; } // This is the common name for the new photos. if (KEEP_THE_NAME_WHEN_CHANGE_IMAGE && !empty($old_file)) { $old_extension = strtolower(substr(strrchr($old_file, '.'), 1)); $filename = in_array($old_extension, $allowed_types) ? substr($old_file, 0, -strlen($old_extension)) : $old_file; $filename = substr($filename, -1) == '.' ? $filename . $extension : $filename . '.' . $extension; } else { $filename = api_replace_dangerous_char($filename); if (PREFIX_IMAGE_FILENAME_WITH_UID) { $filename = uniqid('') . '_' . $filename; } // We always prefix user photos with user ids, so on setting // api_get_setting('split_users_upload_directory') === 'true' // the correspondent directories to be found successfully. $filename = $user_id . '_' . $filename; } //Crop the image to adjust 1:1 ratio $image = new Image($source_file); $image->crop($cropParameters); // Storing the new photos in 4 versions with various sizes. $small = new Image($source_file); $small->resize(22); $small->send_image($path . 'small_' . $filename); $medium = new Image($source_file); $medium->resize(85); $medium->send_image($path . 'medium_' . $filename); $normal = new Image($source_file); $normal->resize(200); $normal->send_image($path . $filename); $big = new Image($source_file); // This is the original picture. $big->send_image($path . 'big_' . $filename); $result = $small && $medium && $normal && $big; return $result ? $filename : false; }
public function edit($id) { global $mysql; if (!isset($_POST['name']) || trim($_POST['name']) == '') { $_POST['name'] = 'Bookmark Collection'; } if (!isset($_POST['description'])) { $_POST['description'] = ''; } if (!isset($_POST['publically_visible'])) { $_POST['publically_visible'] = 'false'; } else { $_POST['publically_visible'] = 'true'; } $setQuery = ''; $photo = $this->upload('file_upload', '', false); if (substr($photo, 0, 6) == 'error_') { $photo = ''; } if ($photo != '') { $this->deletePhoto($id); $setQuery = " `photo` = '" . sql_quote($photo) . "', "; } $mysql->query("\n\t\t\tUPDATE `collections`\n\t\t\tSET `name` = '" . sql_quote($_POST['name']) . "',\n\t\t\t\t\t`text` = '" . sql_quote($_POST['description']) . "',\n\t\t\t\t\t{$setQuery}\n\t\t\t\t\t`public` = '" . sql_quote($_POST['publically_visible']) . "'\n\t\t\tWHERE `id` = '" . intval($id) . "'\n\t\t"); if ($photo != '') { require_once ENGINE_PATH . '/classes/image.class.php'; $imageClass = new Image(); $imageClass->crop(DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . $photo, 260, 140); } return true; }
public function edit($id, $fromAdmin = false) { global $mysql, $langArray, $attributes; //作品详情 $item_info = $this->get($id); $user_id = $_SESSION['user']['user_id']; if (!$user_id) { return false; } //临时文件目录 $temporary_dir = DATA_SERVER_PATH . 'uploads/temporary/' . $user_id . '/'; if (!isset($_POST['description']) || trim($_POST['description']) == '') { $error['description'] = $langArray['error_not_set_description']; } if ($fromAdmin && (!isset($_POST['price']) || trim($_POST['price']) == '' || $_POST['price'] == '0')) { $error['price'] = $langArray['error_not_set_price']; } if (isset($_POST['demo_url']) && trim($_POST['demo_url']) && filter_var($_POST['demo_url'], FILTER_VALIDATE_URL) === false) { $error['demo_url'] = $langArray['error_demo_url']; } if (!isset($_POST['category'])) { $error['category'] = $langArray['error_not_set_category']; } elseif (!is_numeric($_POST['category']) && !is_array($_POST['category'])) { $error['category'] = $langArray['error_not_set_category']; } if (!isset($_POST['tags']) || empty($_POST['tags'])) { $error['tags_features'] = $langArray['error_not_set_tags']; } else { $tags_data = explode(',', $_POST['tags']); if (count($tags_data) > 6) { $error['tags_features'] = $langArray['error_not_set_tags_tomore']; } } //作品非active状态禁止修改文件------------ $edit_file_num = 0; //修改文件是否存在 if (file_exists($temporary_dir . $_POST['thumbnail']) || file_exists($temporary_dir . $_POST['first_preview']) || file_exists($temporary_dir . $_POST['main_file'])) { $edit_file_num++; } //预览图 $theme_preview_arr = explode(',', $_POST['theme_preview']); foreach ($theme_preview_arr as $file_exis) { if (file_exists($temporary_dir . $file_exis)) { $edit_file_num++; } } if ($item_info['status'] != 'active' && $edit_file_num > 0) { $error['file_status_error'] = $langArray['file_status_error']; } //(缩略图) if (isset($_POST['thumbnail']) && trim($_POST['thumbnail']) != '') { $file = pathinfo($_POST['thumbnail']); if (!in_array(strtolower($file['extension']), $this->support_format(1))) { $error['thumbnail'] = $langArray['error_thumbnail_jpg']; } } // (预览图) if (isset($_POST['theme_preview'])) { $theme_preview_arr = explode(',', $_POST['theme_preview']); if (!isset($theme_preview_arr) || !is_array($theme_preview_arr)) { $error['theme_preview'] = $langArray['error_not_set_theme_preview']; } else { foreach ($theme_preview_arr as $theme_f) { $theme_file = pathinfo($theme_f); if (!in_array(strtolower($theme_file['extension']), $this->support_format(0))) { $error['theme_preview'] = $langArray['error_theme_preview_jpg']; } } } } // (封面) if (isset($_POST['first_preview']) && trim($_POST['first_preview']) != '') { $file = pathinfo($_POST['first_preview']); if (!in_array(strtolower($file['extension']), $this->support_format(0))) { $error['first_preview'] = $langArray['error_theme_preview_jpg']; } } // (主程序包) if (isset($_POST['main_file']) && trim($_POST['main_file']) != '') { $file = pathinfo($_POST['main_file']); if (strtolower($file['extension']) != 'zip') { $error['main_file'] = $langArray['error_main_file_zip']; } } if (is_array($attributes)) { $attributesError = false; foreach ($attributes as $a) { if (!isset($_POST['attributes'][$a['id']])) { $attributesError = true; break; } } if ($attributesError) { $error['attributes'] = $langArray['error_set_all_attributes']; } } if (isset($error)) { return $error; } $setQuery = ''; if ($fromAdmin) { $setQuery .= " `price` = '" . sql_quote($_POST['price']) . "', "; if (isset($_POST['free_file'])) { $setQuery .= " `free_file` = 'true', "; } //周推荐至-时间 if (isset($_POST['weekly_to']) && trim($_POST['weekly_to']) != '') { $setQuery .= " `weekly_to` = '" . sql_quote($_POST['weekly_to']) . "', "; } } //演示地址 if (!isset($_POST['demo_url'])) { $_POST['demo_url'] = ''; } //作品状态是否为请求免费上架状态 if (!isset($_POST['free_request'])) { $_POST['free_request'] = 'false'; } //更新作品表 $mysql->query("\n\t\t\tUPDATE `items`\n\t\t\tSET `description` = '" . sql_quote($_POST['description']) . "',\n\t\t\t\t\t`free_request` = '" . sql_quote($_POST['free_request']) . "',\n\t\t\t\t\t{$setQuery}\n\t\t\t\t\t`demo_url` = '" . sql_quote($_POST['demo_url']) . "'\n\t\t\tWHERE `id` = '" . intval($id) . "'\n\t\t\tLIMIT 1\n\t\t"); require_once ROOT_PATH . '/apps/categories/models/categories.class.php'; $categoriesClass = new categories(); $allCategories = $categoriesClass->getAll(); $mysql->query("DELETE FROM `items_to_category` WHERE `item_id` = '" . intval($id) . "'"); if (is_array($_POST['category'])) { foreach ($_POST['category'] as $category_id) { $categories = $categoriesClass->getCategoryParents($allCategories, $category_id); $categories = explode(',', $categories); array_pop($categories); $categories = array_reverse($categories); $categories = ',' . implode(',', $categories) . ','; $mysql->query("\n\t\t\t\t\tINSERT INTO `items_to_category` (\n\t\t\t\t\t\t`item_id`,\n\t\t\t\t\t\t`categories`\n\t\t\t\t\t) \n\t\t\t\t\tVALUES (\n\t\t\t\t\t\t'" . intval($id) . "',\n\t\t\t\t\t\t'" . sql_quote($categories) . "'\n\t\t\t\t\t)\n\t\t\t\t"); } } else { $categories = $categoriesClass->getCategoryParents($allCategories, $_POST['category']); $categories = explode(',', $categories); array_pop($categories); $categories = array_reverse($categories); $categories = ',' . implode(',', $categories) . ','; $mysql->query("\n\t\t\t\tINSERT INTO `items_to_category` (\n\t\t\t\t\t`item_id`,\n\t\t\t\t\t`categories`\n\t\t\t\t) \n\t\t\t\tVALUES (\n\t\t\t\t\t'" . intval($id) . "',\n\t\t\t\t\t'" . sql_quote($categories) . "'\n\t\t\t\t)\n\t\t\t"); } //更新属性 $mysql->query("\n\t\t\tDELETE FROM `items_attributes`\n\t\t\tWHERE `item_id` = '" . intval($id) . "'\n\t\t"); $_POST['attributes'] = (array) (isset($_POST['attributes']) ? $_POST['attributes'] : array()); foreach ($_POST['attributes'] as $cID => $a) { if (is_array($a)) { foreach ($a as $ai) { if (!trim($ai)) { continue; } $mysql->query("\n\t\t\t\t\t\tINSERT INTO `items_attributes` (\n\t\t\t\t\t\t\t`item_id`,\n\t\t\t\t\t\t\t`attribute_id`,\n\t\t\t\t\t\t\t`category_id`\n\t\t\t\t\t\t)\n\t\t\t\t\t\tVALUES (\n\t\t\t\t\t\t\t'" . intval($id) . "',\n\t\t\t\t\t\t\t'" . sql_quote($ai) . "',\n\t\t\t\t\t\t\t'" . sql_quote($cID) . "'\n\t\t\t\t\t\t)\n\t\t\t\t\t"); } } else { if (!trim($a)) { continue; } $mysql->query("\n\t\t\t\t\tINSERT INTO `items_attributes` (\n\t\t\t\t\t\t`item_id`,\n\t\t\t\t\t\t`attribute_id`,\n\t\t\t\t\t\t`category_id`\n\t\t\t\t\t)\n\t\t\t\t\tVALUES (\n\t\t\t\t\t\t'" . intval($id) . "',\n\t\t\t\t\t\t'" . sql_quote($a) . "',\n\t\t\t\t\t\t'" . sql_quote($cID) . "'\n\t\t\t\t\t)\n\t\t\t\t"); } } if ($fromAdmin) { //免费 if (isset($_POST['free_file'])) { $this->addUserStatus($id, 'freefile'); $mysql->query("\n\t\t\t\t\tUPDATE `items`\n\t\t\t\t\tSET `free_file` = 'true'\n\t\t\t\t\tWHERE `id` = '" . intval($id) . "'\n\t\t\t\t\tLIMIT 1\n\t\t\t\t"); } else { $mysql->query("\n\t\t\t\t\tUPDATE `items`\n\t\t\t\t\tSET `free_file` = 'false'\n\t\t\t\t\tWHERE `id` = '" . intval($id) . "'\n\t\t\t\t\tLIMIT 1\n\t\t\t\t"); } if (isset($_POST['weekly_to']) && trim($_POST['weekly_to']) != '') { $this->addUserStatus($id, 'featured'); } $key_num = 0; $setQuery_e = ''; //缩略图 if (isset($_POST['thumbnail']) && trim($_POST['thumbnail']) != '' && file_exists($temporary_dir . $_POST['thumbnail'])) { //检测文件是否被修改 $thumbnail_is = $this->is_edit_item_file($id); $path_file_name = pathinfo($thumbnail_is['thumbnail']); if ($_POST['thumbnail'] != $path_file_name['basename']) { unlink(DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . $id . '/' . $path_file_name['basename']); require_once ENGINE_PATH . '/classes/image.class.php'; $imageClass = new Image(); //缩略图 $temporary_thumbnail_file = $temporary_dir . $_POST['thumbnail']; //裁剪缩略图 $imageClass->crop($temporary_thumbnail_file, 90, 90); copy($temporary_thumbnail_file, DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . $id . '/' . $_POST['thumbnail']); @unlink($temporary_thumbnail_file); $setQuery_e .= ", `thumbnail` = '" . $_POST['thumbnail'] . "'"; $key_num++; } } //预览图 $theme_preview_arr = explode(',', $_POST['theme_preview']); if (isset($theme_preview_arr) && is_array($theme_preview_arr)) { //获取所有预览图 $all_preview = $this->get_theme_preview($id); //预览图路径 $all_preview_dir = array(); foreach ($all_preview as $pre) { $view = pathinfo($pre['dir']); $all_preview_dir[] = $view['basename']; //文件是否修改 if (!in_array($view['basename'], $theme_preview_arr)) { //删除预览 $this->del_preview_by_id($pre['id']); unlink(DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . $id . '/preview/' . $view['basename']); } } foreach ($theme_preview_arr as $post_theme_file) { //判断文件是否被修改 if (!in_array($post_theme_file, $all_preview_dir)) { //判断文件格式 copy($temporary_dir . $post_theme_file, DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . $id . '/preview/' . $post_theme_file); @unlink($temporary_dir . $post_theme_file); #插入预览图 $this->save_theme_preview($id, DATA_SERVER . '/uploads/' . $this->uploadFileDirectory . $id . '/preview/' . $post_theme_file); $key_num++; } } } //封面预览图 if (isset($_POST['first_preview']) && trim($_POST['first_preview']) != '' && file_exists($temporary_dir . $_POST['first_preview'])) { //检测文件是否被修改 $first_preview_is = $this->is_edit_item_file($id); $path_first_file_name = pathinfo($first_preview_is['theme_preview']); if ($_POST['first_preview'] != $path_first_file_name['basename']) { $temporary_first_preview_file = $temporary_dir . $_POST['first_preview']; unlink(DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . $id . '/' . $path_first_file_name['basename']); copy($temporary_first_preview_file, DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . $id . '/' . $_POST['first_preview']); @unlink($temporary_first_preview_file); $setQuery_e .= ", `theme_preview` = '" . $_POST['first_preview'] . "'"; $key_num++; } } //主程序包 if (isset($_POST['main_file']) && trim($_POST['main_file']) != '' && file_exists($temporary_dir . $_POST['main_file'])) { //检测文件是否被修改 $main_file_is = $this->is_edit_item_file($id); $path_first_file_name = pathinfo($main_file_is['main_file']); if ($_POST['main_file'] != $path_first_file_name['basename']) { unlink(DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . $id . '/' . $path_first_file_name['basename']); $temporary_main_file = $temporary_dir . $_POST['main_file']; copy($temporary_main_file, DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . $id . '/' . $_POST['main_file']); @unlink($temporary_main_file); $key_num++; //更新文件名 $setQuery_e .= ", `main_file` = '" . $_POST['main_file'] . "'"; // $setQuery_e .= ", `main_file_name` = '".sql_quote($_SESSION['temp']['edit_item']['main_file_name'])."' "; } } } if ($key_num > 0) { //更新作品状态 $mysql->query("\n\t\t\t\tUPDATE `items`\n\t\t\t\tSET `status` = 'queue' {$setQuery_e}\n\t\t\t\tWHERE `id` = '" . intval($id) . "'\n\t\t\t\tLIMIT 1\n\t\t\t"); } //编辑推荐标签(删除原有 然后新增) require_once ROOT_PATH . '/apps/tags/models/tags.class.php'; $tags = new tags(); //删除原绑定标签 $tags->del_by_item_id($id); //重写绑定标签 $tags_data = explode(',', $_POST['tags']); $tag_arr = array(); foreach ($tags_data as $val) { $tags->add_tags(array('item_id' => $id, 'tag_id' => $val)); } return true; }
/** * Update course picture * @param string Course code * @param string File name * @param string The full system name of the image from which course picture will be created. * @param string $cropParameters Optional string that contents "x,y,width,height" of a cropped image format * @return bool Returns the resulting. In case of internal error or negative validation returns FALSE. */ public static function update_course_picture($course_code, $filename, $source_file = null, $cropParameters = null) { $course_info = api_get_course_info($course_code); // course path $store_path = api_get_path(SYS_COURSE_PATH) . $course_info['path']; // image name for courses $course_image = $store_path . '/course-pic.png'; $course_medium_image = $store_path . '/course-pic85x85.png'; if (file_exists($course_image)) { unlink($course_image); } if (file_exists($course_medium_image)) { unlink($course_medium_image); } //Crop the image to adjust 4:3 ratio $image = new Image($source_file); $image->crop($cropParameters); //Resize the images in two formats $medium = new Image($source_file); $medium->resize(85); $medium->send_image($course_medium_image, -1, 'png'); $normal = new Image($source_file); $normal->resize(300); $normal->send_image($course_image, -1, 'png'); $result = $medium && $normal; return $result ? $result : false; }
public function portrait($arrFiles, $quality, $sharpen, $imgWidth, $thWidth) { foreach ($arrFiles as $file) { $image = new Image($this->path->tmp . $file); $imageWidth = $image->width; $imageHeight = $image->height; //set maximum height of thumbnail $thHeight = $thWidth / $this->conf->ratioThumb; if ($imageWidth < $thWidth) { //image width is smaller than thumbnail width $thWidth = $imageWidth; } //will use image width as thumbnail width if ($imageWidth < $imgWidth) { //image width is smaller than pop-up image width $imgWidth = $imageWidth; } //will use image width as pop-up width //create pop-up image //if image width is smaller than thumbnail width we don't resize it //image width is bigger than pop-up image width, need resize if ($imageWidth > $imgWidth) { $image->resize($imgWidth, NULL)->quality($quality)->sharpen($sharpen); } //save pop-up image $image->save($this->path->images . $file, 0666, false); //create thumbnail //if image width and height is smaller than thumbnail width and height we don't resize it //image width or height is bigger than thumbnail width or height if ($imageWidth > $thWidth || $imageHeight > $thHeight) { // if($imageWidth >= $imageHeight)//landscape or square image // $image->resize($thWidth, $thHeight, Image::HEIGHT); // //portrait // if($imageWidth < $imageHeight) $image->resize($thWidth, $thHeight, Image::HEIGHT); $image->crop($thWidth, $thHeight, 'center')->quality($quality)->sharpen($sharpen); } //save thumbnail $image->save($this->path->thumbnails . $file, 0666, false); } }
private function generate_style($file, $dim, $quality) { $file_name = basename($file); $dir = dirname($file); $new_file = "_cache/" . $dir . "/" . $this->url_safe($dim) . "-" . $file_name; if (!File::exists($file)) { return null; } if (!File::exists($new_file) || File::isNewer($file, $new_file)) { if (!is_dir(dirname($new_file))) { mkdir(dirname($new_file), 0777, true); } $image = new Image($file); $resize = true; list($width, $height, $fix, $crop, $vh) = $this->parse_dim($dim); if ($fix) { $dimension = Image::NONE; } else { $dimension = Image::WIDTH; $wd = $image->width - $width; $hd = $image->height - $height; $pp = $image->width / $image->height * $hd; if ($vh) { if ($vh == 'v') { $dimension = Image::HEIGHT; if (abs($wd) < abs($hd)) { $crop = true; } } elseif ($vh == 'h') { $dimension = Image::WIDTH; if ($wd < 0) { //$resize = false; } else { } } } else { if ($crop) { if ($wd >= $hd && $pp < $wd || $wd < 1 && $pp < $wd) { $dimension = Image::HEIGHT; } } else { if ($wd <= $hd && $pp > $wd || $wd > 1 && $pp > $wd) { $dimension = Image::HEIGHT; } } } } if ($resize) { $image->resize($width, $height, $dimension); } if ($crop) { $image->crop($width, $height, null); } $image->save($new_file, $quality); } $info = getimagesize($new_file); $ret = array(); $ret['width'] = $info[0]; $ret['height'] = $info[1]; $ret['url'] = "/" . $new_file; #backwards compatibility $ret['image_url'] = $ret['url']; return $ret; }
/** * Crops image. * @param int x-coordinate * @param int y-coordinate * @param int width * @param int height * @return ImageMagick provides a fluent interface */ public function crop($left, $top, $width, $height) { if ($this->file === NULL) { return parent::crop($left, $top, $width, $height); } $left = max(0, (int) $left); $top = max(0, (int) $top); $width = min((int) $width, $this->getWidth() - $left); $height = min((int) $height, $this->getHeight() - $top); $this->execute("convert -crop {$width}x{$height}+{$left}+{$top} -strip %input %output", self::PNG); return $this; }
public function save_crop($apikey, $params) { if (!isset($params[1])) { return 'Invalid Parameters'; } $img_path = t_paths::image($apikey) . "/full_{$this->image}"; $image = new Image($img_path); $width = $image->__get('width'); $height = $image->__get('height'); # Make thumbnail from supplied post params. $size = 125; $thumb_path = t_paths::image($apikey) . "/{$this->image}"; $image->crop($params[0], $params[1], $params[2], $params[3])->resize($size, $size)->save($thumb_path); return 'Image saved!'; }
/** * create a cropped image ( do size first, then crop ) * * @param string $field * @return void * @author Andy Bennett */ public static function crop($field = false) { self::init(); $sa = array_reverse(URI::instance()->segment_array()); $image = $sa[0]; $h = $sa[1]; $w = $sa[2]; $top = Input::instance()->get('ctop', 'center'); $left = Input::instance()->get('cleft', 'center'); $row = self::returnImageRow($field, $image); if ($row === false) { self::no_image(); } $path = Kohana::config('upload.upload')->staticfiles_path . Kohana::config('upload.upload')->upload_path . $row->file_name; ini_set("memory_limit", "100M"); $cache_path = APPPATH . 'cache/images/' . dirname(Kohana::instance()->uri->string()); if (!file_exists($cache_path)) { @mkdir($cache_path, 0777, TRUE); } $cache_path .= '/' . $row->file_name; $use_cache = 0; if ($row->is_image) { if (file_exists($cache_path) && (time() - filemtime($cache_path)) / 60 > 5) { @unlink($cache_path); } if (!file_exists($cache_path) || !$use_cache) { if (!file_exists($path)) { die('invalid path:- ' . $path); } $props = getimagesize($path); $image = new Image($path); $a = $props[0]; $b = $props[1]; if ($a == $w and $b == $h) { @copy($path, $cache_path); } else { $s = $w - $a; $t = $h - $b; $r = max(($a + $s) / $a, ($b + $t) / $b); $x = $a * $r; $y = $b * $r; // echo("<br/>\n s: "); var_dump($s); // echo("<br/>\n t: "); var_dump($t); // echo("<br/>\n r: "); var_dump($r); // echo("<br/>\n x: "); var_dump($x); // echo("<br/>\n y: "); var_dump($y); // exit; $image->resize($x, $y, Image::NONE); $image->crop($w, $h, $top, $left); if (!is_numeric($w)) { die('invalid width: ' . $w); } if (!is_numeric($h)) { die('invalid height: ' . $h); } $image->save($cache_path); } } header('Content-type: ' . $row->file_type); header("Content-Length: " . filesize($cache_path)); readfile($cache_path); exit; } else { header('Content-type: ' . $row->file_type); header('Content-Disposition: attachment; filename="' . $row->orig_name . '"'); header("Content-Length: " . filesize($path)); readfile($path); exit; } }
private function manipulate($file, $options) { //Первым делом валидация $this->validateOptions($options); $targetFolder = $options['folder']; $fileName = $options['fileName']; //Путь будущего изображения $path = self::getAbsolutePath($targetFolder, $fileName); //Если изменять размеры не нужно - просто сделаем копию изображения if (isset($options['resize'])) { if ($options['resize'] === false) { copy($file->getTempName(), $path); return; } } //Ширина и высота требуемого изображения $targetWidth = $options['width']; $targetHeight = $options['height']; //Ширина и высота загруженного изображения list($uploadedWidth, $uploadedHeight) = getimagesize($file->getTempName()); //Если изменять размеры не нужно - просто сделаем копию изображения if (isset($options['smartResize'])) { if ($options['smartResize'] === false) { //Если требуемое изображение больше загруженного, его не нужно изменять if ($targetWidth > $uploadedWidth && $targetHeight > $uploadedHeight) { copy($file->getTempName(), $path); } else { //Изображение для манипуляции берется из временной папки $image = new Image($file->getTempName()); //Манипуляция $image->resize($targetWidth, $targetHeight, Image::AUTO)->sharpen(1)->quality(95)->save($path); } return; } } //Отношение сторон загруженного и требуемого изображения $uploadedRatio = $uploadedWidth / $uploadedHeight; $targetRatio = $targetWidth / $targetHeight; //Сравниваем отношения и считаем координаты для кадрирования(если нарисовать на бумаге алгоритм становится очевидным :)) if ($uploadedRatio > $targetRatio) { $cropHeight = $uploadedHeight; $cropWidth = $uploadedHeight * $targetRatio; $cropLeft = ($uploadedWidth - $uploadedHeight * $targetRatio) * 0.5; $cropTop = 0; } else { $cropHeight = $uploadedWidth / $targetRatio; $cropWidth = $uploadedWidth; $cropLeft = 0; $cropTop = ($uploadedHeight - $uploadedWidth / $targetRatio) * 0.2; } //Изображение для манипуляции берется из временной папки $image = new Image($file->getTempName()); //Манипуляция $image->crop($cropWidth, $cropHeight, $cropTop, $cropLeft)->resize($targetWidth, $targetHeight, Image::NONE)->sharpen(1)->quality(95)->save($path); }
/** Applies any options to the supplied image * resize, crop, text, fadeframe * TODO: introduce API for other filters */ public static function applyImageOptions(Image $image, $opts) { //crop image to square or just resize if ($opts['w'] && $opts['h']) { //not isset - always availible if (isset($opts["crop"])) { $image->resize($opts['w'], $opts['h'], Image::FILL); $image->crop('50%', '20%', $opts['w'], $opts['h']); } elseif (isset($opts["crop2"])) { $image->crop('50%', '20%', $opts['w'], $opts['h']); } else { $image->resize($opts['w'], $opts['h'], Image::SHRINK_ONLY); } } //insert text if (isset($opts["text"])) { $image->string(7, 0.1 * $image->width, 0.4 * $image->height, $opts["text"], Image::rgb(255, 255, 255)); } //fade out frame if (isset($opts["fadeframe"])) { $size = (int) $opts["fadeframe"]; if ($size < 2) { $size = 10; } $w = $image->width; $h = $image->height; for ($i = 0; $i < $size; $i++) { $image->line(0, $i, $w, $i, Image::rgb(255, 255, 255, round(127 / $size * $i))); $image->line(0, $h - $i, $w, $h - $i, Image::rgb(255, 255, 255, round(127 / $size * $i))); $image->line($i, 0, $i, $h, Image::rgb(255, 255, 255, round(127 / $size * $i))); $image->line($w - $i, 0, $w - $i, $h, Image::rgb(255, 255, 255, round(127 / $size * $i))); } } }