/** * 保存图像 * @param string $imgname 图像保存名称 * @param string $type 图像类型 * @param boolean $interlace 是否对JPEG类型图像设置隔行扫描 * @throws \Exception */ public function save($imgname, $type = NULL, $interlace = true) { if (empty($this->img)) { throw new \Exception(_('No image resources can be saved')); } //设置图片类型 if (is_null($type)) { $type = $this->info['type']; } else { $type = strtolower($type); $this->img->setImageFormat($type); } //JPEG图像设置隔行扫描 if ('jpeg' == $type || 'jpg' == $type) { $this->img->setImageInterlaceScheme(1); } //去除图像配置信息 $this->img->stripImage(); //保存图像 $imgname = realpath(dirname($imgname)) . '/' . basename($imgname); //强制绝对路径 if ('gif' == $type) { $this->img->writeImages($imgname, true); } else { $this->img->writeImage($imgname); } }
public function save($file, $gray = false, $quality = 100) { if ($gray) { $this->gray(); } $res = $this->image->writeImages($file, true); $this->image->clear(); $this->image->destroy(); return $res; }
/** * アバター自動生成処理 * * @param Model $model ビヘイビア呼び出し元モデル * @param array $user ユーザデータ配列 * @return mixed On success Model::$data, false on failure * @throws InternalErrorException */ public function createAvatarAutomatically(Model $model, $user) { //imagickdraw オブジェクトを作成します $draw = new ImagickDraw(); //文字色のセット $draw->setfillcolor('white'); //フォントサイズを 160 に設定します $draw->setFontSize(140); //テキストを追加します $draw->setFont(CakePlugin::path($model->plugin) . 'webroot' . DS . 'fonts' . DS . 'ipaexg.ttf'); $draw->annotation(19, 143, mb_substr(mb_convert_kana($user['User']['handlename'], 'KVA'), 0, 1)); //新しいキャンバスオブジェクトを作成する $canvas = new Imagick(); //ランダムで背景色を指定する $red1 = strtolower(dechex(mt_rand(3, 12))); $red2 = strtolower(dechex(mt_rand(0, 15))); $green1 = strtolower(dechex(mt_rand(3, 12))); $green2 = strtolower(dechex(mt_rand(0, 15))); $blue1 = strtolower(dechex(mt_rand(3, 12))); $blue2 = strtolower(dechex(mt_rand(0, 15))); $canvas->newImage(179, 179, '#' . $red1 . $red2 . $green1 . $green2 . $blue1 . $blue2); //ImagickDraw をキャンバス上に描画します $canvas->drawImage($draw); //フォーマットを PNG に設定します $canvas->setImageFormat('png'); App::uses('TemporaryFolder', 'Files.Utility'); $folder = new TemporaryFolder(); $filePath = $folder->path . DS . Security::hash($user['User']['handlename'], 'md5') . '.png'; $canvas->writeImages($filePath, true); return $filePath; }
/** * {@inheritdoc} * * @return ImageInterface */ public function save($path = null, array $options = array()) { $path = null === $path ? $this->imagick->getImageFilename() : $path; if (null === $path) { throw new RuntimeException('You can omit save path only if image has been open from a file'); } try { $this->prepareOutput($options, $path); /** BEGIN CORE HACK */ // If a specific PNG format is requested, set it if (isset($options['png_format'])) { // Unless it's PNG8. Then we attempt to force Imagick to save it // as PNG, that is palette-based with transparency if ($options['png_format'] == 'png8') { $this->imagick->quantizeImage(255, \Imagick::COLORSPACE_YUV, 8, false, false); } else { $path = (isset($options['png_format']) ? $options['png_format'] . ':' : '') . $path; } } /** END CORE HACK */ $this->imagick->writeImages($path, true); } catch (\ImagickException $e) { throw new RuntimeException('Save operation failed', $e->getCode(), $e); } return $this; }
private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4, $format = "png", $quality = 85, $filename = FALSE, $save = TRUE, $print = false) { $imgH = count($frame); $imgW = strlen($frame[0]); $col[0] = new \ImagickPixel("white"); $col[1] = new \ImagickPixel("black"); $image = new \Imagick(); $image->newImage($imgW, $imgH, $col[0]); $image->setCompressionQuality($quality); $image->setImageFormat($format); $draw = new \ImagickDraw(); $draw->setFillColor($col[1]); for ($y = 0; $y < $imgH; $y++) { for ($x = 0; $x < $imgW; $x++) { if ($frame[$y][$x] == '1') { $draw->point($x, $y); } } } $image->drawImage($draw); $image->borderImage($col[0], $outerFrame, $outerFrame); $image->scaleImage(($imgW + 2 * $outerFrame) * $pixelPerPoint, 0); if ($save) { if ($filename === false) { throw new Exception("QR Code filename can't be empty"); } $image->writeImages($filename, true); } if ($print) { Header("Content-type: image/" . $format); echo $image; } }
/** * Outputs the image. * * @see XenForo_Image_Abstract::output() */ public function output($outputType, $outputFile = null, $quality = 85) { $this->_image->stripImage(); // NULL means output directly switch ($outputType) { case IMAGETYPE_GIF: if (is_callable(array($this->_image, 'optimizeimagelayers'))) { $this->_image->optimizeimagelayers(); } $success = $this->_image->setImageFormat('gif'); break; case IMAGETYPE_JPEG: $success = $this->_image->setImageFormat('jpeg') && $this->_image->setImageCompression(Imagick::COMPRESSION_JPEG) && $this->_image->setImageCompressionQuality($quality); break; case IMAGETYPE_PNG: $success = $this->_image->setImageFormat('png'); break; default: throw new XenForo_Exception('Invalid output type given. Expects IMAGETYPE_XXX constant.'); } try { if ($success) { if (!$outputFile) { echo $this->_image->getImagesBlob(); } else { $success = $this->_image->writeImages($outputFile, true); } } } catch (ImagickException $e) { return false; } return $success; }
/** * {@inheritdoc} */ public function save($path, array $options = array()) { try { $this->prepareOutput($options); $this->imagick->writeImages($path, true); } catch (\ImagickException $e) { throw new RuntimeException('Save operation failed', $e->getCode(), $e); } return $this; }
/** * Write a rendered PDF to the cache. * * @param $filePath * @param $cacheLocation */ protected function processFileToImageCache($filePath, $cacheLocation) { if (!is_dir($cacheLocation)) { mkdir($cacheLocation); } $imagick = new \Imagick(); $imagick->setResolution(150, 150); $imagick->readImage($filePath); $imagick->writeImages($cacheLocation . '/rendered.jpg', true); }
/** * Функция создания квадратного изображения с кадрированием. * @param string $sourceFile - путь до исходного файла * @param string $destinationFile - путь файла, в который сохраняется результат * @param integer $width * @param integer $height * @return */ function resizeImagick($sourceFile, $destinationFile, $width, $height, $resultType = 'gif') { $info = getimagesize($sourceFile); $destinationFile = $destinationFile; if (false === in_array($info[2], array(IMAGETYPE_JPEG, IMAGETYPE_GIF, IMAGETYPE_PNG))) { return false; } $originalWidth = $info[0]; $originalHeight = $info[1]; $ratio_orig = $originalWidth / $originalHeight; if ($width / $height > $ratio_orig) { $width = round($height * $ratio_orig); } else { $height = round($width / $ratio_orig); } if ($originalWidth < $width) { $height = $originalHeight; $width = $originalWidth; } $newWidth = $width; $newHeight = $height; $biggestSideSize = max($newWidth, $newHeight); # создаём новый пустой объект $newFileObj = new \Imagick(); # оригинальное изображение $im = new \Imagick($sourceFile); switch ($info[2]) { case IMAGETYPE_GIF: $im->setFormat("gif"); foreach ($im as $animation) { $animation->thumbnailImage($newWidth, $newHeight); //Выполняется resize до 200 пикселей поширине и сколько получится по высоте (с соблюдением пропорций конечно) $animation->setImagePage($animation->getImageWidth(), $animation->getImageHeight(), 0, 0); } $im->writeImages($destinationFile, true); return image_type_to_extension($info[2], false); break; case IMAGETYPE_PNG: $im = $im->coalesceImages(); $im->setFormat("gif"); $im->thumbnailImage($newWidth, $newHeight); $im->writeImages($destinationFile, true); return image_type_to_extension($info[2], false); break; case IMAGETYPE_JPEG: $im = $im->coalesceImages(); $im->setFormat("gif"); $im->thumbnailImage($newWidth, $newHeight); $im->writeImages($destinationFile, true); return image_type_to_extension($info[2], false); break; default: die($info[2] . 'd'); } }
/** * {@inheritdoc} * * @return ImageInterface */ public function save($path = null, array $options = array()) { $path = null === $path ? $this->imagick->getImageFilename() : $path; if (null === $path) { throw new RuntimeException('You can omit save path only if image has been open from a file'); } try { $this->prepareOutput($options, $path); $this->imagick->writeImages($path, true); } catch (\ImagickException $e) { throw new RuntimeException('Save operation failed', $e->getCode(), $e); } return $this; }
/** * Processes an image. * * @param \Imagick $inputImage * @return \Imagick The processed image. */ public function processImage(\Imagick $inputImage) { $totalFrames = 0; $uniqueFrameDelays = []; // If the image isn't animated, we don't have to do anything. if ($inputImage->getIteratorIndex() < 2) { return $inputImage; } $imageCopy = $inputImage->coalesceImages(); // Count frames, and build a set of unique frame delay amounts. /** @var \Imagick $item */ foreach ($imageCopy as $item) { $totalFrames++; $delay = $item->getImageDelay(); if (!isset($uniqueFrameDelays[$delay])) { $uniqueFrameDelays[$delay] = 0; } $uniqueFrameDelays[$delay]++; } // If all the frames are the same length, we don't need to do anything. if (1 === count($uniqueFrameDelays)) { return $inputImage; } // To re-time the animation, we'll need to find the least common // multiple of all the frame delays. $frameDelays = array_keys($uniqueFrameDelays); $newDelay = max(min($frameDelays), gcf_array($frameDelays)); $inputImage = $inputImage->coalesceImages(); $outputImage = new \Imagick(); var_dump(["Input delay", $inputImage->getImageDelay()]); /** @var \Imagick $frame */ foreach ($inputImage as $frame) { $outputFrame = clone $frame->getImage(); $frameCount = floor($outputFrame->getImageDelay() / $newDelay); $outputFrame->setImageDelay($newDelay); for ($i = 0; $i < $frameCount; $i++) { $outputImage->addImage($outputFrame); } } // $outputImage = $outputImage->deconstructImages(); $outputImage->setImageFormat('gif'); foreach ($outputImage as $frame) { var_dump($frame->getImageDelay()); } var_dump($inputImage->getImageLength()); var_dump($outputImage->getImageLength()); $outputImage->writeImages("output.gif", true); return $outputImage; }
protected function _save($file, $quality) { $extension = pathinfo($file, PATHINFO_EXTENSION); $type = $this->_save_function($extension, $quality); $this->im->setImageCompressionQuality($quality); if ($this->im->getNumberImages() > 1 && $extension == "gif") { $res = $this->im->writeImages($file, true); } else { $res = $this->im->writeImage($file); } if ($res) { $this->type = $type; $this->mime = image_type_to_mime_type($type); return true; } return false; }
/** * {@inheritdoc} * * @return ImageInterface */ public function save($path = null, array $options = array()) { $path = null === $path ? $this->imagick->getImageFilename() : $path; if (null === $path) { throw new RuntimeException('You can omit save path only if image has been open from a file'); } try { $this->prepareOutput($options, $path); /** BEGIN CORE HACK */ // If a specific PNG format is requested, set it $path = (isset($options['png_format']) ? $options['png_format'] . ':' : '') . $path; /** END CORE HACK */ $this->imagick->writeImages($path, true); } catch (\ImagickException $e) { throw new RuntimeException('Save operation failed', $e->getCode(), $e); } return $this; }
$mask = new Imagick($baseUri . 'mask.png'); $overlay = new Imagick($baseUri . 'overlay.png'); add_mask($im, $mask); add_overlay($im, $overlay); $mask->destroy(); $overlay->destroy(); $combined->addImage($im); $im->destroy(); } #$combined->resetIterator(); #$combined = $combined->appendImages(true); #$combined->setPage(595,842,0,0); $combined->setImageFormat('pdf'); #$fp = fopen('/home/gujc/Downloads/test.pdf','wb'); #$combined->writeImagesFile($fp); $combined->writeImages($baseUri . 'test.pdf', true); #$combined->destroy(); $reload = new Imagick($baseUri . 'test.pdf'); #$type=$combined->getFormat(); header('Content-type: pdf'); #header('Content-Disposition: attachment;filename="test.pdf"'); echo $reload->getImagesBlob(); function add_text($image, $text, $x = 0, $y = 0, $angle = 0, $style = array()) { $draw = new ImagickDraw(); if (isset($style['font'])) { $draw->setFont($style['font']); } if (isset($style['font_size'])) { $draw->setFontSize($style['font_size']); }
// imagefilter($bm, IMG_FILTER_GRAYSCALE); // imagecolortransparent($bm, $white); imagepng(transparent($bm, $new_width, $new_height), $imgdir); imagedestroy($bm); } else { if ($ext === 'eps') { $im = new Imagick(); $im->setResolution(100, 100); $im->readImage($imgdir); $im->setImageFormat("png"); $extln = strlen($ext); $dir = substr($imgdir, 0, strlen($imgdir) - $extln); $imgdir = $dir . "png"; // echo $imgdir; // die(); $im->writeImages($imgdir, true); $bm = imagecreatefrompng($imgdir); list($width, $height) = getimagesize($imgdir); $new_width = $width; $new_height = $height; // $white = imagecolorallocate($bm, 255, 255, 255); // imagefilter($bm, IMG_FILTER_GRAYSCALE); // imagecolortransparent($bm, $white); imagepng(transparent($bm, $new_width, $new_height), $imgdir); imagedestroy($bm); } } } } } }
<?php $combined = null; $images = ['../../../imagick/images/Biter_500.jpg', '../../../imagick/images/Source1.png']; foreach ($images as $image) { /** @var $combined \Imagick */ if ($combined == null) { $combined = new Imagick(realpath($image)); } else { $card = new Imagick(realpath($image)); //get single card $combined->addImage($card); } } $combined->setImageFormat("pdf"); $combined->writeImages('./card.pdf', true);
/** * Outputs an image resource as a given type * * @param Imagick $im * @param string $type * @param string $filename * @param int $qual * @return bool */ function zp_imageOutput($im, $type, $filename = NULL, $qual = 75) { $interlace = getOption('image_interlace'); $qual = max(min($qual, 100), 0); $im->setImageFormat($type); switch ($type) { case 'gif': $im->setImageCompression(Imagick::COMPRESSION_LZW); $im->setImageCompressionQuality($qual); if ($interlace) { $im->setInterlaceScheme(Imagick::INTERLACE_GIF); } break; case 'jpeg': case 'jpg': $im->setImageCompression(Imagick::COMPRESSION_JPEG); $im->setImageCompressionQuality($qual); if ($interlace) { $im->setInterlaceScheme(Imagick::INTERLACE_JPEG); } break; case 'png': $im->setImageCompression(Imagick::COMPRESSION_ZIP); $im->setImageCompressionQuality($qual); if ($interlace) { $im->setInterlaceScheme(Imagick::INTERLACE_PNG); } break; } $im->optimizeImageLayers(); if ($filename == NULL) { header('Content-Type: image/' . $type); return print $im->getImagesBlob(); } return $im->writeImages(imgSrcURI($filename), true); }
print "</pre>"; $s3 = new Aws\S3\S3Client(['version' => 'latest', 'region' => 'us-east-1']); $bucket = uniqid("php-jgl-mpfinal", false); # Create bucket for both images $result = $s3->createBucket(['ACL' => 'public-read', 'Bucket' => $bucket]); $s3->waitUntil('BucketExists', array('Bucket' => $bucket)); $result = $s3->putObject(['ACL' => 'public-read', 'Bucket' => $bucket, 'Key' => "Hello" . $uploadfile, 'ContentType' => $_FILES['userfile']['tmp_name'], 'Body' => fopen($uploadfile, 'r+')]); $url = $result['ObjectURL']; echo $url; //Get original image from s3 and save it locally $result = $s3->getObject(array('Bucket' => $bucket, 'Key' => "Hello" . $uploadfile, 'ContentType' => $_FILES['userfile']['tmp_name'], 'SaveAs' => 'result/s3result.jpg')); //Make the original image into a thumbnail $image = new Imagick(glob('result/s3result.jpg')); $image->thumbnailImage(100, 0); $image->setImageFormat("jpg"); $image->writeImages('imagesResult/s3rendered.jpg', true); // Upload rendered image to the same bucket $resultrendered = $s3->putObject(['ACL' => 'public-read', 'Bucket' => $bucket, 'Key' => "Hello" . $uploadfile . " rendered", 'SourceFile' => "imagesResult/s3rendered.jpg", 'ContentType' => $_FILES['userfile']['tmp_name'], 'Body' => fopen("imagesResult/s3rendered.jpg", 'r+')]); //Eliminate the variable s3rendered locally unlink('imagesResult/s3rendered.jpg'); $urlren = $resultrendered['ObjectURL']; echo $urlren; //Put a expiration date to the bucket $expiration = $s3->putBucketLifecycleConfiguration(['Bucket' => $bucket, 'LifecycleConfiguration' => ['Rules' => [['Expiration' => ['Date' => '2016-01-01'], 'Prefix' => ' ', 'Status' => 'Enabled']]]]); //Connect to the database $rds = new Aws\Rds\RdsClient(['version' => 'latest', 'region' => 'us-east-1']); $result = $rds->describeDBInstances(['DBInstanceIdentifier' => 'mp1-jgl']); $endpoint = $result['DBInstances'][0]['Endpoint']['Address']; print "============\n" . $endpoint . "================"; # Database connection $link = mysqli_connect($endpoint, "controller", "letmein888", "customerrecords", 3306) or die("Error " . mysqli_error($link));
/** * * @param Oops_File $source * @param unknown_type $Scene * return Oops_File_Temporary */ public function make($source, $scene = null) { // 1. Collect source stats if (!$source instanceof Oops_Image_File) { require_once 'Oops/Image/File.php'; $source = new Oops_Image_File($source); } // $source object contains image's width, height and orientation // 2. Get scene specification require_once 'Oops/Image/Preview/Scene.php'; $sceneObject = Oops_Image_Preview_Scene::getInstance($scene); $rotate = $sceneObject->rotate; // 3. Now calculate target image dimensions, rotate angle, etc. // 3.1. First calculate rotation switch ($source->orient) { case 8: $rotate += 90; case 3: $rotate += 90; case 6: $rotate += 90; $rotate = $rotate % 360; } // 3.2. Calculate target image dimensions $sourceWidth = $source->width; $sourceHeight = $source->height; if ($rotate == 90 || $rotate == 270) { $tmp = $sourceWidth; $sourceWidth = $sourceHeight; $sourceHeight = $tmp; } $resizeCoeffX = $this->_config->width / $sourceWidth; $resizeCoeffY = $this->_config->height / $sourceHeight; if (!$this->_config->enlarge) { if ($resizeCoeffX > 1 || $resizeCoeffX <= 0) { $resizeCoeffX = 1; } if ($resizeCoeffY > 1 || $resizeCoeffY <= 0) { $resizeCoeffY = 1; } } if ($this->_config->crop) { // Fit side with maximum resized rate and crop larger side $resizeCoeff = max($resizeCoeffX, $resizeCoeffY); } else { $resizeCoeff = min($resizeCoeffX, $resizeCoeffY); } $resizeWidth = round($resizeCoeff * $sourceWidth); $resizeHeight = round($resizeCoeff * $sourceHeight); // Now we have instructions for source modifications - rotate it, resize it // 3.3 Calculate preview instructions - crop it, fill it, etc $previewWidth = $resizeWidth; $previewHeight = $resizeHeight; $crop = false; if ($this->_config->crop) { if ($resizeWidth > $this->_config->width) { $previewWidth = $this->_config->width; $crop = true; } if ($resizeHeight > $this->_config->height) { $previewHeight = $this->_config->height; $crop = true; } } $fillColor = null; $fill = false; if ($this->_config->fill) { $previewWidth = $this->_config->width; $previewHeight = $this->_config->height; if ($resizeWidth < $previewWidth || $resizeHeight < $previewHeight) { $fillColor = $this->_config->fill; $fill = true; } } $previewPositionX = ($previewWidth - $resizeWidth) / 2; $previewPositionY = ($previewHeight - $resizeHeight) / 2; /* * Now we have instructions: * rotate angle * resize dimensions * whenever to crop * whenever to fill and fill color * And result image width and height */ // Read source image to new Imagick object $mgkSource = new Imagick(); $mgkSource->readImage($source->filename); $framesCount = $mgkSource->getNumberImages(); if (strlen($this->_config->maxFrames)) { $framesCount = min($framesCount, $this->_config->maxFrames); } $backGroundPixel = is_null($fillColor) ? new ImagickPixel() : new ImagickPixel($fillColor); if ($framesCount > 1) { $mgkPreview = $mgkSource->coalesceImages(); if ($rotate) { $mgkPreview->rotateimage($backGroundPixel, $rotate); } foreach ($mgkPreview as $frame) { $frame->thumbnailImage($resizeWidth, $resizeHeight); $frame->setImagePage($previewWidth, $previewWidth, $previewPositionX, $previewPositionY); } $mgkPreview->cropImage($previewWidth, $previewHeight, 0, 0); } else { $mgkSource->resizeImage($resizeWidth, $resizeHeight, Imagick::FILTER_LANCZOS, 1); $mgkPreview = new Imagick(); $mgkPreview->newImage($previewWidth, $previewHeight, $backGroundPixel); $mgkPreview->compositeImage($mgkSource, Imagick::COMPOSITE_OVER, $previewPositionX, $previewPositionY); } $mgkPreview->stripImage(); $previewFile = new Oops_File_Temporary(); $mgkPreview->setImageFormat($mgkSource->getImageFormat()); $mgkPreview->setCompressionQuality($mgkSource->getCompressionQuality()); $mgkPreview->writeImages($previewFile->filename, true); return $previewFile; }
public function joinArchiveContents($pa_files, $pa_options = array()) { if (!is_array($pa_files)) { return false; } $vs_archive_original = tempnam(caGetTempDirPath(), "caArchiveOriginal"); @rename($vs_archive_original, $vs_archive_original . ".tif"); $vs_archive_original = $vs_archive_original . ".tif"; $vo_orig = new Imagick(); foreach ($pa_files as $vs_file) { if (file_exists($vs_file)) { $vo_imagick = new Imagick(); if ($vo_imagick->readImage($vs_file)) { $vo_orig->addImage($vo_imagick); } } } if ($vo_orig->getNumberImages() > 0) { if ($vo_orig->writeImages($vs_archive_original, true)) { return $vs_archive_original; } } return false; }
print "</pre>"; $s3 = new Aws\S3\S3Client(['version' => 'latest', 'region' => 'us-east-1']); $bucket = uniqid("php-ars-test-bucket-", false); # AWS PHP SDK version 3 create bucket $result = $s3->createBucket(['ACL' => 'public-read', 'Bucket' => $bucket]); $s3->waitUntil('BucketExists', array('Bucket' => $bucket)); # PHP version 3 $result = $s3->putObject(['ACL' => 'public-read', 'Bucket' => $bucket, 'Key' => "Hello" . $uploadfile, 'ContentType' => $_FILES['userfile']['tmp_name'], 'Body' => fopen($uploadfile, 'r+')]); $url = $result['ObjectURL']; echo $url; $result = $s3->getObject(array('Bucket' => $bucket, 'Key' => "Hello" . $uploadfile, 'ContentType' => $_FILES['userfile']['tmp_name'], 'SaveAs' => '/tmp/originalimage.jpg')); $image = new Imagick(glob('/tmp/originalimage.jpg')); $image->oilPaintImage(2); //Oilpaint image $image->setImageFormat("jpg"); $image->writeImages('/tmp/modifiedimage.jpg', true); $modifiedbucket = uniqid("modified-image-", false); $result = $s3->createBucket(['ACL' => 'public-read', 'Bucket' => $modifiedbucket]); $resultrendered = $s3->putObject(['ACL' => 'public-read', 'Bucket' => $modifiedbucket, 'Key' => "Hello" . $uploadfile, 'SourceFile' => "/tmp/modifiedimage.jpg", 'ContentType' => $_FILES['userfile']['tmp_name'], 'Body' => fopen("/tmp/modifiedimage.jpg", 'r+')]); unlink('/tmp/modifiedimage.jpg'); $finishedurl = $resultrendered['ObjectURL']; echo $finishedurl; $expiration = $s3->putBucketLifecycleConfiguration(['Bucket' => $bucket, 'LifecycleConfiguration' => ['Rules' => [['Expiration' => ['Date' => '2015-12-25'], 'Prefix' => ' ', 'Status' => 'Enabled']]]]); $expiration = $s3->putBucketLifecycleConfiguration(['Bucket' => $modifiedbucket, 'LifecycleConfiguration' => ['Rules' => [['Expiration' => ['Date' => '2015-12-25'], 'Prefix' => ' ', 'Status' => 'Enabled']]]]); $rds = new Aws\Rds\RdsClient(['version' => 'latest', 'region' => 'us-east-1']); $result = $rds->describeDBInstances(['DBInstanceIdentifier' => 'mp1-db']); $endpoint = $result['DBInstances'][0]['Endpoint']['Address']; print "============\n" . $endpoint . "================"; print_r($result); # Database connection $link = mysqli_connect($endpoint, "controller", "letmein888", "customerrecords", 3306) or die("Error " . mysqli_error($link));
/** * Создание превью средствами imagick * @param $src_file исходный файл * @param $dst_file файл с результатом * @param max_w максимальная ширина * @param max_h максимальная высота * @return bool */ private function image_constrain_imagick($src_file, $dst_file, $max_w, $max_h, $watermark = null, $watermark_offet_x = 0, $watermark_offet_y = 0, $watermark_opacity = 1, $sharpen = 0.2) { $thumb = new Imagick(); // Читаем изображение if (!$thumb->readImage($src_file)) { return false; } // Размеры исходного изображения $src_w = $thumb->getImageWidth(); $src_h = $thumb->getImageHeight(); // Нужно ли обрезать? if (!$watermark && $src_w <= $max_w && $src_h <= $max_h) { // Нет - просто скопируем файл if (!copy($src_file, $dst_file)) { return false; } return true; } // Размеры превью при пропорциональном уменьшении list($dst_w, $dst_h) = $this->calc_contrain_size($src_w, $src_h, $max_w, $max_h); // Уменьшаем $thumb->thumbnailImage($dst_w, $dst_h); // Устанавливаем водяной знак if ($watermark && is_readable($watermark)) { $overlay = new Imagick($watermark); //$overlay->setImageOpacity(0.9); $overlay->setImageOpacity($watermark_opacity); $overlay_compose = $overlay->getImageCompose(); // Get the size of overlay $owidth = $overlay->getImageWidth(); $oheight = $overlay->getImageHeight(); $watermark_x = min(($dst_w - $owidth) * $watermark_offet_x / 100, $dst_w); $watermark_y = min(($dst_h - $oheight) * $watermark_offet_y / 100, $dst_h); } // Анимированные gif требуют прохода по фреймам foreach ($thumb as $frame) { // Уменьшаем $frame->thumbnailImage($dst_w, $dst_h); /* Set the virtual canvas to correct size */ $frame->setImagePage($dst_w, $dst_h, 0, 0); // Наводим резкость if ($sharpen > 0) { $thumb->adaptiveSharpenImage($sharpen, $sharpen); } if (isset($overlay) && is_object($overlay)) { $frame->compositeImage($overlay, $overlay_compose, $watermark_x, $watermark_y, imagick::COLOR_ALPHA); } } // Убираем комменты и т.п. из картинки $thumb->stripImage(); // $thumb->setImageCompressionQuality(100); // Записываем картинку if (!$thumb->writeImages($dst_file, true)) { return false; } // Уборка $thumb->destroy(); if (isset($overlay) && is_object($overlay)) { $overlay->destroy(); } return true; }
function ImagickResizeImage($srcFile, $destFile, $new_w, $new_h, $zhenshu = false) { if ($new_w <= 0 || $new_h <= 0 || !file_exists($srcFile)) { return false; } $src = new Imagick($srcFile); $image_format = strtolower($src->getImageFormat()); if ($image_format != 'jpeg' && $image_format != 'gif' && $image_format != 'png' && $image_format != 'jpg' && $image_format != 'bmp') { return false; } //如果是 jpg jpeg if ($image_format != 'gif') { $dest = $src; $dest->thumbnailImage($new_w, $new_h, true); $dest->writeImage($destFile); $dest->clear(); //gif需要以帧一帧的处理 } else { $dest = new Imagick(); $color_transparent = new ImagickPixel("transparent"); //透明色 $gif_i = 1; foreach ($src as $img) { $page = $img->getImagePage(); $tmp = new Imagick(); $tmp->newImage($page['width'], $page['height'], $color_transparent, 'gif'); $tmp->compositeImage($img, Imagick::COMPOSITE_OVER, $page['x'], $page['y']); $tmp->thumbnailImage($new_w, $new_h, true); $dest->addImage($tmp); $dest->setImagePage($tmp->getImageWidth(), $tmp->getImageHeight(), 0, 0); $dest->setImageDelay($img->getImageDelay()); $dest->setImageDispose($img->getImageDispose()); if ($zhenshu > 0) { if ($zhenshu <= $gif_i) { break; } $gif_i++; } } $dest->coalesceImages(); $dest->writeImages($destFile, true); $dest->clear(); } }
/** * Convert an image file into anoher format. * This need Imagick php extension. * * @param string $fileinput Input file name * @param string $ext Format of target file (It is also extension added to file if fileoutput is not provided). * @param string $fileoutput Output filename * @return int <0 if KO, >0 if OK */ function dol_convert_file($fileinput, $ext = 'png', $fileoutput = '') { global $langs; $image = new Imagick(); $ret = $image->readImage($fileinput); if ($ret) { $ret = $image->setImageFormat($ext); if ($ret) { if (empty($fileoutput)) { $fileoutput = $fileinput . "." . $ext; } $count = $image->getNumberImages(); $ret = $image->writeImages($fileoutput, true); if ($ret) { return $count; } else { return -3; } } else { return -2; } } else { return -1; } }
session_start(); include 'header.php'; $uploaddir = '/tmp/'; $uploadfile = $uploaddir . basename($_FILES['userfile']['name']); echo '<pre>'; if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) { echo "File is valid, and was successfully uploaded.\n"; } else { echo "Possible file upload attack!\n"; } print_r($_FILES); print "</pre>"; $testimagefilename = $uploadfile . '_magick'; $testimage = new Imagick($uploadfile); $testimage->thumbnailImage(100, 0); $testimage->writeImages($testimagefilename, false); require 'vendor/autoload.php'; require 'resources/library/db.php'; $s3 = new Aws\S3\S3Client(['version' => 'latest', 'region' => 'us-east-1']); use Aws\Sns\SnsClient; $sns = SnsClient::factory(array('version' => 'latest', 'region' => 'us-east-1')); $bucket = uniqid("php-pv-", false); $result = $s3->createBucket(['ACL' => 'public-read', 'Bucket' => $bucket]); $result = $s3->putObject(['ACL' => 'public-read', 'Bucket' => $bucket, 'Expires' => gmdate("D, d M Y H:i:s T", strtotime("+1 day")), 'Key' => $uploadfile, 'SourceFile' => $uploadfile]); $url = $result['ObjectURL']; $resultthumb = $s3->putObject(['ACL' => 'public-read', 'Bucket' => $bucket, 'Expires' => gmdate("D, d M Y H:i:s T", strtotime("+1 day")), 'Key' => $testimagefilename, 'SourceFile' => $testimagefilename]); $urlthumb = $resultthumb['ObjectURL']; $link = getDbConn(); if (!($stmt = $link->prepare("INSERT INTO items (id, email,phone,filename,s3rawurl,s3finishedurl,status,issubscribed) VALUES (NULL,?,?,?,?,?,?,?)"))) { echo "Prepare failed: (" . $link->errno . ") " . $link->error; }
public function make_block9($files, $save = null, $rawData = true) { if (!(count($files) >= 9)) { throw new ImageUtilityException('ImageImagickUtility 錯誤!', '參數錯誤,files count:' . count($files), '參數 files 數量一定要大於 9!'); } if (!$save) { throw new ImageUtilityException('ImageImagickUtility 錯誤!', '錯誤的儲存路徑,save' . $save, '請再次確認儲存路徑!'); } $newImage = new Imagick(); $newImage->newImage(266, 200, new ImagickPixel('white')); $newImage->setFormat(pathinfo($save, PATHINFO_EXTENSION)); $positions = array(array('left' => 2, 'top' => 2, 'width' => 130, 'height' => 130), array('left' => 134, 'top' => 2, 'width' => 64, 'height' => 64), array('left' => 200, 'top' => 2, 'width' => 64, 'height' => 64), array('left' => 134, 'top' => 68, 'width' => 64, 'height' => 64), array('left' => 200, 'top' => 68, 'width' => 64, 'height' => 64), array('left' => 2, 'top' => 134, 'width' => 64, 'height' => 64), array('left' => 68, 'top' => 134, 'width' => 64, 'height' => 64), array('left' => 134, 'top' => 134, 'width' => 64, 'height' => 64), array('left' => 200, 'top' => 134, 'width' => 64, 'height' => 64)); for ($i = 0; $i < 9; $i++) { $newImage->compositeImage(ImageUtility::create($files[$i])->getImage(), imagick::COMPOSITE_DEFAULT, $positions[$i]['left'], $positions[$i]['top']); } return $newImage->writeImages($save, $rawData); }
/** * Outputs an image resource as a given type * * @internal Imagick::INTERLACE_[GIF|JPEG|PNG] require Imagick compiled against ImageMagick 6.3.4+ * * @param Imagick $im * @param string $type * @param string $filename * @param int $qual * @throws ImagickException * @return bool */ function zp_imageOutput($im, $type, $filename = NULL, $qual = 75) { global $_imagemagick_version, $_imagick_newer_interlace; if (!isset($_imagick_newer_interlace)) { $_imagick_newer_interlace = version_compare($_imagemagick_version['versionNumber'], '6.3.4', '>='); } $interlace = getOption('image_interlace'); $qual = max(min($qual, 100), 0); $im->setImageFormat($type); switch ($type) { case 'gif': $im->setCompression(Imagick::COMPRESSION_LZW); $im->setCompressionQuality($qual); if ($interlace) { if ($_imagick_newer_interlace) { $im->setInterlaceScheme(Imagick::INTERLACE_GIF); } else { $im->setInterlaceScheme(Imagick::INTERLACE_LINE); } } break; case 'jpeg': case 'jpg': $im->setCompression(Imagick::COMPRESSION_JPEG); $im->setCompressionQuality($qual); if ($interlace) { if ($_imagick_newer_interlace) { $im->setInterlaceScheme(Imagick::INTERLACE_JPEG); } else { $im->setInterlaceScheme(Imagick::INTERLACE_LINE); } } break; case 'png': $im->setCompression(Imagick::COMPRESSION_ZIP); $im->setCompressionQuality($qual); if ($interlace) { if ($_imagick_newer_interlace) { $im->setInterlaceScheme(Imagick::INTERLACE_PNG); } else { $im->setInterlaceScheme(Imagick::INTERLACE_LINE); } } break; } try { $im->optimizeImageLayers(); } catch (ImagickException $e) { if (DEBUG_IMAGE) { debugLog('Caught ImagickException in zp_imageOutput(): ' . $e->getMessage()); } } if ($filename == NULL) { header('Content-Type: image/' . $type); return print $im->getImagesBlob(); } return $im->writeImages($filename, true); }
function helper_thumb_imagick($name, $ext, $filename, $new_w, $new_h) { #intiating the Imagick lib $im = new Imagick($name); #guess the right thumb height, weights list($thumb_w, $thumb_h) = scale_image_imagick($im->getImageWidth(), $im->getImageHeight(), $new_w, $new_h); #an exception for gif image #generating thumb with 10 frames only, big gif is a devil if ($ext == 'gif') { $i = 0; //$gif_new = new Imagick(); foreach ($im as $frame) { $frame->thumbnailImage($thumb_w, $thumb_h); $frame->setImagePage($thumb_w, $thumb_h, 0, 0); // $gif_new->addImage($frame->getImage()); if ($i >= 10) { # more than 10 frames, quit it break; } $i++; } $im->writeImages($filename, true); return; } #and other image extenion use one way $im->thumbnailImage($thumb_w, $thumb_h); #right it $im->writeImages($filename, false); return; }
private function _imageickThumb($url, $type, $new_w = 765, $new_h = 1000, $self = false, $trim = false) { $srcFile = $url; if ($self) { $destFile = $url; } else { $destFile = $type; } if ($new_w <= 0 || !file_exists($srcFile)) { return false; } $src = new Imagick($srcFile); $image_format = strtolower($src->getImageFormat()); if ($image_format != 'jpeg' && $image_format != 'gif' && $image_forumat != 'bmp' && $image_format != 'png' && $image_format != 'jpg') { return false; } $src_page = $src->getImagePage(); $src_w = $src_page['width']; $rate_w = $new_w / $src_w; if ($rate_w >= 1) { return false; } if ($new_h == -1) { $new_h = $rate_w * $src_page['height']; } //如果是 jpg jpeg gif if ($image_format != 'gif') { $dest = $src; if (!$trim) { $dest->thumbnailImage($new_w, $new_h, true); } else { $dest->cropthumbnailImage($new_w, $new_h); } $dest->writeImage($destFile); $dest->clear(); //gif需要以帧一帧的处理 } else { $dest = new Imagick(); $color_transparent = new ImagickPixel("transparent"); //透明色 foreach ($src as $img) { $page = $img->getImagePage(); if ($new_h == -1) { $new_h = $new_w / $page['width'] * $src_page['hight']; } $tmp = new Imagick(); $tmp->newImage($page['width'], $page['height'], $color_transparent, 'gif'); $tmp->compositeImage($img, Imagick::COMPOSITE_OVER, $page['x'], $page['y']); if (!$trim) { $tmp->thumbnailImage($new_w, $new_h, true); } else { $tmp->cropthumbnailImage($new_w, $new_h); } $dest->addImage($tmp); $dest->setImagePage($tmp->getImageWidth(), $tmp->getImageHeight(), 0, 0); $dest->setImageDelay($img->getImageDelay()); $dest->setImageDispose($img->getImageDispose()); } $dest->coalesceImages(); $dest->writeImages($destFile, true); $dest->clear(); } }
if ($ext === 'eps') { $im = imagecreatefromstring(base64_decode(transparent($imgdir, $imgtype))); imagepng($im, "/var/www/mch/env/html5_configurator/img/design/{$post['sessionid']}-{$date}-test_layer.png"); $tempimg_path = "/var/www/mch/env/html5_configurator/img/design/{$post['sessionid']}-{$date}-test_layer.png"; $imgdir = $tempimg_path; imagedestroy($im); $im = new Imagick(); $im->setResolution(100, 100); $im->readImage($imgdir); $im->setImageFormat("png"); $extln = strlen($ext); $dir = substr($imgdir, 0, strlen($imgdir) - $extln); $imgdir = $dir . "png"; // echo $imgdir; // die(); $im->writeImages($imgdir . "?" . $query, true); $im->destroy(); $im = imagecreatefrompng($imgdir); imagefilter($im, IMG_FILTER_COLORIZE, $red, $green, $blue); ob_start(); imagepng($im); $changed_file = base64_encode(ob_get_contents()); ob_end_clean(); imagepng($im, $imgdir . "?" . $query); $base64 = 'data:image/png' . ';base64,' . $changed_file; imagedestroy($im); echo $base64; // echo $imgtype; } } }