/** * @inheritdoc */ public function run() { if (Yii::$app->request->isPost) { $file = UploadedFile::getInstanceByName($this->uploadParam); $model = new DynamicModel(compact($this->uploadParam)); $model->addRule($this->uploadParam, 'file', ['maxSize' => $this->maxSize, 'tooBig' => Yii::t('upload', 'TOO_BIG_ERROR', ['size' => $this->maxSize / (1024 * 1024)]), 'extensions' => explode(', ', $this->extensions), 'checkExtensionByMimeType' => false, 'wrongExtension' => Yii::t('upload', 'EXTENSION_ERROR', ['formats' => $this->extensions])])->validate(); if ($model->hasErrors()) { $result = ['error' => $model->getFirstError($this->uploadParam)]; } else { $model->{$this->uploadParam}->name = uniqid() . '.' . $model->{$this->uploadParam}->extension; $request = Yii::$app->request; $image_name = $this->temp_path . $model->{$this->uploadParam}->name; $image = Image::crop($file->tempName . $request->post('filename'), intval($request->post('w')), intval($request->post('h')), [$request->post('x'), $request->post('y')])->resize(new Box($this->width, $this->height))->save($image_name); // watermark if ($this->watermark != '') { $image = Image::watermark($image_name, $this->watermark)->save($image_name); } if ($image->save($image_name)) { // create Thumbnail if ($this->thumbnail && ($this->thumbnail_width > 0 && $this->thumbnail_height > 0)) { Image::thumbnail($this->temp_path . $model->{$this->uploadParam}->name, $this->thumbnail_width, $this->thumbnail_height)->save($this->temp_path . '/thumbs/' . $model->{$this->uploadParam}->name); } $result = ['filelink' => $model->{$this->uploadParam}->name]; } else { $result = ['error' => Yii::t('upload', 'ERROR_CAN_NOT_UPLOAD_FILE')]; } } Yii::$app->response->format = Response::FORMAT_JSON; return $result; } else { throw new BadRequestHttpException(Yii::t('upload', 'ONLY_POST_REQUEST')); } }
public function actionCrop($id) { $model = $this->findModel($id); $type = \Yii::$app->getRequest()->post("type"); $x = \Yii::$app->getRequest()->post("x"); $y = \Yii::$app->getRequest()->post("y"); $w = \Yii::$app->getRequest()->post("w"); $h = \Yii::$app->getRequest()->post("h"); switch ($type) { case CropType::ALL: $original = $model->getAbsolutePath(); Image::crop($original, $w, $h, [$x, $y])->save($original); $model->deleteThumbs(); break; case CropType::THUMBNAIL: $original = $model->getAbsolutePath(); $newPath = $model->getTempDirectory() . DIRECTORY_SEPARATOR . $model->hash . "." . $model->extension; $newOriginal = \Yii::$app->get("fileStorage")->getPath($newPath); Image::crop($original, $w, $h, [$x, $y])->save($newOriginal); $thumbs = $model->getThumbs(); foreach ($thumbs as $path) { $fileName = ltrim(pathinfo(" " . $path, PATHINFO_FILENAME)); $parts = explode("_", $fileName); list($w, $h) = explode("x", $parts[2]); Image::thumbnail($newOriginal, $w, $h)->save(\Yii::$app->get("fileStorage")->getPath($path)); } \Yii::$app->get("fileStorage")->delete($newPath); break; case CropType::ORIGINAL: $original = $model->getAbsolutePath(); Image::crop($original, $w, $h, [$x, $y])->save($original); break; } return $this->renderJsonMessage(true, "裁剪成功"); }
/** * @inheritdoc */ public function run() { if (Yii::$app->request->isPost) { $file = UploadedFile::getInstanceByName($this->uploadParam); $model = new DynamicModel(compact($this->uploadParam)); $model->addRule($this->uploadParam, 'image', ['maxSize' => $this->maxSize, 'tooBig' => Yii::t('cropper', 'TOO_BIG_ERROR', ['size' => $this->maxSize / (1024 * 1024)]), 'extensions' => explode(', ', $this->extensions), 'wrongExtension' => Yii::t('cropper', 'EXTENSION_ERROR', ['formats' => $this->extensions])])->validate(); if ($model->hasErrors()) { $result = ['error' => $model->getFirstError($this->uploadParam)]; } else { $model->{$this->uploadParam}->name = uniqid() . '.' . $model->{$this->uploadParam}->extension; $request = Yii::$app->request; $width = $request->post('width', $this->width); $height = $request->post('height', $this->height); $image = Image::crop($file->tempName . $request->post('filename'), intval($request->post('w')), intval($request->post('h')), [$request->post('x'), $request->post('y')])->resize(new Box($width, $height)); if ($image->save($this->path . $model->{$this->uploadParam}->name)) { $result = ['filelink' => $this->url . $model->{$this->uploadParam}->name]; } else { $result = ['error' => Yii::t('cropper', 'ERROR_CAN_NOT_UPLOAD_FILE')]; } } Yii::$app->response->format = Response::FORMAT_JSON; return $result; } else { throw new BadRequestHttpException(Yii::t('cropper', 'ONLY_POST_REQUEST')); } }
/** * 裁剪图片 * @param $filename string 图片全路径(./uploads/editor/20150516/demo.jpg) * @param int $width 裁剪后的宽 * @param int $height 裁剪后的高 * @param string $qz 裁剪后图片的前缀 * @param string $type 裁剪类型 [居中裁剪('center')] * @return string */ public static function crop($filename, $width = 200, $height = 200, $qz = 'crop_', $type = 'center') { // 获取图片居中裁剪的 x坐标,y坐标 $info = getimagesize($filename); // 判断,裁剪后图片的宽高不能大于原图的宽高 if ($info[0] < $width) { $width = $info[0]; } if ($info[1] < $height) { $height = $info[1]; } switch ($type) { // 目前我只用到了居中裁剪,需要其他的裁剪方式自己加就好了 case 'center': // 居中裁剪坐标 $x = ($info[0] - $width) * 0.5; $y = ($info[1] - $height) * 0.5; break; default: // 默认居中裁剪坐标 $x = ($info[0] - $width) * 0.5; $y = ($info[1] - $height) * 0.5; } $saveName = self::qz($filename, $qz); // 保存图片 Image::crop($filename, $width, $height, [$x, $y])->save($saveName); // save()方法有第二个参数数组,可以设置保存图片的质量 save($savename, ['quality' => 80]); return trim($saveName, './'); }
public function testCrop() { $point = [20, 20]; $img = Image::crop($this->imageFile, 100, 100, $point); $this->assertEquals(100, $img->getSize()->getWidth()); $this->assertEquals(100, $img->getSize()->getHeight()); }
public function ImageCrop($pathToImg = "", $params = []) { $imageSize = getimagesize($pathToImg); $width = $imageSize[0]; $height = $imageSize[1]; list($imgWidth, $imgHeight) = explode(":", $params["crop"]); $centerWidth = $width / 2 - $imgWidth / 2; $centerHeight = $height / 2 - $imgHeight / 2; Image::crop($pathToImg, $imgWidth, $imgHeight, [$centerWidth, $centerHeight])->save($pathToImg, ["quality" => 100]); }
public function actionAvatar() { $user = $this->finder->findUserById(Yii::$app->user->identity->getId()); if (\Yii::$app->getRequest()->isAjax) { $avatar = \Yii::$app->getRequest()->post("avatar"); $x = \Yii::$app->getRequest()->post("x"); $y = \Yii::$app->getRequest()->post("y"); $w = \Yii::$app->getRequest()->post("w"); $h = \Yii::$app->getRequest()->post("h"); $original = \Yii::$app->get("fileStorage")->getPath($avatar); Image::crop($original, $w, $h, [$x, $y])->save($original); $user->saveAvatar($avatar); Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; $message = Yii::createObject('\\hass\\base\\classes\\JSONMessage', [true, "保存成功"]); $result = $message->getArray(); return $result; } return $this->render('avatar', ['user' => $user]); }
public function applyFilter($loadFromPath, $imageSavePath) { if (!$this->evalMethod()) { throw new InvalidConfigException('The requested effect mode ' . $this->effect->imagine_name . ' is not supported'); } if (!$this->evalRequiredMethodParams()) { throw new InvalidConfigException("The requested effect mode does require some parameters which are not provided."); } switch ($this->effect->imagine_name) { case "crop": $image = Image::crop($loadFromPath, $this->getMethodParam('width'), $this->getMethodParam('height')); Image::autoRotate($image)->save($imageSavePath, $this->getMethodParam('saveOptions')); break; case "thumbnail": $image = Image::thumbnail($loadFromPath, $this->getMethodParam('width'), $this->getMethodParam('height'), $this->getMethodParam('mode')); Image::autoRotate($image)->save($imageSavePath, $this->getMethodParam('saveOptions')); break; } }
/** * @inheritdoc */ public function run() { if (Yii::$app->request->isPost) { $data = Yii::$app->request->post(); if (!empty($data['url'])) { try { $crop = []; if (!empty($data['crop'])) { $crop = explode(',', $data['crop']); if (count($crop) !== 4) { return Json::encode(['errors' => ['Invalid crop options!']]); } foreach ($crop as $c) { if (!is_numeric(trim($c)) || trim($c) < 0 || trim($c) > 1) { return Json::encode(['errors' => ['Invalid crop options!']]); } } } $url = $data['url']; $url = str_replace(Yii::$app->request->baseUrl, '', $url); if (substr($url, 0, 1) == '/') { $url = substr($url, 1); } if (strpos($url, '?_ignore=') !== false) { $url = substr($url, 0, strpos($url, '?_ignore=')); } if (!empty($crop)) { list($width, $height) = getimagesize($url); Image::crop($url, floor($width * trim($crop[3]) - $width * trim($crop[1])), floor($height * trim($crop[2]) - $height * trim($crop[0])), [floor($width * trim($crop[1])), floor($height * trim($crop[0]))])->save($url); } list($width, $height) = getimagesize($url); return Json::encode(['size' => [$width, $height], 'url' => Yii::$app->request->baseUrl . '/' . $url, 'alt' => basename($url)]); } catch (Exception $e) { return Json::encode(['errors' => [$e->getMessage()]]); } } else { return Json::encode(['errors' => ['Invalid insert options!']]); } } }
/** * Crop image * @param UploadedFile $file * @param array $coords * @param array $options * @return \Imagine\Image\ManipulatorInterface */ private function crop($file, array $coords, array $options) { if (isset($options['width']) && !isset($options['height'])) { $width = $options['width']; $height = $options['width'] * $coords['h'] / $coords['w']; } elseif (!isset($options['width']) && isset($options['height'])) { $width = $options['height'] * $coords['w'] / $coords['h']; $height = $options['height']; } elseif (isset($options['width']) && isset($options['height'])) { $width = $options['width']; $height = $options['height']; } else { $width = $coords['w']; $height = $coords['h']; } return Image::crop($file->tempName, $coords['w'], $coords['h'], [$coords['x'], $coords['y']])->resize(new Box($width, $height)); }
function createPoster($imageName) { $newWidth = 1980; $newHeight = 562; $mime = getimagesize($imageName); if ($mime['mime'] == 'image/png') { $src_img = imagecreatefrompng($imageName); } if ($mime['mime'] == 'image/jpg') { $src_img = imagecreatefromjpeg($imageName); } if ($mime['mime'] == 'image/jpeg') { $src_img = imagecreatefromjpeg($imageName); } if ($mime['mime'] == 'image/pjpeg') { $src_img = imagecreatefromjpeg($imageName); } $old_x = imageSX($src_img); $old_y = imageSY($src_img); if ($old_x > $old_y) { $thumb_w = $newWidth; $thumb_h = $old_y / $old_x * $newWidth; } if ($old_x < $old_y) { $thumb_w = $old_x / $old_y * $newHeight; $thumb_h = $newHeight; } if ($old_x == $old_y) { $thumb_w = $newWidth; $thumb_h = $newHeight; } $dst_img = ImageCreateTrueColor($thumb_w, $thumb_h); imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y); if ($mime['mime'] == 'image/png') { $result = imagepng($dst_img, $imageName, 8); } if ($mime['mime'] == 'image/jpg') { $result = imagejpeg($dst_img, $imageName, 80); } if ($mime['mime'] == 'image/jpeg') { $result = imagejpeg($dst_img, $imageName, 80); } if ($mime['mime'] == 'image/pjpeg') { $result = imagejpeg($dst_img, $imageName, 80); } imagedestroy($dst_img); imagedestroy($src_img); if ($thumb_w != $newWidth) { Image::crop($imageName, $newWidth, $newHeight, [($thumb_w - $newWidth) / 2, 0])->save($imageName, ['quality' => 80]); } if ($thumb_h != $newHeight) { Image::crop($imageName, $newWidth, $newHeight, [0, ($thumb_h - $newHeight) / 2])->save($imageName, ['quality' => 80]); } }
/** * 头像图片处理 * * @param string $fileName 待处理文件名(包括完整的路径) * @param string $extName 图片扩展名 * - 图片扩展名暂时支持jpeg/jpg/png/gif * @return boolean|string */ protected function process($fileName, $extName, $options) { $tmpFileName = time() . mt_rand(10000, 99999) . '.' . $extName; $tmpFile = $this->tmpPath . $tmpFileName; $img = Image::getImagine()->open(Yii::getAlias($fileName)); $size = ['width' => $img->getSize()->getWidth(), 'height' => $img->getSize()->getHeight()]; // 提供默认参数 $defPointer = [0, 0]; $defSize = $size['width'] > $size['height'] ? $size['height'] : $size['width']; if (!$options) { $options = ['pointer' => $defPointer, 'size' => $defSize]; } else { if (!isset($options['pointer'])) { $options['pointer'] = $defPointer; } if (!isset($options['size'])) { $options['size'] = $defSize; } $options['pointer'] = array_map('intval', $options['pointer']); $remSize = ['width' => $size['width'] - $options['pointer'][0], 'height' => $size['height'] - $options['pointer'][1]]; $refSize = $remSize['width'] > $remSize['height'] ? $remSize['height'] : $remSize['width']; if ($refSize < $options['size']) { $options['size'] = $refSize; } } try { // XXX: 两个操作是否可以合并为一个 Image::crop($fileName, $options['size'], $options['size'], $options['pointer'])->save(Yii::getAlias($tmpFile), ['quality' => self::IMAGE_QUALITY]); Image::thumbnail($tmpFile, self::AVATAR_SIZE, self::AVATAR_SIZE)->save(Yii::getAlias($tmpFile), ['quality' => self::IMAGE_QUALITY]); } catch (\Exception $e) { return false; } return $tmpFileName; }
/** * action UploadFile */ public function actionUploadFile() { $avatar = new Avatar(); $avatar->upload('avatar'); exit; $file = UploadedFile::getInstanceByName('myfile'); /* Image::thumbnail($file->tempName, 120, 120) ->save(Yii::getAlias('/tmp/test.jpg'), ['quality' => 80]); */ Image::crop($file->tempName, 100, 100, [100, 100])->save(Yii::getAlias('/tmp/test2.jpg'), ['quality' => 80]); echo 'good'; exit; /* $oss = new Oss(); $file = '/tmp/1455812025.jpg'; $obj = date('Ym/') . 'test.jpg'; $result = $oss->upload_by_file('cyj-i-test', $obj, $file); var_dump($result); */ }