public function resizeImage($imagePath, $new_width, $new_height) { $fileName = pathinfo($imagePath, PATHINFO_FILENAME); $fullPath = pathinfo($imagePath, PATHINFO_DIRNAME) . "/" . $fileName . "_small.png"; if (file_exists($fullPath)) { return $fullPath; } $image = $this->openImage($imagePath); if ($image == false) { return null; } $width = imagesx($image); $height = imagesy($image); $imageResized = imagecreatetruecolor($width, $height); if ($imageResized == false) { return null; } $image = imagecreatetruecolor($width, $height); $imageResized = imagescale($image, $new_width, $new_heigh); touch($fullPath); $write = imagepng($imageResized, $fullPath); if (!$write) { imagedestroy($imageResized); return null; } imagedestroy($imageResized); return $fullPath; }
public function actionPhoto($id) { $model = $this->loadModel($id); $model->scenario = 'photo'; Yii::trace("FC.actionPhoto called", 'application.controllers.FamilyController'); if (Yii::app()->params['photoManip']) { if (isset($_POST['x1'])) { $x1 = $_POST['x1']; $y1 = $_POST['y1']; $width = $_POST['width']; $height = $_POST['height']; $pfile = $_POST['pfile']; $sdir = './images/uploaded/'; $size = getimagesize($sdir . $pfile); if ($size) { list($w, $h, $t) = $size; } else { Yii::trace("FR.actionPhoto crop call to getimagesize failed for image " . $sdir . $pfile . " returned {$size}", 'application.controllers.FamilyController'); } Yii::trace("FC.actionPhoto crop received {$x1}, {$y1}, {$width}, {$height}, {$w}, {$h}, {$t}", 'application.controllers.FamilyController'); switch ($t) { case 1: $img = imagecreatefromgif($sdir . $pfile); break; case 2: $img = imagecreatefromjpeg($sdir . $pfile); break; case 3: $img = imagecreatefrompng($sdir . $pfile); break; case IMAGETYPE_BMP: $img = ImageHelper::ImageCreateFromBMP($sdir . $pfile); break; case IMAGETYPE_WBMP: $img = imagecreatefromwbmp($sdir . $pfile); break; default: Yii::trace("FC.actionPhoto crop unknown image type {$t}", 'application.controllers.FamilyController'); } if (function_exists('imagecrop')) { # untested $cropped = imagecrop($img, array('x1' => $x1, 'y1' => $y1, 'width' => $width, 'height' => $height)); $scaled = imagescale($cropped, 400); } else { $h = $height * 400 / $width; $scaled = imagecreatetruecolor(400, $h); imagecopyresized($scaled, $img, 0, 0, $x1, $y1, 400, $h, $width, $height); } $dir = './images/families/'; $fname = preg_replace('/\\.[a-z]+$/i', '', $pfile); $fext = ".jpg"; if (file_exists($dir . $pfile)) { $fname .= "_01"; while (file_exists($dir . $fname . $fext)) { ++$fname; } } $dest = $dir . $fname . $fext; imagejpeg($scaled, $dest, 90); imagedestroy($scaled); imagedestroy($img); unlink($sdir . $pfile); $model->photo = $fname . $fext; $model->save(false); Yii::trace("FC.actionPhoto saved to {$pfile}", 'application.controllers.FamilyController'); $this->redirect(array('view', 'id' => $model->id)); return; } elseif (isset($_FILES['Families'])) { Yii::trace("FC.actionPhoto _FILES[Families] set", 'application.controllers.FamilyController'); $files = $_FILES['Families']; $filename = $files['name']['raw_photo']; if (isset($filename) and '' != $filename) { Yii::trace("FC.actionPhoto filename {$filename}", 'application.controllers.FamilyController'); $tmp_path = $files['tmp_name']['raw_photo']; if (isset($tmp_path) and '' != $tmp_path) { Yii::trace("FC.actionPhoto tmp_path {$tmp_path}", 'application.controllers.FamilyController'); $dir = "./images/uploaded/"; $dest = $dir . $filename; list($width, $height) = getimagesize($tmp_path); if ($width < 900) { $w = $width; $h = $height; $zoom = 1; } else { $w = 900; $h = $height * 900 / $width; $zoom = $w / $width; } $w = $width < 900 ? $width : 900; move_uploaded_file($tmp_path, $dest); $this->render('crop', array('model' => $model, 'pfile' => $filename, 'width' => $w, 'height' => $h, 'zoom' => $zoom)); return; } else { $errors = array(1 => "Size exceeds max_upload", 2 => "FORM_SIZE", 3 => "No tmp dir", 4 => "can't write", 5 => "error extension", 6 => "error partial"); $error = $errors[$files['error']['raw_photo']]; Yii::trace("FC.actionPhoto file error {$error}", 'application.controllers.FamilyController'); } } } } elseif (isset($_FILES['Families'])) { $files = $_FILES['Families']; $filename = $files['name']['photo']; if (isset($filename) and '' != $filename) { $tmp_path = $files['tmp_name']['photo']; if (isset($tmp_path) and '' != $tmp_path) { $dir = "./images/families/"; $fname = preg_replace('/\\.[a-z]+$/i', '', $filename); preg_match('/(\\.[a-z]+)$/i', $filename, $matches); $fext = $matches[0]; if (file_exists($dir . $filename)) { $fname .= "_01"; while (file_exists($dir . $fname . $fext)) { ++$fname; } } $dest = $dir . $fname . $fext; $model->photo = $fname . $fext; if ($model->save()) { move_uploaded_file($tmp_path, $dest); $this->redirect(array('view', 'id' => $model->id)); return; } } else { $model->addError('photo', $files['error']['photo']); } } } $this->render('photo', array('model' => $model)); }
<?php include dirname(__FILE__) . '/_init.php'; $im = imagecreatefromjpeg('images/mutzig.jpg'); $im1 = imagescale($im, 100, 100, IMAGE_EX_SCALE_PAD); imagejpeg($im1, 'output/scale-pad-1.jpg'); $im2 = imagescale($im, 1000, 1000, IMAGE_EX_SCALE_PAD); imagejpeg($im2, 'output/scale-pad-2.jpg');
/** * Resize the image to the given co-ordinates * + WIDTH 512 * + HEIGHT 512 * @param $image * @return bool */ private function resizeImage($image) { if (($newImage = imagescale($image, 512, 512)) != false) { $this->newImage = $newImage; return true; } return false; }
/** * resize file $source and save the resized image into $destination * * @param string $source file to resize * @param string $destination resized file * @throws ImageResizerException */ public function resize($source, $destination) { list($srcWidth, $srcHeight) = $this->retrieveSrcDimensions($source); list($dstWidth, $dstHeight) = $this->calculateDstDimensions($srcWidth, $srcHeight); $srcId = $this->getImageIdentifier($source); $dstId = @imagescale($srcId, $dstWidth, $dstHeight, IMG_BILINEAR_FIXED); @imageinterlace($dstId, $this->getOption(self::OPT_INTERLACE)); $this->save($dstId, $destination); @imagedestroy($dstId); }
public function handle(FileUpload $uploader, FileInfo $fileinfo) { // TODO Auto-generated method stub $filename = $fileinfo->getPath(); $realpath = $uploader->getFileBaseDir() . DIRECTORY_SEPARATOR . $filename; //resize the file list($o_width, $o_height, ) = getimagesize($realpath); list($des_width, $des_height) = $this->getDestSize(array($o_width, $o_height)); $destination = $this->getDestName($fileinfo, array($des_width, $des_height)); $full_destination = $uploader->getFileBaseDir() . DIRECTORY_SEPARATOR . $destination; $source = imagecreatefromstring(file_get_contents($realpath)); if (function_exists('imagescale')) { $dest = imagescale($source, $des_width, $des_height); if ($dest) { $result = true; } else { $result = false; } } else { $dest = imagecreatetruecolor($des_width, $des_height); $result = imagecopyresampled($dest, $source, 0, 0, 0, 0, $des_width, $des_height, $o_width, $o_height); } imagedestroy($source); if ($result) { switch (strtolower($fileinfo->getExtension())) { case 'jpg': case 'jpeg': default: $result = imagejpeg($dest, $full_destination); break; case 'png': $result = imagepng($dest, $full_destination); break; case 'gif': $result = imagegif($dest, $full_destination); break; case 'bmp': throw new Exception('不支持bmp文件'); break; } imagedestroy($dest); if ($result) { $info = new FileInfo($fileinfo->getName(), filesize($full_destination), $destination, $fileinfo->getType()); return $info; } return false; } return false; }
function scaleToHeight($in_fn, $out_fn, $height) { if (!file_exists($in_fn)) { throw new \Exception("file {$in_fn} does not exists"); } $im = imagecreatefromjpeg($in_fn); $ini_x_size = getimagesize($in_fn)[0]; $ini_y_size = getimagesize($in_fn)[1]; $new_y = $height; $new_x = $new_y * $ini_x_size / $ini_y_size; if (!($scaled_im = imagescale($im, $new_x, $new_y))) { throw new \Exception("Scaling operation failed"); } if (!imagejpeg($scaled_im, $out_fn, 100)) { throw new \Exception("write of scaled image to {$out_fn} failed"); } }
public function render() { $filename = ''; $path = ''; $width = 0; $height = 0; if ($this->request->input('path')) { $filename = basename($this->request->input('path')); } if ($this->request->input('path')) { $path = '/' . $this->request->input('path'); } if ($this->request->input('x')) { $width = $this->request->input('x'); } if ($this->request->input('y')) { $height = $this->request->input('y'); } $image = $path; $image_2 = '/images/cache/' . $width . 'x' . $height . '_' . $filename; $new_image = Storage::get($image); if (!Storage::directories(storage_path('app') . '/images/cache')) { Storage::makeDirectory('/images/cache'); } if ($width > 0) { if (!Storage::exists($image_2)) { switch (exif_imagetype(storage_path('app') . $image)) { case 2: $new_image = imagescale(imagecreatefromjpeg(storage_path('app') . $image), $width, $height, IMG_BICUBIC_FIXED); imagejpeg($new_image, storage_path('app') . $image_2); break; case 3: $new_image = imagescale(imagecreatefrompng(storage_path('app') . $image), $width, $height, IMG_BICUBIC_FIXED); imagepng($new_image, storage_path('app') . $image_2); break; default: break; } $new_image = Storage::get($image_2); } else { $new_image = Storage::get($image_2); } } return (new Response($new_image, 200))->header('Content-Type', 'image/png'); }
public function uploadImageAction(Request $request): Response { $image = $request->files->get('image'); $filename = sha1(uniqid(mt_rand(), true)) . time(); $filePath = $filename . '.' . $image->guessExtension(); if ('png' == $image->guessExtension()) { $imageSrc = imagecreatefrompng($image->getRealPath()); } else { $imageSrc = imagecreatefromjpeg($image->getRealPath()); } $imageScaled = imagescale($imageSrc, 800); imagejpeg($imageScaled, $this->uploadDir.'/temp/'.$filePath); $this->log->debug(sprintf('%s: image created %s',__CLASS__, $filePath)); return new JsonResponse(['image' => $filePath], 201); }
public function run($template) { //Remove the whole string as the first result array_shift($this->URLMatch); //Get the database $dbh = Engine::getDatabase(); //Get result ID $resultID = $this->URLMatch[0]; //Check if the result is in the array and return results $sql = "SELECT * FROM Results WHERE Result_ID IN (SELECT Result_ID FROM Result_History WHERE Result_ID= :result) LIMIT 1"; $stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY)); $stmt->execute(array(':result' => $resultID)); $result = $stmt->fetchObject('Result'); if ($result == false) { exit; } //There's no result to give an image for $result->Data = json_decode($result->Data, true); $data = $result->Data; $blueBackground = imagecreatefromstring(file_get_contents(__DIR__ . '/../public/images/share-background.png', "r")); $friends = array_keys($data['interaction']); $friend1 = imagecreatefromstring(file_get_contents(User::getAvatar($friends[0]))); //200,200 (width x height) $friend2 = imagecreatefromstring(file_get_contents(User::getAvatar($friends[1]))); $friend3 = imagecreatefromstring(file_get_contents(User::getAvatar($friends[2]))); $gaussian = array(array(1.0, 2.0, 1.0), array(2.0, 4.0, 2.0), array(1.0, 2.0, 1.0)); for ($i = 0; $i < 60; $i++) { imageconvolution($friend1, $gaussian, 16, 0); imageconvolution($friend2, $gaussian, 16, 0); imageconvolution($friend3, $gaussian, 16, 0); } $graph = imagecreatefromstring(file_get_contents(__DIR__ . '/../public/images/white-logo-transparent-medium.png', "r")); $foreground = imagecreatefromstring(file_get_contents(__DIR__ . '/../public/images/share-foreground.png', "r")); imagecopy($blueBackground, $friend1, -50, 25, 0, 0, imagesx($friend1), imagesy($friend1)); imagecopy($blueBackground, $friend2, 150, 25, 0, 0, imagesx($friend2), imagesy($friend2)); imagecopy($blueBackground, $friend3, 350, 25, 0, 0, imagesx($friend3), imagesy($friend3)); $graph = imagescale($graph, imagesx($friend1) * 2); imagecopy($blueBackground, $graph, 80, -20, 0, 0, imagesx($graph), imagesy($graph)); imagecopy($blueBackground, $foreground, 0, 0, 0, 0, imagesx($foreground), imagesy($foreground)); ob_clean(); ob_start(); header('Content-Type: image/png'); imagepng($blueBackground); }
public static function mergeImage($src_a, $src_b) { $a = $src_a; $b = $src_b; $a = imagecreatefromstring($a); $b = imagecreatefromstring($b); $b = imagescale($b, imagesx($a) / 4); Utils::imagecopymerge_alpha($a, $b, imagesx($a) / 2 - imagesx($b) / 2, imagesy($a) / 100 * 10, 0, 0, imagesx($b), imagesy($b), 100); imagesavealpha($a, true); // php u fuckng suck ob_start(); imagepng($a); $contents = ob_get_contents(); ob_end_clean(); // imagedestroy($a); imagedestroy($b); return $contents; }
protected function resize_image($image, $width, $height) { $ext = strtolower(pathinfo($image, PATHINFO_EXTENSION)); if (!preg_match('/(jpg|jpeg|png|gif)/', $ext)) { $src = imagecreatefromstring(file_get_contents($image)); unlink($image); $image = sprintf("%s/%s.png", pathinfo($image, PATHINFO_DIRNAME), pathinfo($image, PATHINFO_FILENAME)); imagepng($src, $image); imagedestroy($src); } list($oWidth, $oHeight) = getimagesize($image); if ($oWidth > $width || $oHeight > $height) { $ratio = min($width / $oWidth, $height / $oHeight); $src = imagecreatefromstring(file_get_contents($image)); $dst = imagescale($src, $oWidth * $ratio, $oHeight * $ratio, IMG_BICUBIC); call_user_func(preg_match('/jpeg|jpg/', $ext) ? 'imagejpeg' : (preg_match('/gif/', $ext) ? 'imagegif' : 'imagepng'), $dst, $image); imagedestroy($src); imagedestroy($dst); } return $image; }
/** * The method by which images are uploaded to our servers * * @throws \RuntimeException when the user did not have the authority to add an image * @throws \InvalidArgumentException when filetype is not supported * @throws \Exception when another error occurs **/ public function imageUpload() { if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); } if (empty($_SESSION["profile"]) === true) { throw new \RuntimeException("Please log in or sign up", 401); } if ($_SESSION["profile"]->getProfileId() !== $this->imageProfileId) { throw new \RuntimeException("We could not upload your image, as your account did not match the account the image would have been placed under. We didn't even think that was possible.", 401); } $maximumWidth = 2048; $maximumHeight = 2048; $validExts = ["jpeg", "jpg", "gif", "png"]; $validFormat = ["image/jpeg", "image/jpg", "image/gif", "image/png"]; $name = $_FILES["file"]["name"]; $tmp = explode(".", $name); $extension = strtolower(end($tmp)); $type = $_FILES["file"]["type"]; $imagePath = $_FILES["file"]["tmp_name"]; if (in_array($type, $validFormat) === false || in_array($extension, $validExts) === false) { throw new \InvalidArgumentException("File was not of correct type", 418); // tea earl grey hot } $identificationOfImage = $_SESSION["profile"]->getProfileEmail() . $this->imageId; $tempName = hash("ripemd160", $identificationOfImage) . "."; $imageSizes = getimagesize($imagePath); $widthRatio = $maximumWidth / $imageSizes[0]; $heightRatio = $maximumHeight / $imageSizes[1]; switch ($extension) { case "jpeg": $tempImage = imagecreatefromjpeg($imagePath); break; case "jpg": $tempImage = imagecreatefromjpeg($imagePath); break; case "gif": $tempImage = imagecreatefromgif($imagePath); break; case "png": $tempImage = imagecreatefrompng($imagePath); break; default: throw new \InvalidArgumentException("File was not of correct type", 418); break; } if (!($imageSizes[0] <= $maximumWidth && $imageSizes[1] <= $maximumHeight)) { if ($heightRatio * $imageSizes[0] < $maximumWidth) { $tempImage = imagescale($tempImage, $heightRatio * $imageSizes[0], $maximumHeight); } else { $tempImage = imagescale($tempImage, $maximumWidth, $widthRatio * $imageSizes[1]); } } if ($extension === "gif") { $tempName = $tempName . "gif"; $fileLocation = "/var/www/html/public_html/jpegery/content/" . $tempName; $savedImage = imagegif($tempImage, $fileLocation); $this->setImageType("image/gif"); } else { $tempName = $tempName . "jpeg"; $fileLocation = "/var/www/html/public_html/jpegery/content/" . $tempName; $savedImage = imagejpeg($tempImage, $fileLocation); $this->setImageType("image/jpeg"); } $this->setImageFileName($fileLocation); if ($savedImage === false) { throw new \Exception("Something went wrong in uploading your image.", 400); } }
define('MODE_A4R4G4B4', 'a4r4g4b4'); define('COMPRESSION_OFF', 'off'); $options = options(); list($width, $height, $type) = getimagesize($options->input); switch ($type) { case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($options->input); break; case IMAGETYPE_PNG: $image = imagecreatefrompng($options->input); break; default: error(sprintf("Unsupported file type '%s'", $options->input)); } $image = imagescale($image, $options->width, $options->height); $output = fopen($options->output, 'wb'); if (false === $output) { error(sprintf("Can't open output file '%s'", $options->output)); } // // Image's information // // 64-bytes image's name fwrite($output, pack('a63x', $options->name)); // 2-bytes BE width and height fwrite($output, pack('n', $options->width)); fwrite($output, pack('n', $options->height)); // 2-bytes color's mode and compression's mode switch ($options->mode) { case MODE_A4R4G4B4:
/** * @param int $width * @param int $height * * @return static */ public function resize($width, $height) { if (version_compare(PHP_VERSION, '5.5.0') < 0) { $image = imagecreatetruecolor($width, $height); imagealphablending($image, false); imagesavealpha($image, true); imagecopyresampled($image, $this->_image, 0, 0, 0, 0, $width, $height, $this->_width, $this->_height); } else { $image = imagescale($this->_image, $width, $height); } imagedestroy($this->_image); $this->_image = $image; $this->_width = imagesx($image); $this->_height = imagesy($image); return $this; }
function getIcon($spell, $url, $iconIndent) { global $cacheFolder; global $iconMap; global $iconType; global $spellsTextureFolder; global $spellsFolder; global $interpolationType; global $currentDurability; $cacheFile = $cacheFolder . '/' . urlencode($url); if (!file_exists($cacheFile)) { $iconFile = file_get_contents($url); file_put_contents($cacheFile, $iconFile); } $sourceImage = imagecreatefrompng($cacheFile); $icon = imagecreatetruecolor(8, 8); imagecopyresampled($icon, $sourceImage, 0, 0, 8, 8, 8, 8, 8, 8); $icon = imagescale($icon, 32, 32, $interpolationType); imagepng($icon, $spellsTextureFolder . '/' . $spell . '.png'); imagedestroy($sourceImage); imagedestroy($icon); $spellJson = <<<END { "parent" : "item/custom/icon", "textures": { "particle": "items/spells/{$spell}", "texture": "items/spells/{$spell}" } } END; file_put_contents($spellsFolder . '/' . $spell . '.json', $spellJson); $durability = $currentDurability + 1; $currentDurability++; $iconMap[$durability] = $spell; return $iconIndent . "icon: {$iconType}:{$durability}\n"; }
dl("gd.so"); $input_file = __DIR__ . '/' . TestSettings::INPUT_FILE; $output_file = __DIR__ . "/output/gd.jpg"; $timers = ['new' => 0, 'open' => 0, 'get_info' => 0, 'scale' => 0, 'rotate' => 0, 'paste' => 0, 'save' => 0]; for ($i = 0; $i < TestSettings::NUM_RUNS; $i++) { $time_open_start = microtime(true); $image1 = imagecreatefromjpeg($input_file); $timers['open'] += microtime(true) - $time_open_start; $time_get_info_start = microtime(true); $width = imagesx($image1); $height = imagesy($image1); $timers['get_info'] += microtime(true) - $time_get_info_start; $new_width = ceil($width / TestSettings::DOWNSCALE_FACTOR); $new_height = ceil($height / TestSettings::DOWNSCALE_FACTOR); $time_scale_start = microtime(true); $image2 = imagescale($image1, $new_width, $new_height); $timers['scale'] += microtime(true) - $time_scale_start; $gd_rotate_angle = 360 - TestSettings::ROTATE_ANGLE; $time_rotate_start = microtime(true); $white = imagecolorallocate($image2, 0xff, 0xff, 0xff); $image3 = imagerotate($image2, $gd_rotate_angle, $white); $timers['rotate'] += microtime(true) - $time_rotate_start; $time_new_start = microtime(true); $image4 = imagecreatetruecolor(TestSettings::OUTPUT_IMAGE_WIDTH, TestSettings::OUTPUT_IMAGE_HEIGHT); $white = imagecolorallocate($image4, 0xff, 0xff, 0xff); imagefill($image4, 0, 0, $white); $timers['new'] += microtime(true) - $time_new_start; $rotated_image_width = imagesx($image3); $rotated_image_height = imagesy($image3); $time_paste_start = microtime(true); imagecopymerge($image4, $image3, TestSettings::PASTE_X, TestSettings::PASTE_Y, 0, 0, $rotated_image_width, $rotated_image_height, 100);
<?php include dirname(__FILE__) . '/_init.php'; $im = imagecreatefromjpeg('images/mutzig.jpg'); $im1 = imagescale($im, 100, 100, IMAGE_EX_SCALE_FIT); imagejpeg($im1, 'output/scale-fit-1.jpg'); $im2 = imagescale($im, 1000, 1000, IMAGE_EX_SCALE_FIT); imagejpeg($im2, 'output/scale-fit-2.jpg');
/** * Cette fonction permet de redimensionner une image PNG OU JPG par rapport à une hauteur maximale et un ratio de cette hauteur en largeur, le tout sans deformations, avec un crop si necessaires * @param string $image : L'adresse de l'image à redimensionner * @param string $outfile : L'adresse de l'image de sortie * @param int $height : La hauteur à fixer * @param float $ratio : Le ratio à appliquer pour la width * @param int $quality : La qualité de l'image (0-9 pour png et 0-100 pour jpg), par défaut à null, donnera 9 pour png et 100 pour jpeg * @return boolean : true si la transformation a reussi, false sinon */ public static function resizeImageAndCropForHeightAndRatio($image, $outfile, $height, $ratio, $quality = null) { $mediaInfo = new finfo(FILEINFO_MIME_TYPE); $mediaMimeType = $mediaInfo->file($image); if ($mediaMimeType === false) { return false; } //On switch pour fixer la qualité et recuperer l'image switch ($mediaMimeType) { case 'image/jpeg': $quality = $quality === null ? 100 : $quality; $src_image = imagecreatefromjpeg($image); break; case 'image/png': $quality = $quality === null ? 9 : $quality; $src_image = imagecreatefrompng($image); break; default: return false; } $imageSize = getimagesize($image); $ratioWidthHeight = $imageSize[0] / $imageSize[1]; $newWidth = ceil($height * $ratio); $dst_x = 0; $dst_y = 0; $dst_w = $newWidth; $dst_h = $height; $dst_image = imagecreatetruecolor($newWidth, $height); //On assure la transparence des fichiers png if ($imageSize['mime'] == 'image/png') { $black = imagecolorallocate($dst_image, 0, 0, 0); imagecolortransparent($dst_image, $black); } //On choisi le comportement à adopter pour le redimensionnement //Si l'image de base est plus en largeur que voulu, on doit redimensionner la hauteur est recentrer en largeur if ($ratioWidthHeight > $ratio) { //On calcul la taille qu'aurait l'image originale si on la scaler sans recouper $originalNewWidth = ceil($ratioWidthHeight * $height); $widthReste = ceil(($originalNewWidth - $newWidth) / 2); $src_x = $widthReste; $src_y = 0; $src_w = $newWidth; $src_h = $height; $src_image = imagescale($src_image, $originalNewWidth); } else { $ratioHeightWidth = $imageSize[1] / $imageSize[0]; $originalNewHeight = ceil($height * $ratioHeightWidth); $heightReste = ceil(($originalNewHeight - $height) / 2); $src_x = 0; $src_y = 0; $src_w = $newWidth; $src_h = $height; $src_image = imagescale($src_image, $newWidth); } //On a toutes les infos necessaires, on va faire notre redimension if (!imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)) { return false; } //On ecrit l'image et on retourne le resultat de l'opération switch ($imageSize['mime']) { case 'image/jpeg': $result = imagejpeg($dst_image, $outfile, $quality); break; case 'image/png': $result = imagepng($dst_image, $outfile, $quality); break; default: return false; } return $result; }
<?php include dirname(__FILE__) . '/_init.php'; $im = imagecreatefromjpeg('images/mutzig.jpg'); $im1 = imagescale($im, 100, 100, IMAGE_EX_SCALE_CROP); imagejpeg($im1, 'output/scale-crop-1.jpg'); $im2 = imagescale($im, 1000, 1000, IMAGE_EX_SCALE_CROP); imagejpeg($im2, 'output/scale-crop-2.jpg');
public function make_image() { $this->theImage = imagecreatetruecolor($this->imageWidth, $this->imageHeight); //defines colors for the fonts and background $headerColor = imagecolorallocate($this->theImage, $this->header['fontColor']['red'], $this->header['fontColor']['green'], $this->header['fontColor']['blue']); $bodyColor = imagecolorallocate($this->theImage, $this->body['fontColor']['red'], $this->body['fontColor']['green'], $this->body['fontColor']['blue']); $footerColor = imagecolorallocate($this->theImage, $this->footer['fontColor']['red'], $this->footer['fontColor']['green'], $this->footer['fontColor']['blue']); $backgroundColor = imagecolorallocate($this->theImage, $this->backgroundColor['red'], $this->backgroundColor['green'], $this->backgroundColor['blue']); //fills the image with its background color imagefill($this->theImage, 0, 0, $backgroundColor); //inserts header and footer background images if they exist // only scales the header and footer image to fit the final image if it is // set to do so, and if your PHP version is over 5.5.0 if (!empty($this->header['theImage'])) { if (PHP_VERSION_ID >= 50500 && $this->header['scalebgImage'] == true) { imagescale($this->header['theImage'], $this->imageWidth); } imagecopy($this->theImage, $this->header['theImage'], 0, 0, 0, 0, $this->header['bgImageWidth'], $this->header['bgImageHeight']); } if (!empty($this->footer['theImage'])) { if (PHP_VERSION_ID >= 50500 && $this->footer['scalebgImage'] == true) { imagescale($this->footer['theImage'], $this->imageWidth); } imagecopy($this->theImage, $this->footer['theImage'], 0, $this->imageHeight - $this->footer['bgImageHeight'], 0, 0, $this->footer['bgImageWidth'], $this->footer['bgImageHeight']); } $lineHeight = $this->verticalImageMargin + $this->header['fontSize'] + $this->footer['fontSize'] / 3; if (!empty($this->header['string'][0])) { foreach ($this->header['string'] as $s) { imagettftext($this->theImage, $this->header['fontSize'], 0, $this->horizontalImageMargin, $lineHeight, $headerColor, $this->header['font'], $s); $lineHeight += $this->header['lineHeight']; } } $lineHeight += $this->verticalImageMargin + $this->header['padding']; foreach ($this->body['string'] as $s) { imagettftext($this->theImage, $this->body['fontSize'], 0, $this->horizontalImageMargin, $lineHeight, $bodyColor, $this->body['font'], $s); $lineHeight += $this->body['lineHeight']; } $lineHeight += $this->verticalImageMargin + $this->footer['padding']; if (!empty($this->footer['string'][0])) { foreach ($this->footer['string'] as $s) { imagettftext($this->theImage, $this->footer['fontSize'], 0, $this->horizontalImageMargin, $lineHeight, $footerColor, $this->footer['font'], $s); $lineHeight += $this->footer['lineHeight']; } } }
<?php include dirname(__FILE__) . '/_init.php'; if (!defined('IMAGE_EX_SCALE_CARVE')) { echo "Seam carving (by using liblqr) is not enabled.\n"; exit(1); } $im = imagecreatefromjpeg('images/mutzig.jpg'); $im1 = imagescale($im, 100, 100, IMAGE_EX_SCALE_CARVE); imagejpeg($im1, 'output/scale-carve-1.jpg'); $im2 = imagescale($im, 1000, 1000, IMAGE_EX_SCALE_CARVE); imagejpeg($im2, 'output/scale-carve-2.jpg');
} } } if ($errorText) { Error($errorText); } else { if (($scale == 0 || $scale == 100) && $width == 0 && $height == 0) { readfile(ZM_DIR_EVENTS . '/' . $path); } else { $i = imagecreatefromjpeg(ZM_DIR_EVENTS . '/' . $path); $oldWidth = imagesx($i); $oldHeight = imagesy($i); if ($width == 0 && $height == 0) { $width = $oldWidth * $scale / 100.0; $height = $oldHeight * $scale / 100.0; } elseif ($width == 0 && $height != 0) { $width = $height * $oldWidth / $oldHeight; } elseif ($width != 0 && $height == 0) { $height = $width * $oldHeight / $oldWidth; } if ($width == $oldWidth && $height == $oldHeight) { imagejpeg($i); imagedestroy($i); } else { $iScale = imagescale($i, $width, $height); imagejpeg($iScale); imagedestroy($i); imagedestroy($iScale); } } }
<?php include dirname(__FILE__) . '/_init.php'; $im = imagecreatefromjpeg('images/mutzig.jpg'); $im1 = imagescale($im, 100, 100, IMAGE_EX_SCALE_NONE); imagejpeg($im1, 'output/scale-none-1.jpg'); $im2 = imagescale($im, 1000, 1000, IMAGE_EX_SCALE_NONE); imagejpeg($im2, 'output/scale-none-2.jpg');
if ($state->isState('authorized')) { $login = $state->getState('authorized'); if ($_FILES['image']['error'] !== 0) { error("Ошибка при загрузке изображения."); } else { if ($_FILES['image']['size'] === 0) { error("Файл не выбран."); } else { $tmpImage = $_FILES['image']['tmp_name']; $size = getimagesize($tmpImage); $typeToImgCreateFuncs = ['image/gif' => 'imagecreatefromgif', 'image/jpeg' => 'imagecreatefromjpeg', 'image/png' => 'imagecreatefrompng', 'image/bmp' => 'imagecreatefrombmp']; if (!$size || !in_array($size['mime'], array_keys($typeToImgCreateFuncs))) { error("Некорректный формат изображения."); } else { $param = new Parameters(); $db = new DB(); $id = $db->addImage($login); $image = call_user_func($typeToImgCreateFuncs[$size['mime']], $tmpImage); $imagePath = $param->imagesPath . $login . DIRECTORY_SEPARATOR; $ratio = $size[1] / $size[0]; $size = $param->previewSize; $scaled = imagescale($image, $size['width'], $size['height'] * $ratio); imagejpeg($image, $imagePath . $id . '.jpg', 100); imagejpeg($scaled, $imagePath . $id . $param->previewSuffix . '.jpg'); imagedestroy($image); imagedestroy($scaled); echo "success"; } } } }
<?php header("Content-type: image/jpeg"); require_once "resources/config.php"; $stmt = $mysqli->prepare('select folder, filename from photoman_image where image_id = ?'); $stmt->bind_param('s', $_GET['img']); $stmt->execute(); /* bind result variables */ $stmt->bind_result($folder, $filename); /* fetch value */ $stmt->fetch(); $image_path = $folder . DIRECTORY_SEPARATOR . $filename; $image = imagecreatefromjpeg($image_path); $scaled = imagescale($image, 200, -1, IMG_BICUBIC_FIXED); imagejpeg($scaled); $mysqli->close();
private function handleImages($eqFiles, $eq, $em) { foreach ($eqFiles as $file) { // store the original, and image itself $origFullPath = $this->getParameter('image_storage_dir') . DIRECTORY_SEPARATOR . 'equipment' . DIRECTORY_SEPARATOR . 'original' . DIRECTORY_SEPARATOR . $file[0] . '.' . $file[2]; $imgFullPath = $this->getParameter('image_storage_dir') . DIRECTORY_SEPARATOR . 'equipment' . DIRECTORY_SEPARATOR . $file[0] . '.' . $file[2]; rename($file[3], $origFullPath); // check image size $imgInfo = getimagesize($origFullPath); $ow = $imgInfo[0]; // original width $oh = $imgInfo[1]; // original height $r = $ow / $oh; // ratio $nw = $ow; // new width $nh = $oh; // new height $scale = False; if ($r > 1) { if ($ow > 1024) { $nw = 1024; $m = $nw / $ow; // multiplier $nh = $oh * $m; $scale = True; } } else { if ($oh > 768) { $nh = 768; $m = $nh / $oh; // multiplier $nw = $ow * $m; $scale = True; } } // scale the image if ($scale) { if ($file[2] == 'png') { $img = imagecreatefrompng($origFullPath); } else { $img = imagecreatefromjpeg($origFullPath); } $sc = imagescale($img, intval(round($nw)), intval(round($nh)), IMG_BICUBIC_FIXED); if ($file[2] == 'png') { imagepng($sc, $imgFullPath); } else { imagejpeg($sc, $imgFullPath); } } else { copy($origFullPath, $imgFullPath); } // store entry in database $img = new Image(); $img->setUuid($file[0]); $img->setName($file[1]); $img->setExtension($file[2]); $img->setPath('equipment'); $img->setOriginalPath('equipment' . DIRECTORY_SEPARATOR . 'original'); $em->persist($img); $em->flush(); $eq->addImage($img); $em->flush(); } }
function imgTableizr($imgSrc, $quality = 'medium', $width = 'no-resize') { global $colspan, $prevHex, $prevRGB, $currentHex, $currentRGB, $tdCount, $output; $output = array(); $explodedSrc = explode('.', $imgSrc); $ext = end($explodedSrc); switch ($ext) { case 'jpg' || 'jpeg': $img = imagecreatefromjpeg($imgSrc); break; case 'png': $img = imagecreatefrompng($imgSrc); break; case 'gif': $img = imagecreatefromgif($imgSrc); break; case 'bmp': $img = imagecreatefrombmp($imgSrc); break; default: return false; } if ($width != 'no-resize' && is_int($width) && $width > 0) { $img = imagescale($img, $width); } switch ($quality) { case 'medium': $threshold = 20; break; case 'low': $threshold = 30; break; case 'high': $threshold = 10; break; case 'maximum': $threshold = 0; break; case is_int($quality) && $quality >= 0: $threshold = $quality; break; case is_int($quality) && $quality < 0: $threshold = 0; break; default: return false; } $imgW = imagesx($img); $imgH = imagesy($img); array_push($output, '<table style="border-spacing:0;width:' . $imgW . 'px;height:' . $imgH . 'px;margin:0;padding:0;">'); for ($y = 0; $imgH > $y; $y++) { array_push($output, '<tr>'); for ($x = 0; $imgW > $x; $x++) { $rgb = imagecolorat($img, $x, $y); $currentRGB = array(0 => $rgb >> 16 & 0xff, 1 => $rgb >> 8 & 0xff, 2 => $rgb & 0xff); $currentHex = rgb2hex($currentRGB); if ($x != 0) { if (abs($currentRGB[0] - $prevRGB[0]) <= $threshold) { if (abs($currentRGB[1] - $prevRGB[1]) <= $threshold) { if (abs($currentRGB[2] - $prevRGB[2]) <= $threshold) { $colspan++; if ($x + 1 == $imgW) { generateCell(); } } else { generateCell(); } } else { generateCell(); } } else { generateCell(); } } else { $prevHex = $currentHex; $prevRGB = $currentRGB; } } array_push($output, '</tr>'); } array_push($output, '</table>'); imagedestroy($img); echo implode('', $output); }
public function resize(handle $handle, $width, $height, $zoom = true, $background = '#000000') { $background = hexdec(ltrim($background, '#')); $resource = $handle->getResource(); return imagescale($resource, intval($width), intval($height)); }
function scaleToHeight($in_fn, $out_fn, $height) { if( ! file_exists($in_fn ) ) throw new \Exception("file $in_fn does not exists"); $im = imagecreatefromjpeg($in_fn); $ini_x_size = getimagesize($in_fn)[0]; $ini_y_size = getimagesize($in_fn)[1]; $new_y = $height; $new_x = ($new_y * $ini_x_size) / ($ini_y_size); print "Initial size ". $ini_x_size ." ". $ini_y_size ."\n"; print "Scaled sizes : ".$new_x.":".$new_y ."\n"; if( ! ($scaled_im = imagescale($im, $new_x, $new_y)) ) throw new \Exception("Scaling operation failed"); if( ! imagejpeg($scaled_im, $out_fn, 100) ) throw new \Exception("write of scaled image to $out_fn failed"); }