/** * 生成された画像を保存する * * @return boolean * @access public * @static */ function save() { //保存先のディレクトリが存在しているかチェック $filePath = dirname($this->dstPath); if (!file_exists($filePath)) { mkdir($filePath); } if ($this->imageType == 'image/jpeg') { return imageJpeg($this->dstImage, $this->dstPath, $this->quality); } elseif ($this->imageType == 'image/gif') { return imageGif($this->dstImage, $this->dstPath); } elseif ($this->imageType == 'image/png') { return imagePng($this->dstImage, $this->dstPath); } }
public function resize_image($data, $imgX, $sizedef, $lid, $imgid) { $file = $data["raw_name"]; $type = $data["file_ext"]; $outfile = $imgX[$sizedef]['dir'] . "/" . $lid . "/" . $file . '.jpg'; $path = $this->config->item("upload_dir"); $image = $this->create_image_container($file, $type); if ($image) { $size = GetImageSize($path . $file . $type); $old = $image; // сей форк - не просто так. непонятно, правда, почему... if ($size['1'] < $size['0']) { $h_new = round($imgX[$sizedef]['max_dim'] * ($size['1'] / $size['0'])); $measures = array($imgX[$sizedef]['max_dim'], $h_new); } if ($size['1'] >= $size['0']) { $h_new = round($imgX[$sizedef]['max_dim'] * ($size['0'] / $size['1'])); $measures = array($h_new, $imgX[$sizedef]['max_dim']); } $new = ImageCreateTrueColor($measures[0], $measures[1]); ImageCopyResampled($new, $image, 0, 0, 0, 0, $measures[0], $measures[1], $size['0'], $size['1']); imageJpeg($new, $outfile, $imgX[$sizedef]['quality']); $this->db->query("UPDATE `images` SET `images`.`" . $sizedef . "` = ? WHERE `images`.`id` = ?", array(implode($measures, ","), $imgid)); imageDestroy($new); } }
function image_createThumb($src, $dest, $maxWidth, $maxHeight, $quality = 75) { if (file_exists($src) && isset($dest)) { // path info $destInfo = pathInfo($dest); // image src size $srcSize = getImageSize($src); // image dest size $destSize[0] = width, $destSize[1] = height $srcRatio = $srcSize[0] / $srcSize[1]; // width/height ratio $destRatio = $maxWidth / $maxHeight; if ($destRatio > $srcRatio) { $destSize[1] = $maxHeight; $destSize[0] = $maxHeight * $srcRatio; } else { $destSize[0] = $maxWidth; $destSize[1] = $maxWidth / $srcRatio; } // path rectification if ($destInfo['extension'] == "gif") { $dest = substr_replace($dest, 'jpg', -3); } // true color image, with anti-aliasing $destImage = imageCreateTrueColor($destSize[0], $destSize[1]); // imageAntiAlias($destImage,true); // src image switch ($srcSize[2]) { case 1: //GIF $srcImage = imageCreateFromGif($src); break; case 2: //JPEG $srcImage = imageCreateFromJpeg($src); break; case 3: //PNG $srcImage = imageCreateFromPng($src); break; default: return false; break; } // resampling imageCopyResampled($destImage, $srcImage, 0, 0, 0, 0, $destSize[0], $destSize[1], $srcSize[0], $srcSize[1]); // generating image switch ($srcSize[2]) { case 1: case 2: imageJpeg($destImage, $dest, $quality); break; case 3: imagePng($destImage, $dest); break; } return true; } else { return 'No such File'; } }
private function resizeImage($file, $data, $tmd = 600, $quality = 100) { $data['type'] = "image/jpeg"; $basename = basename($file); $filesDir = $this->input->post('uploadDir'); // хэш нередактируемой карты! $uploaddir = implode(array($this->input->server('DOCUMENT_ROOT'), 'storage', $tmd, $filesDir), DIRECTORY_SEPARATOR); $srcFile = implode(array($this->input->server('DOCUMENT_ROOT'), 'storage', 'source', $filesDir, $basename), DIRECTORY_SEPARATOR); $image = $this->createimageByType($data, $srcFile); if (!file_exists($uploaddir)) { mkdir($uploaddir, 0775, true); } $size = GetImageSize($srcFile); $new = ImageCreateTrueColor($size['1'], $size['0']); if ($size['1'] > $tmd || $size['0'] > $tmd) { if ($size['1'] < $size['0']) { $hNew = round($tmd * $size['1'] / $size['0']); $new = ImageCreateTrueColor($tmd, $hNew); ImageCopyResampled($new, $image, 0, 0, 0, 0, $tmd, $hNew, $size['0'], $size['1']); } if ($size['1'] >= $size['0']) { $hNew = round($tmd * $size['0'] / $size['1']); $new = ImageCreateTrueColor($hNew, $tmd); ImageCopyResampled($new, $image, 0, 0, 0, 0, $hNew, $tmd, $size['0'], $size['1']); } } //print $uploaddir."/".TMD."/".$filename.".jpg<br>"; imageJpeg($new, $uploaddir . DIRECTORY_SEPARATOR . $basename, $quality); //header("content-type: image/jpeg");// активировать для отладки //imageJpeg ($new, "", 100);//активировать для отладки imageDestroy($new); }
function generate_thumbnail($file, $mime) { global $config; gd_capabilities(); list($file_type, $exact_type) = explode("/", $mime); if (_JB_GD_INSTALLED && ($file_type = "image")) { if ($exact_type != "gif" && $exact_type != "png" && $exact_type != "jpeg") { return false; } if ($exact_type == "gif" && !_JB_GD_GIF) { return false; } if ($exact_type == "png" && !_JB_GD_PNG) { return false; } if ($exact_type == "jpeg" && !_JB_GD_JPG) { return false; } // Load up the original and get size // NOTE: use imageCreateFromString to avoid to have to check what type of image it is $original = imageCreateFromString(file_get_contents($file)); $original_w = imagesX($original); $original_h = imagesY($original); // Only if the image is really too big, resize it // NOTE: if image is smaller than target size, don't do anything. // We *could* copy the original to filename_thumb, but since it's the same // it would be a waste of precious resources if ($original_w > $config['uploader']['thumb_w'] || $original_h > $config['uploader']['thumb_h']) { // If original is wider than it's high, resize the width and vice versa // NOTE: '>=' cause otherwise it's possible that $scale isn't computed if ($original_w >= $original_h) { $scaled_w = $config['uploader']['thumb_w']; // Figure out how much smaller that target is than original // and apply it to height $scale = $config['uploader']['thumb_w'] / $original_w; $scaled_h = ceil($original_h * $scale); } elseif ($original_w <= $original_h) { $scaled_h = $config['uploader']['thumb_h']; $scale = $config['uploader']['thumb_h'] / $original_h; $scaled_w = ceil($original_w * $scale); } } else { // Break out of if($file_type = image) since no resize is possible return false; } // Scale the image $scaled = imageCreateTrueColor($scaled_w, $scaled_h); imageCopyResampled($scaled, $original, 0, 0, 0, 0, $scaled_w, $scaled_h, $original_w, $original_h); // Store thumbs in jpeg, hope no one minds the 100% quality lol imageJpeg($scaled, $file . "_thumb", 100); // Let's be nice to our server imagedestroy($scaled); imagedestroy($original); return true; } }
function writeCopy($filename, $width, $height) { if($this->isLoaded()) { $imageNew = imageCreate($width, $height); if(!$imageNew) { echo "ERREUR : Nouvelle image non créée"; } imageCopyResized($imageNew, $this->image, 0, 0, 0, 0, $width, $height, $this->width, $this->height); imageJpeg($imageNew, $filename); } }
public static function saveFile($image = null, $destFile = null, $saveType = self::SAVE_JPG) { switch ($saveType) { case self::SAVE_GIF: return @imageGif($image, $destFile); case self::SAVE_JPG: return @imageJpeg($image, $destFile, self::SAVE_QUALITY); case self::SAVE_PNG: return @imagePng($image, $destFile); default: return false; } }
/** * Create test image. * * @param string $filename * @return void */ protected function createTestImage($filename) { $filename = $this->getFullPath($filename); if (!file_exists($filename)) { // Create an image with the specified dimensions $image = imageCreate(300, 200); // Create a color (this first call to imageColorAllocate // also automatically sets the image background color) $colorYellow = imageColorAllocate($image, 255, 255, 0); // Draw a rectangle imageFilledRectangle($image, 50, 50, 250, 150, $colorYellow); $directory = dirname($filename); if (!file_exists($directory)) { mkdir($directory, 0777, true); } imageJpeg($image, $filename); // Release memory imageDestroy($image); } }
function make_img($content) { $timage = array(strlen($content) * 20 + 10, 28); // array(largeur, hauteur) de l'image; ici la largeur est fonction du nombre de lettre du contenu, on peut bien sur mettre une largeur fixe. $content = preg_replace('/(\\w)/', '\\1 ', $content); // laisse plus d'espace entre les lettres $image = imagecreatetruecolor($timage[0], $timage[1]); // création de l'image // definition des couleurs $fond = imageColorAllocate($image, 240, 255, 240); $grey = imageColorAllocate($image, 210, 210, 210); $text_color = imageColorAllocate($image, rand(0, 100), rand(0, 50), rand(0, 60)); imageFill($image, 0, 0, $fond); // on remplit l'image de blanc //On remplit l'image avec des polygones for ($i = 0, $imax = mt_rand(3, 5); $i < $imax; $i++) { $x = mt_rand(3, 10); $poly = array(); for ($j = 0; $j < $x; $j++) { $poly[] = mt_rand(0, $timage[0]); $poly[] = mt_rand(0, $timage[1]); } imageFilledPolygon($image, $poly, $x, imageColorAllocate($image, mt_rand(150, 255), mt_rand(150, 255), mt_rand(150, 255))); } // Création des pixels gris for ($i = 0; $i < $timage[0] * $timage[1] / rand(15, 18); $i++) { imageSetPixel($image, rand(0, $timage[0]), rand(0, $timage[1]), $grey); } // affichage du texte demandé; on le centre en hauteur et largeur (à peu près ^^") //imageString($image, 5, ceil($timage[0]-strlen($content)*8)/2, ceil($timage[1]/2)-9, $content, $text_color); $longueur_chaine = strlen($content); for ($ch = 0; $ch < $longueur_chaine; $ch++) { imagettftext($image, 18, mt_rand(-30, 30), 10 * ($ch + 1), mt_rand(18, 20), $text_color, 'res/georgia.ttf', $content[$ch]); } $type = function_exists('imageJpeg') ? 'jpeg' : 'png'; @header('Content-Type: image/' . $type); @header('Cache-control: no-cache, no-store'); $type == 'png' ? imagePng($image) : imageJpeg($image); ImageDestroy($image); exit; }
function resizeImage($file, $max_x, $max_y, $forcePng = false) { if ($max_x <= 0 || $max_y <= 0) { $max_x = 5; $max_y = 5; } $src = BASEDIR . '/avatars/' . $file; list($width, $height, $type) = getImageSize($src); $scale = min($max_x / $width, $max_y / $height); $newWidth = $width * $scale; $newHeight = $height * $scale; $img = imagecreatefromstring(file_get_contents($src)); $black = imagecolorallocate($img, 0, 0, 0); $resizedImage = imageCreateTrueColor($newWidth, $newHeight); imagecolortransparent($resizedImage, $black); imageCopyResampled($resizedImage, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); imageDestroy($img); unlink($src); if (!$forcePng) { switch ($type) { case IMAGETYPE_JPEG: imageJpeg($resizedImage, BASEDIR . '/avatars/' . $file); break; case IMAGETYPE_GIF: imageGif($resizedImage, BASEDIR . '/avatars/' . $file); break; case IMAGETYPE_PNG: imagePng($resizedImage, BASEDIR . '/avatars/' . $file); break; default: imagePng($resizedImage, BASEDIR . '/avatars/' . $file); break; } } else { imagePng($resizedImage, BASEDIR . '/avatars/' . $file . '.png'); } return; }
function save($filename, $type = 'png', $quality = 100) { $this->_build(); $this->_build_border(); switch ($type) { case 'gif': $ret = imageGif($this->_dest_image, $filename); break; case 'jpg': case 'jpeg': $ret = imageJpeg($this->_dest_image, $filename, $quality); break; case 'png': $ret = imagePng($this->_dest_image, $filename); break; default: $this->_error('Save: Invalid Format'); break; } if (!$ret) { $this->_error('Save: Unable to save'); } }
private function resizeJpeg($newW, $newH, $oWidth, $oHeight, $fullPath) { // create a new canvas $im = ImageCreateTruecolor($newW, $newH); $baseImage = ImageCreateFromJpeg($this->imageName); // if successful this returns as true - this is the actual resizing if (imagecopyresampled($im, $baseImage, 0, 0, 0, 0, $newW, $newH, $oWidth, $oHeight)) { // resizing is successful and saved to $fullPath imageJpeg($im, $fullPath); if (file_exists($fullPath)) { $this->msg .= 'Resized file created<br />'; imagedestroy($im); // don't really need this cos $im will disappear after function done return true; } else { $this->msg .= 'Failure in resize jpeg<br />'; } } else { // resizing fails $this->msg .= 'Unable to resize image<br />'; return false; } }
function createThumbMobile($src, $dest, $desired_width) { $max_h = 68; $max_w = 80; if ($max_w > $max_h) { $max_h = $max_w; } else { if ($max_h > $max_w) { $max_w = $max_h; } } $size = getImageSize($src); $old_w = $size[0]; $old_h = $size[1]; if ($old_w > $old_h) { $nw = $max_w; $nh = $old_h * ($max_w / $old_w); } if ($old_w < $old_h) { $nw = $old_w * ($max_h / $old_h); $nh = $max_h; } if ($old_w == $old_h) { $nw = $max_w; $nh = $max_h; } // Building the intermediate resized thumbnail $resimage = imagecreatefromjpeg($src); $newimage = imagecreatetruecolor($nw, $nh); // use alternate function if not installed imageCopyResampled($newimage, $resimage, 0, 0, 0, 0, $nw, $nh, $old_w, $old_h); // Making the final cropped thumbnail $viewimage = imagecreatetruecolor($max_w, $max_h); $bg = imagecolorallocate($viewimage, 255, 255, 255); imagefill($viewimage, 0, 0, $bg); imagecopy($viewimage, $newimage, 0, 0, 0, 0, $nw, $nh); // saving imageJpeg($viewimage, $dest, 85); }
function Main($path, $width, $height, $dst_file, $header = false) { if (!isset($path)) { return array(0, "イメージのパスが設定されていません。"); } if (!file_exists($path)) { return array(0, "指定されたパスにファイルが見つかりません。"); } // 画像の大きさをセット if ($width) { $this->imgMaxWidth = $width; } if ($height) { $this->imgMaxHeight = $height; } $size = @GetimageSize($path); $re_size = $size; //アスペクト比固定処理 if ($this->imgMaxWidth != 0) { $tmp_w = $size[0] / $this->imgMaxWidth; } if ($this->imgMaxHeight != 0) { $tmp_h = $size[1] / $this->imgMaxHeight; } if ($tmp_w > 1 || $tmp_h > 1) { if ($this->imgMaxHeight == 0) { if ($tmp_w > 1) { $re_size[0] = $this->imgMaxWidth; $re_size[1] = $size[1] * $this->imgMaxWidth / $size[0]; } } else { if ($tmp_w > $tmp_h) { $re_size[0] = $this->imgMaxWidth; $re_size[1] = $size[1] * $this->imgMaxWidth / $size[0]; } else { $re_size[1] = $this->imgMaxHeight; $re_size[0] = $size[0] * $this->imgMaxHeight / $size[1]; } } } $imagecreate = function_exists("imagecreatetruecolor") ? "imagecreatetruecolor" : "imagecreate"; $imageresize = function_exists("imagecopyresampled") ? "imagecopyresampled" : "imagecopyresized"; switch ($size[2]) { // gif形式 case "1": if (function_exists("imagecreatefromgif")) { $src_im = imagecreatefromgif($path); $dst_im = $imagecreate($re_size[0], $re_size[1]); $transparent = imagecolortransparent($src_im); $colorstotal = imagecolorstotal($src_im); $dst_im = imagecreate($re_size[0], $re_size[1]); if (0 <= $transparent && $transparent < $colorstotal) { imagepalettecopy($dst_im, $src_im); imagefill($dst_im, 0, 0, $transparent); imagecolortransparent($dst_im, $transparent); } $imageresize($dst_im, $src_im, 0, 0, 0, 0, $re_size[0], $re_size[1], $size[0], $size[1]); if (function_exists("imagegif")) { // 画像出力 if ($header) { header("Content-Type: image/gif"); imagegif($dst_im); return ""; } else { $dst_file = $dst_file . ".gif"; if ($re_size[0] == $size[0] && $re_size[1] == $size[1]) { // サイズが同じ場合には、そのままコピーする。(画質劣化を防ぐ) copy($path, $dst_file); } else { imagegif($dst_im, $dst_file); } } imagedestroy($src_im); imagedestroy($dst_im); } else { // 画像出力 if ($header) { header("Content-Type: image/png"); imagepng($dst_im); return ""; } else { $dst_file = $dst_file . ".png"; if ($re_size[0] == $size[0] && $re_size[1] == $size[1]) { // サイズが同じ場合には、そのままコピーする。(画質劣化を防ぐ) copy($path, $dst_file); } else { imagepng($dst_im, $dst_file); } } imagedestroy($src_im); imagedestroy($dst_im); } } else { // サムネイル作成不可の場合(旧バージョン対策) $dst_im = imageCreate($re_size[0], $re_size[1]); imageColorAllocate($dst_im, 255, 255, 214); //背景色 // 枠線と文字色の設定 $black = imageColorAllocate($dst_im, 0, 0, 0); $red = imageColorAllocate($dst_im, 255, 0, 0); imagestring($dst_im, 5, 10, 10, "GIF {$size['0']}x{$size['1']}", $red); imageRectangle($dst_im, 0, 0, $re_size[0] - 1, $re_size[1] - 1, $black); // 画像出力 if ($header) { header("Content-Type: image/png"); imagepng($dst_im); return ""; } else { $dst_file = $dst_file . ".png"; imagepng($dst_im, $dst_file); } imagedestroy($src_im); imagedestroy($dst_im); } break; // jpg形式 // jpg形式 case "2": $src_im = imageCreateFromJpeg($path); $dst_im = $imagecreate($re_size[0], $re_size[1]); $imageresize($dst_im, $src_im, 0, 0, 0, 0, $re_size[0], $re_size[1], $size[0], $size[1]); // 画像出力 if ($header) { header("Content-Type: image/jpeg"); imageJpeg($dst_im); return ""; } else { $dst_file = $dst_file . ".jpg"; if ($re_size[0] == $size[0] && $re_size[1] == $size[1]) { // サイズが同じ場合には、そのままコピーする。(画質劣化を防ぐ) copy($path, $dst_file); } else { imageJpeg($dst_im, $dst_file); } } imagedestroy($src_im); imagedestroy($dst_im); break; // png形式 // png形式 case "3": $src_im = imageCreateFromPNG($path); $colortransparent = imagecolortransparent($src_im); $has_alpha = ord(file_get_contents($path, false, null, 25, 1)) & 0x4; if ($colortransparent > -1 || $has_alpha) { $dst_im = $imagecreate($re_size[0], $re_size[1]); // アルファチャンネルが存在する場合はそちらを使用する if ($has_alpha) { imagealphablending($dst_im, false); imagesavealpha($dst_im, true); } imagepalettecopy($dst_im, $src_im); imagefill($dst_im, 0, 0, $colortransparent); imagecolortransparent($dst_im, $colortransparent); imagecopyresized($dst_im, $src_im, 0, 0, 0, 0, $re_size[0], $re_size[1], $size[0], $size[1]); } else { $dst_im = $imagecreate($re_size[0], $re_size[1]); imagecopyresized($dst_im, $src_im, 0, 0, 0, 0, $re_size[0], $re_size[1], $size[0], $size[1]); imagecolorstotal($src_im) == 0 ? $colortotal = 65536 : ($colortotal = imagecolorstotal($src_im)); imagetruecolortopalette($dst_im, true, $colortotal); } // 画像出力 if ($header) { header("Content-Type: image/png"); imagepng($dst_im); return ""; } else { $dst_file = $dst_file . ".png"; if ($re_size[0] == $size[0] && $re_size[1] == $size[1]) { // サイズが同じ場合には、そのままコピーする。(画質劣化を防ぐ) copy($path, $dst_file); } else { imagepng($dst_im, $dst_file); } } imagedestroy($src_im); imagedestroy($dst_im); break; default: return array(0, "イメージの形式が不明です。"); } return array(1, $dst_file); }
/** * Writes the input GDlib image pointer to file * * @param resource $destImg The GDlib image resource pointer * @param string $theImage The filename to write to * @param int $quality The image quality (for JPEGs) * @return bool The output of either imageGif, imagePng or imageJpeg based on the filename to write * @see maskImageOntoImage(), scale(), output() */ public function ImageWrite($destImg, $theImage, $quality = 0) { imageinterlace($destImg, 0); $ext = strtolower(substr($theImage, strrpos($theImage, '.') + 1)); $result = false; switch ($ext) { case 'jpg': case 'jpeg': if (function_exists('imageJpeg')) { if ($quality == 0) { $quality = $this->jpegQuality; } $result = imageJpeg($destImg, $theImage, $quality); } break; case 'gif': if (function_exists('imageGif')) { imagetruecolortopalette($destImg, true, 256); $result = imageGif($destImg, $theImage); } break; case 'png': if (function_exists('imagePng')) { $result = ImagePng($destImg, $theImage); } break; } if ($result) { GeneralUtility::fixPermissions($theImage); } return $result; }
// readfile($filename); // exit; $old_image = imagecreatefromgif($filename); } elseif ($image_format == 2) { $old_image = imagecreatefromjpeg($filename); } elseif ($image_format == 3) { $old_image = imagecreatefrompng($filename); } else { return; } // echo("$image_width x $image_height"); $new_image = imageCreateTrueColor($image_width, $image_height); $white = ImageColorAllocate($new_image, 255, 255, 255); ImageFill($new_image, 0, 0, $white); /*imageCopyResized*/ imagecopyresampled($new_image, $old_image, 0, 0, 0, 0, $image_width, $image_height, imageSX($old_image), imageSY($old_image)); // Save to cache if (_I_CACHING == "1" && !$_REQUEST['dc']) { //if (!file_exists(_I_CACHE_PATH)) { // @mkdir(_I_CACHE_PATH, 0777); //} if (!is_dir($path_to_cache_file)) { @mkdir($path_to_cache_file); } imageJpeg($new_image, $cache); //@chmod($cache, '0666'); } // Endof save Header("Content-type:image/jpeg"); imageJpeg($new_image); }
$file_size = $_FILES['myfile']['size']; $sql = "select count(id)+1 from pe.file_allegati allegati where pratica={$idpratica} and allegato={$idallegato}"; if ($desc) { $sql = "insert into pe.file_allegati (pratica,allegato,nome_file,tipo_file,size_file,ordine,chk,uidins,tmsins,form,note) values ({$idpratica},{$idallegato},'{$file_name}','{$file_type}',{$file_size},({$sql}),1," . $_SESSION["USER_ID"] . "," . time() . ",'{$form}','{$desc}');"; } else { $sql = "insert into pe.file_allegati (pratica,allegato,nome_file,tipo_file,size_file,ordine,chk,uidins,tmsins,form) values ({$idpratica},{$idallegato},'{$file_name}','{$file_type}',{$file_size},({$sql}),1," . $_SESSION["USER_ID"] . "," . time() . ",'{$form}');"; } $db->sql_query($sql); $_SESSION["ADD_NEW"] = 1; if (DEBUG) { echo $sql; } //creo l'oggetto immagine se il file è tipo immagine if (ereg("jpeg", $file_type)) { $im_file_name = $updDir . $file_name; $image_attribs = getimagesize($im_file_name); $im_old = @imageCreateFromJpeg($im_file_name); //setto le dimensioni del thumbnail $th_max_width = 100; $th_max_height = 100; $ratio = $width > $height ? $th_max_width / $image_attribs[0] : $th_max_height / $image_attribs[1]; $th_width = $image_attribs[0] * $ratio; $th_height = $image_attribs[1] * $ratio; $im_new = imagecreatetruecolor($th_width, $th_height); //@imageantialias ($im_new,true); //creo la thumbnail e la copio sul disco $th_file_name = $updDir . "tmb/tmb_" . $file_name; @imageCopyResampled($im_new, $im_old, 0, 0, 0, 0, $th_width, $th_height, $image_attribs[0], $image_attribs[1]); @imageJpeg($im_new, $th_file_name, 100); ini_set('max_execution_time', $var); }
} switch ($ext) { case "gif": header('Content-type: image/gif'); imageGif($imgNew, $cache_path); imageGif($imgNew); break; case "jpg": header('Content-type: image/jpeg'); imageJpeg($imgNew, $cache_path); imageJpeg($imgNew); break; case "jpeg": header('Content-type: image/jpeg'); imageJpeg($imgNew, $cache_path); imageJpeg($imgNew); break; case "png": header('Content-type: image/png'); imagePng($imgNew, $cache_path); imagePng($imgNew); break; } imageDestroy($img); imageDestroy($imgNew); // function from docos to convert short-hand notation to bytes function imageresize_return_bytes($val) { $val = trim($val); $last = strtolower($val[strlen($val) - 1]); switch ($last) {
function debugMode($line, $message, $file = null, $config = null, $message2 = null) { global $im, $configData; // Destroy the image if (isset($im)) { imageDestroy($im); } if (is_numeric($line)) { $line -= 1; } $error_text = 'Error!'; $line_text = 'Line: ' . $line; $file = !empty($file) ? 'File: ' . $file : ''; $config = $config ? 'Check the config file' : ''; $message2 = !empty($message2) ? $message2 : ''; $lines = array(); $lines[] = array('s' => $error_text, 'f' => 5, 'c' => 'red'); $lines[] = array('s' => $line_text, 'f' => 3, 'c' => 'blue'); $lines[] = array('s' => $file, 'f' => 2, 'c' => 'green'); $lines[] = array('s' => $message, 'f' => 2, 'c' => 'black'); $lines[] = array('s' => $config, 'f' => 2, 'c' => 'black'); $lines[] = array('s' => $message2, 'f' => 2, 'c' => 'black'); $height = $width = 0; foreach ($lines as $line) { if (strlen($line['s']) > 0) { $line_width = ImageFontWidth($line['f']) * strlen($line['s']); $width = $width < $line_width ? $line_width : $width; $height += ImageFontHeight($line['f']); } } $im = @imagecreate($width + 1, $height); if ($im) { $white = imagecolorallocate($im, 255, 255, 255); $red = imagecolorallocate($im, 255, 0, 0); $green = imagecolorallocate($im, 0, 255, 0); $blue = imagecolorallocate($im, 0, 0, 255); $black = imagecolorallocate($im, 0, 0, 0); $linestep = 0; foreach ($lines as $line) { if (strlen($line['s']) > 0) { imagestring($im, $line['f'], 1, $linestep, utf8_to_nce($line['s']), ${$line}['c']); $linestep += ImageFontHeight($line['f']); } } switch ($configData['image_type']) { case 'jpeg': case 'jpg': header('Content-type: image/jpg'); @imageJpeg($im); break; case 'png': header('Content-type: image/png'); @imagePng($im); break; case 'gif': default: header('Content-type: image/gif'); @imagegif($im); break; } imageDestroy($im); } else { if (!empty($file)) { $file = "[<span style=\"color:green\">{$file}</span>]"; } $string = "<strong><span style=\"color:red\">Error!</span></strong>"; $string .= "<span style=\"color:blue\">Line {$line}:</span> {$message} {$file}\n<br /><br />\n"; if ($config) { $string .= "{$config}\n<br />\n"; } if (!empty($message2)) { $string .= "{$message2}\n"; } print $string; } exit; }
function redimage($src, $dest, $dw = false, $dh = false, $stamp = false) { // detect file type (could be a lot better) if (is_array($src)) { $type_src = strtoupper(substr($src['name'], -3)); $src = $src['tmp_name']; } else { $type_src = strtoupper(substr($src, -3)); } $type_dest = strtoupper(substr($dest, -3)); // read source image switch ($type_src) { case 'JPG': $src_img = ImageCreateFromJpeg($src); break; case 'PEG': $src_img = ImageCreateFromJpeg($src); break; case 'GIF': $src_img = ImageCreateFromGif($src); break; case 'PNG': $src_img = imageCreateFromPng($src); break; case 'BMP': $src_img = imageCreatefromWBmp($src); break; } // get it's info $size = GetImageSize($src); $sw = $size[0]; $sh = $size[1]; /* // get it's info $size = GetImageSize ($src); $fw = $size[0]; $fh = $size[1]; // ROGNE the picture from the top left pixel's color $rogne_color = imagecolorat ($src_img, 0, 0); $rogne_point = array ($fh, 0, 0, $fw); for ($x = 0; $x < $fw; $x ++){ for ($y = 0; $y < $fh; $y ++){ if (imagecolorat ($src_img, $x, $y) != $rogne_color){ $rogne_point[0] = ($rogne_point[0] > $y)?$y:$rogne_point[0]; $rogne_point[1] = ($rogne_point[1] < $x)?$x:$rogne_point[1]; $rogne_point[2] = ($rogne_point[2] < $y)?$y:$rogne_point[2]; $rogne_point[3] = ($rogne_point[3] > $x)?$x:$rogne_point[3]; } } } $sw = $rogne_point[1] - $rogne_point[3]; $sh = $rogne_point[2] - $rogne_point[0]; $rogne_img = ImageCreateTrueColor ($sw, $sh); ImageCopyResampled ($rogne_img, $src_img, 0, 0, $rogne_point[3], $rogne_point[0], $fw, $fh, $fw, $fh); $src_img = $rogne_img; */ // do not redim the pic if ($dw == false && $dh == false) { $dest_img = ImageCreateTrueColor($sw, $sh); ImageCopyResampled($dest_img, $src_img, 0, 0, 0, 0, $sw, $sh, $sw, $sh); } else { // redim the pix with dest W as max Side if ($dw != 0 && $dh == false) { if ($sw == $sh) { $dh = $dw; } else { if ($sw > $sh) { $dh = round($dw / $sw * $sh); } else { $dh = $dw; $dw = round($dh / $sh * $sw); } } $dest_img = ImageCreateTrueColor($dw, $dh); ImageCopyResampled($dest_img, $src_img, 0, 0, 0, 0, $dw, $dh, $sw, $sh); } else { // redim the pic according to dest W or dest H if ($dw == 0 || $dh == 0) { if ($dw == 0) { $dw = round($dh / $sh * $sw); } else { if ($dh == 0) { $dh = round($dw / $sw * $sh); } } $dest_img = ImageCreateTrueColor($dw, $dh); ImageCopyResampled($dest_img, $src_img, 0, 0, 0, 0, $dw, $dh, $sw, $sh); } else { if ($sw / $sh < $dw / $dh) { $tw = $sw; $th = round($sw / $dw * $dh); $x = 0; $y = round(($sh - $th) / 2); $temp_img = ImageCreateTrueColor($tw, $th); $dest_img = ImageCreateTrueColor($dw, $dh); ImageCopyResampled($temp_img, $src_img, 0, 0, $x, $y, $sw, $sh, $sw, $sh); ImageCopyResampled($dest_img, $temp_img, 0, 0, 0, 0, $dw, $dh, $tw, $th); ImageDestroy($temp_img); } else { $tw = $sw; $th = round($sw * ($dh / $dw)); $x = 0; $y = round(($th - $sh) / 2); $temp_img = ImageCreateTrueColor($tw, $th); $dest_img = ImageCreateTrueColor($dw, $dh); imagefill($temp_img, 0, 0, imagecolorallocate($dest_img, 0, 0, 0)); ImageCopyResampled($temp_img, $src_img, $x, $y, 0, 0, $sw, $sh, $sw, $sh); ImageCopyResampled($dest_img, $temp_img, 0, 0, 0, 0, $dw, $dh, $tw, $th); ImageDestroy($temp_img); } } } } if ($stamp != false) { // detect file type (could be a lot better) $type_stamp = strtoupper(substr($stamp, -3)); // read stamp switch ($type_stamp) { case 'JPG': $stamp_img = ImageCreateFromJpeg($stamp); break; case 'PEG': $stamp_img = ImageCreateFromJpeg($stamp); break; case 'GIF': $stamp_img = ImageCreateFromGif($stamp); break; case 'PNG': $stamp_img = imageCreateFromPng($stamp); break; case 'BMP': $stamp_img = imageCreatefromWBmp($stamp); break; } // get it's info $size = GetImageSize($stamp); $stw = $size[0]; $sth = $size[1]; $sx = $dw - $stw; $sy = $dh - $sth; imagecolortransparent($stamp_img, imageColorAllocate($stamp_img, 0, 0, 0)); imagecopy($dest_img, $stamp_img, $sx, $sy, 0, 0, $stw, $sth); } // free destination if (file_exists($dest_img)) { unlink($dest_img); } // save dest image switch ($type_dest) { case 'JPG': imageJpeg($dest_img, $dest, 90); break; case 'PEG': imageJpeg($dest_img, $dest, 90); break; case 'GIF': imageGif($dest_img, $dest, 90); break; case 'PNG': imagePng($dest_img, $dest, 90); break; case 'BMP': imageWBmp($dest_img, $dest, 90); break; } // free memory imageDestroy($src_img); ImageDestroy($dest_img); }
function imageResize($params, $filePath) { $params["WIDTH"] = !isset($params["WIDTH"]) ? 100 : intval($params["WIDTH"]); $params["HEIGHT"] = !isset($params["HEIGHT"]) ? 100 : intval($params["HEIGHT"]); $params["MODE"] = !isset($params["MODE"]) ? 'inv' : strtolower($params["MODE"]); $params["QUALITY"] = (!isset($params["QUALITY"]) || intval($params["QUALITY"]) <= 0 ) ? 100 : $params["QUALITY"]; $params["HIQUALITY"] = !isset($params["HIQUALITY"]) ? (($params["WIDTH"] <= 200 || $params["HEIGHT"] <= 200) ? 1 : 0 ) : 0; $imageType = getFileExtension($filePath); $pathToOriginalFile = "{$_SERVER["DOCUMENT_ROOT"]}/{$filePath}"; if (!file_exists($pathToOriginalFile)) return; $salt = md5(strtolower($filePath) . implode('_', $params) . $SETSTYLE); $salt = substr($salt, 0, 3) . '/'; $filename = basename($filePath); $pathToFile = $salt . $filename; // если изображение существует if (is_file(CHACHE_IMG_PATH . $pathToFile) == true) { if ($_REQUEST["clear_cache"] == 'IMAGE') { //при очистке кэша unlink(RETURN_IMG_PATH . $pathToFile); } else { return RETURN_IMG_PATH . $pathToFile; } } CheckDirPath(CHACHE_IMG_PATH . $salt); $i = getImageSize($pathToOriginalFile); if (intval($params["WIDTH"]) == 0) $params["WIDTH"] = intval($params["HEIGHT"] / $i[1] * $i[0]); if (intval($params["HEIGHT"]) == 0) $params["HEIGHT"] = intval($params["WIDTH"] / $i[0] * $i[1]); //если вырезаться будет cut проверка размеров if (($params["WIDTH"] > $i[0] || $params["HEIGHT"] > $i[1]) && ($params["MODE"] != "in" && $params["MODE"] != "inv")) { $params["WIDTH"] = $i[0]; $params["HEIGHT"] = $i[1]; } $im = ImageCreateTrueColor($params["WIDTH"], $params["HEIGHT"]); imageAlphaBlending($im, false); switch (strtolower($imageType)) { case 'gif' : $i0 = ImageCreateFromGif($pathToOriginalFile); $icolor = imagecolorallocate($im, 255, 255, 255); imagefill($im, 0, 0, $icolor); break; case 'jpg' : case 'jpeg' : $i0 = ImageCreateFromJpeg($pathToOriginalFile); $icolor = imagecolorallocate($im, 255, 255, 255); imagefill($im, 0, 0, $icolor); break; case 'png' : $i0 = ImageCreateFromPng($pathToOriginalFile); $icolor = imagecolorallocate($im, 255, 255, 255); imagefill($im, 0, 0, $icolor); break; } if (!($i[0] == $params["WIDTH"] && $i[1] == $params["HEIGHT"] && !$SETSTYLE)) { switch (strtolower($params["MODE"])) { case 'cut' : $k_x = $i [0] / $params["WIDTH"]; $k_y = $i [1] / $params["HEIGHT"]; if ($k_x > $k_y) $k = $k_y; else $k = $k_x; $pn["WIDTH"] = $i [0] / $k; $pn["HEIGHT"] = $i [1] / $k; $x = ($params["WIDTH"] - $pn["WIDTH"]) / 2; $y = ($params["HEIGHT"] - $pn["HEIGHT"]) / 2; imageCopyResampled($im, $i0, $x, $y, 0, 0, $pn["WIDTH"] + 2, $pn["HEIGHT"] + 2, $i[0], $i[1]); // ( dst_im, src_im, dstX, dstY, srcX, srcY, int dstW, int dstH, int srcW, int srcH) break; //вписана в квадрат без маштабирования (картинка может быть увеличена больше своего размера) case 'in' : if (($i [0] < $params["WIDTH"]) && ($i [1] < $params["HEIGHT"])) { $k_x = 1; $k_y = 1; } else { $k_x = $i[0] / $params["WIDTH"]; $k_y = $i[1] / $params["HEIGHT"]; } if ($k_x < $k_y) $k = $k_y; else $k = $k_x; $pn["WIDTH"] = intval($i[0] / $k); $pn["HEIGHT"] = intval($i[1] / $k); $x = intval(($params["WIDTH"] - $pn["WIDTH"]) / 2); $y = intval(($params["HEIGHT"] - $pn["HEIGHT"]) / 2); imageCopyResampled($im, $i0, $x, $y, 0, 0, $pn["WIDTH"], $pn["HEIGHT"], $i[0], $i[1]); // 1 первый параметр изборажение источник // 2 изображение которое вставляется // 3 4 -х и у с какой точки будет вставятся в изображении источник // 5 6 - ширина и высота куда будет вписано изображение break; //вписана в квадрат с маштабированием (картинка может быть увеличена) case 'inv' : $k_x = $i [0] / $params["WIDTH"]; $k_y = $i [1] / $params["HEIGHT"]; if ($k_x < $k_y) $k = $k_y; else $k = $k_x; $pn["WIDTH"] = $i [0] / $k; $pn["HEIGHT"] = $i [1] / $k; $x = ($params["WIDTH"] - $pn["WIDTH"]) / 2; $y = ($params["HEIGHT"] - $pn["HEIGHT"]) / 2; imageCopyResampled($im, $i0, $x, $y, 0, 0, $pn["WIDTH"], $pn["HEIGHT"], $i[0], $i[1]); if ($params["WIDTH"] == 55 && $params["HEIGHT"] == 45) { imageAlphaBlending($im, true); $waterMark = ImageCreateFromPng($_SERVER["DOCUMENT_ROOT"] . "/img/video.png"); imageCopyResampled($im, $waterMark, 0, 0, 0, 0, $params["WIDTH"], $params["HEIGHT"], $params["WIDTH"], $params["HEIGHT"]); } break; case 'width' : $factor = $i[1] / $i[0]; // определяем пропорцию height / width if ($factor > 1.35) { $pn["WIDTH"] = $params["WIDTH"]; $scale_factor = $i[0] / $pn["WIDTH"]; // коэфффициент масштабирования $pn["HEIGHT"] = ceil($i[1] / $scale_factor); $x = 0; $y = 0; if (($params["HEIGHT"] / $pn["HEIGHT"]) < 0.6) { //echo 100 / ($pn["HEIGHT"] * 100) / ($params["HEIGHT"] *1.5); $pn["HEIGHT"] = (100 / (($pn["HEIGHT"] * 100) / ($params["HEIGHT"] * 1.3))) * $pn["HEIGHT"]; $newKoef = $i[1] / $pn["HEIGHT"]; $pn["WIDTH"] = $i[0] / $newKoef; $x = ($params["WIDTH"] - $pn["WIDTH"]) / 2; //$y = ($params["HEIGHT"] - $pn["HEIGHT"]) / 2; } imageCopyResampled($im, $i0, $x, $y, 0, 0, $pn["WIDTH"], $pn["HEIGHT"], $i[0], $i[1]); } else { if (($i [0] < $params["WIDTH"]) && ($i [1] < $params["HEIGHT"])) { $k_x = 1; $k_y = 1; } else { $k_x = $i [0] / $params["WIDTH"]; $k_y = $i [1] / $params["HEIGHT"]; } if ($k_x < $k_y) $k = $k_y; else $k = $k_x; $pn["WIDTH"] = $i [0] / $k; $pn["HEIGHT"] = $i [1] / $k; $x = ($params["WIDTH"] - $pn["WIDTH"]) / 2; $y = ($params["HEIGHT"] - $pn["HEIGHT"]) / 2; imageCopyResampled($im, $i0, $x, $y, 0, 0, $params["MODE"], $pn["HEIGHT"], $i[0], $i[1]); } break; default : imageCopyResampled($im, $i0, 0, 0, 0, 0, $params["WIDTH"], $params["HEIGHT"], $i[0], $i[1]); break; } if ($params["HIQUALITY"]) { $sharpenMatrix = array ( array(-1.2, -1, -1.2), array(-1, 20, -1), array(-1.2, -1, -1.2) ); // calculate the sharpen divisor $divisor = array_sum(array_map('array_sum', $sharpenMatrix)); $offset = 0; // apply the matrix imageconvolution($im, $sharpenMatrix, $divisor, $offset); } switch (strtolower($imageType)) { case 'gif' :imageSaveAlpha($im, true); @imageGif($im, CHACHE_IMG_PATH . $pathToFile); break; case 'jpg' : case 'jpeg' : @imageJpeg($im, CHACHE_IMG_PATH . $pathToFile, $params["QUALITY"]); break; case 'png' : imageSaveAlpha($im, true); @imagePng($im, CHACHE_IMG_PATH . $pathToFile); break; } } else { copy($pathToOriginalFile, CHACHE_IMG_PATH . $pathToFile); } return RETURN_IMG_PATH . $pathToFile; }
/** * This function resizes given image, if it has bigger dimensions, than we need and saves it (also makes chmod 0777 on the file) ... * It uses GD or ImageMagick, setting is available to change in CL's config file. * * @param string $inputFileName the input file to work with * @param string $outputFileName the file to write into the final (resized) image * @param integer $maxNewWidth maximal width of image * @param integer $maxNewHeight maximal height of image * @return bool TRUE, if everything was successful (resize and chmod), else FALSE */ function resize($inputFileName, $outputFileName, $maxNewWidth, $maxNewHeight) { $imageInfo = getimagesize($inputFileName); $fileType = $imageInfo['mime']; $extension = strtolower(str_replace('.', '', substr($outputFileName, -4))); $originalWidth = $imageInfo[0]; $originalHeight = $imageInfo[1]; if ($originalWidth > $maxNewWidth or $originalHeight > $maxNewHeight) { $newWidth = $maxNewWidth; $newHeight = $originalHeight / ($originalWidth / $maxNewWidth); if ($newHeight > $maxNewHeight) { $newHeight = $maxNewHeight; $newWidth = $originalWidth / ($originalHeight / $maxNewHeight); } $newWidth = ceil($newWidth); $newHeight = ceil($newHeight); } else { $newWidth = $originalWidth; $newHeight = $originalHeight; } $ok = FALSE; if (CL::getConf('CL_Images/engine') == 'imagick-cli') { exec("convert -thumbnail " . $newWidth . "x" . $newHeight . " " . $inputFileName . " " . $outputFileName); $ok = TRUE; } elseif (CL::getConf('CL_Images/engine') == 'imagick-php') { $image = new Imagick($inputFileName); $image->thumbnailImage($newWidth, $newHeight); $ok = (bool) $image->writeImage($outputFileName); $image->clear(); $image->destroy(); } else { $out = imageCreateTrueColor($newWidth, $newHeight); switch (strtolower($fileType)) { case 'image/jpeg': $source = imageCreateFromJpeg($inputFileName); break; case 'image/png': $source = imageCreateFromPng($inputFileName); break; case 'image/gif': $source = imageCreateFromGif($inputFileName); break; default: break; } imageCopyResized($out, $source, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight); switch (strtolower($extension)) { case 'jpg': case 'jpeg': if (imageJpeg($out, $outputFileName)) { $ok = TRUE; } break; case 'png': if (imagePng($out, $outputFileName)) { $ok = TRUE; } break; case 'gif': if (imageGif($out, $outputFileName)) { $ok = TRUE; } break; default: break; } imageDestroy($out); imageDestroy($source); } if ($ok and chmod($outputFileName, 0777)) { return TRUE; } else { return FALSE; } }
$randW = mt_rand(0, imageSX($im)); $randH = mt_rand(0, imageSY($im)); imageSetPixel($im, $randW, $randH, $color); } imageSetThickness($im, 2); $color = imageColorAllocate($im, 100, 100, 100); imageLine($im, 10, 30, 130, 20, $color); $color = imageColorAllocate($im, 70, 70, 70); $n1 = mt_rand(0, 9); imageTtfText($im, 25, 10, mt_rand(2, 10), mt_rand(25, 45), $color, "times.ttf", $n1); $color = imageColorAllocate($im, 255, 0, 50); $str = "ABCDIFGHIJKLMNOPKASTUVWXYZ"; $nw = mt_rand(0, 15); $n2 = $str[$nw]; imageTtftext($im, 22, -10, mt_rand(25, 35), mt_rand(25, 45), $color, "times.ttf", $n2); $color = imageColorAllocate($im, 50, 50, 50); $n3 = mt_rand(0, 9); imageTtfText($im, 25, 15, mt_rand(60, 70), mt_rand(25, 45), $color, "times.ttf", $n3); $color = imageColorAllocate($im, 250, 250, 250); $nw2 = mt_rand(15, 25); $n4 = $str[$nw2]; imageTtfText($im, 22, 30, mt_rand(90, 100), mt_rand(25, 45), $color, "times.ttf", $n4); $color = imageColorAllocate($im, 255, 220, 70); $n5 = mt_rand(0, 9); imageTtfText($im, 25, -20, mt_rand(115, 125), mt_rand(25, 45), $color, "times.ttf", $n5); $n = $n1 . $n2 . $n3 . $n4 . $n5; session_start(); $_SESSION['kap'] = md5(strtolower($n)); header("Content-type: image/jpeg"); imageJpeg($im); imageDestroy($im);
/** * Generate images of alternate sizes. */ function resizeImage($cnvrt_arry) { global $platform, $imgs, $cnvrt_path, $reqd_image, $convert_writable, $convert_magick, $convert_GD, $convert_cmd, $cnvrt_alt, $cnvrt_mesgs, $compat_quote; if (empty($imgs) || $convert_writable == FALSE) { return; } if ($convert_GD == TRUE && !($gd_version = gdVersion())) { return; } if ($cnvrt_alt['no_prof'] == TRUE) { $strip_prof = ' +profile "*"'; } else { $strip_prof = ''; } if ($cnvrt_alt['mesg_on'] == TRUE) { $str = ''; } foreach ($imgs as $img_file) { if ($cnvrt_alt['indiv'] == TRUE && $img_file != $reqd_image['file']) { continue; } $orig_img = $reqd_image['pwd'] . '/' . $img_file; $cnvrtd_img = $cnvrt_path . '/' . $cnvrt_arry['prefix'] . $img_file; if (!is_file($cnvrtd_img)) { $img_size = GetImageSize($orig_img); $height = $img_size[1]; $width = $img_size[0]; $area = $height * $width; $maxarea = $cnvrt_arry['maxwid'] * $cnvrt_arry['maxwid'] * 0.9; $maxheight = $cnvrt_arry['maxwid'] * 0.75 + 1; if ($area > $maxarea || $width > $cnvrt_arry['maxwid'] || $height > $maxheight) { if ($width / $cnvrt_arry['maxwid'] >= $height / $maxheight) { $dim = 'W'; } if ($height / $maxheight >= $width / $cnvrt_arry['maxwid']) { $dim = 'H'; } if ($dim == 'W') { $cnvt_percent = round(0.9375 * $cnvrt_arry['maxwid'] / $width * 100, 2); } if ($dim == 'H') { $cnvt_percent = round(0.75 * $cnvrt_arry['maxwid'] / $height * 100, 2); } // convert it if ($convert_magick == TRUE) { // Image Magick image conversion if ($platform == 'Win32' && $compat_quote == TRUE) { $winquote = '"'; } else { $winquote = ''; } exec($winquote . $convert_cmd . ' -geometry ' . $cnvt_percent . '%' . ' -quality ' . $cnvrt_arry['qual'] . ' -sharpen ' . $cnvrt_arry['sharpen'] . $strip_prof . ' "' . $orig_img . '"' . ' "' . $cnvrtd_img . '"' . $winquote); $using = $cnvrt_mesgs['using IM']; } elseif ($convert_GD == TRUE) { // GD image conversion if (eregi('\\.jpg$|\\.jpeg$', $img_file) == TRUE && (imageTypes() & IMG_JPG) == TRUE) { $src_img = imageCreateFromJpeg($orig_img); } elseif (eregi('\\.gif$', $img_file) == TRUE && (imageTypes() & IMG_PNG) == TRUE) { $src_img = imageCreateFromPng($orig_img); } elseif (eregi('\\.gif$', $img_file) == TRUE && (imageTypes() & IMG_GIF) == TRUE) { $src_img = imageCreateFromGif($orig_img); } else { continue; } $src_width = imageSx($src_img); $src_height = imageSy($src_img); $dest_width = $src_width * ($cnvt_percent / 100); $dest_height = $src_height * ($cnvt_percent / 100); if ($gd_version >= 2) { $dst_img = imageCreateTruecolor($dest_width, $dest_height); imageCopyResampled($dst_img, $src_img, 0, 0, 0, 0, $dest_width, $dest_height, $src_width, $src_height); } else { $dst_img = imageCreate($dest_width, $dest_height); imageCopyResized($dst_img, $src_img, 0, 0, 0, 0, $dest_width, $dest_height, $src_width, $src_height); } imageDestroy($src_img); if (eregi('\\.jpg$|\\.jpeg$/i', $img_file) == TRUE && (imageTypes() & IMG_JPG) == TRUE) { imageJpeg($dst_img, $cnvrtd_img, $cnvrt_arry['qual']); } elseif (eregi('\\.gif$', $img_file) == TRUE && (imageTypes() & IMG_PNG) == TRUE) { imagePng($dst_img, $cnvrtd_img); } elseif (eregi('\\.gif$/i', $img_file) == TRUE && (imageTypes() & IMG_GIF) == TRUE) { imageGif($dst_img, $cnvrtd_img); } imageDestroy($dst_img); $using = $cnvrt_mesgs['using GD'] . $gd_version; } if ($cnvrt_alt['mesg_on'] == TRUE && is_file($cnvrtd_img)) { $str .= " <small>\n" . ' ' . $cnvrt_mesgs['generated'] . $cnvrt_arry['txt'] . $cnvrt_mesgs['converted'] . $cnvrt_mesgs['image_for'] . $img_file . $using . ".\n" . " </small>\n <br />\n"; } } } } if (isset($str)) { return $str; } }
public static function convert($srcFile = null, $destFile = null, $width = 0, $height = 0, $mode = self::MODE_CUT) { if (false === file_exists($srcFile)) { return false; } preg_match('/\\.([^\\.]+)$/', $destFile, $matches); switch (strtolower($matches[1])) { case 'jpg': case 'jpeg': $saveType = self::TYPE_JPG; break; case 'gif': $saveType = self::TYPE_GIF; break; case 'png': $saveType = self::TYPE_PNG; break; default: $saveType = self::TYPE_JPG; } $type = self::getImageType($srcFile); $srcImage = null; switch ($type) { case self::TYPE_GIF: $srcImage = imageCreateFromGif($srcFile); break; case self::TYPE_JPG: $srcImage = imageCreateFromJpeg($srcFile); break; case self::TYPE_PNG: $srcImage = imageCreateFromPng($srcFile); break; default: return false; } $srcWidth = imageSX($srcImage); $srcHeight = imageSY($srcImage); if ($width == 0 && $height == 0) { $width = $srcWidth; $height = $srcHeight; $mode = self::MODE_SCALE; } else { if ($width > 0 & $height == 0) { $useWidth = true; $mode = self::MODE_SCALE; if ($srcWidth <= $width) { return self::saveFile($srcImage, $destFile, $saveType); } } else { if ($width == 0 && $height > 0) { $mode = self::MODE_SCALE; } } } if ($mode == self::MODE_SCALE) { if ($width > 0 & $height > 0) { $useWidth = $srcWidth * $height > $srcHeight * $width ? true : false; } if (isset($useWidth) && $useWidth == true) { $height = $srcHeight * $width / $srcWidth; } else { $width = $srcWidth * $height / $srcHeight; } } $destImage = imageCreateTrueColor($width, $height); if ($mode == self::MODE_CUT) { $useWidth = $srcWidth * $height > $srcHeight * $width ? false : true; if ($useWidth == true) { $tempWidth = $width; $tempHeight = $srcHeight * $tempWidth / $srcWidth; } else { $tempHeight = $height; $tempWidth = $srcWidth * $tempHeight / $srcHeight; } $tempImage = imageCreateTrueColor($tempWidth, $tempHeight); $srcImage = imageCopyResampled($tempImage, $srcImage, 0, 0, 0, 0, $tempWidth, $tempHeight, $srcWidth, $srcHeight); imageDestroy($srcImage); $srcImage = $tempImage; $srcWidth = $width; $srcHeight = $srcWidth * $width / $srcHeight; } if ($mode == self::MODE_SCALE) { imageCopyResampled($destImage, $srcImage, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight); } else { imageCopyResampled($destImage, $srcImage, 0, 0, 0, 0, $width, $height, $width, $height); } @imageDestroy($srcImage); ob_start(); // output the image as a file to the output stream imageJpeg($destImage); //Read the output buffer $buffer = ob_get_contents(); //clear the buffer ob_end_clean(); return file_put_contents($destFile, $buffer); }
<?php ## Увеличение картинки со сглаживанием. $tile = imageCreateFromJpeg("sample1.jpg"); $im = imageCreateTrueColor(800, 600); imageFill($im, 0, 0, imageColorAllocate($im, 0, 255, 0)); imageSetTile($im, $tile); // Создаем массив точек со случайными координатами. $p = []; for ($i = 0; $i < 4; $i++) { array_push($p, mt_rand(0, imageSX($im)), mt_rand(0, imageSY($im))); } // Рисуем закрашенный многоугольник. imageFilledPolygon($im, $p, count($p) / 2, IMG_COLOR_TILED); // Выводим результат. header("Content-type: image/jpeg"); // Выводим картинку с максимальным качеством (100). imageJpeg($im, '', 100); // Можно было сжать с помощью PNG. #header("Content-type: image/png"); #imagePng($im);
imageRectangle ($dst_im, 0, 0, ($re_size[0]-1), ($re_size[1]-1), $black); header("content-Type: image/png"); imagepng($dst_im); imagedestroy($src_im); imagedestroy($dst_im); } */ ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // jpg形式 case "2": $src_im = imageCreateFromJpeg($photo_path); $dst_im = $imagecreate($re_size[0], $re_size[1]); $imageresize($dst_im, $src_im, 0, 0, 0, 0, $re_size[0], $re_size[1], $size[0], $size[1]); header("content-Type: image/jpeg"); header("cache-control: no-cache"); imageJpeg($dst_im); imagedestroy($src_im); imagedestroy($dst_im); break; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // png形式 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // png形式 case "3": $src_im = imagecreatefrompng($photo_path); $colortransparent = imagecolortransparent($src_im); if ($colortransparent > -1) { $dst_im = $imagecreate($re_size[0], $re_size[1]); imagepalettecopy($dst_im, $src_im); imagefill($dst_im, 0, 0, $colortransparent); imagecolortransparent($dst_im, $colortransparent);
function saveImage($path, $quality = 75) { if (!$this->image) { return FALSE; } $fp = fopen($path, "w"); if (!$fp) { return FALSE; } else { fclose($fp); if (!imageJpeg($this->image, $path, $quality)) { return FALSE; } else { return TRUE; } } }
<?php ## Увеличение картинки со сглаживанием. $from = imageCreateFromJpeg("sample2.jpg"); $to = imageCreateTrueColor(2000, 2000); imageCopyResampled($to, $from, 0, 0, 0, 0, imageSX($to), imageSY($to), imageSX($from), imageSY($from)); header("Content-type: image/jpeg"); imageJpeg($to);
function showCartoonfy($p_ext, $p_dis) { switch (strtolower($p_ext)) { case "jpg": header('Content-type:image/' . strtolower($p_ext)); if ($p_dis) { header('Content-disposition:attachment;filename=' . time() . '.' . strtolower($p_ext)); } imageJpeg($this->i1); break; case "jpeg": header('Content-type:image/' . strtolower($p_ext)); if ($p_dis) { header('Content-disposition:attachment;filename=' . time() . '.' . strtolower($p_ext)); } imageJpeg($this->i1); break; case "gif": header('Content-type:image/' . strtolower($p_ext)); if ($p_dis) { header('Content-disposition:attachment;filename=' . time() . '.' . strtolower($p_ext)); } imageGif($this->i1); break; case "png": header('Content-type:image/' . strtolower($p_ext)); if ($p_dis) { header('Content-disposition:attachment;filename=' . time() . '.' . strtolower($p_ext)); } imagePng($this->i1); break; default: print "<b>" . $p_ext . "</b> is not supported image format!"; exit; } imageDestroy($this->i1); }