/** * Contructor method. Will create a new image from the target file. * Accepts an image filename as a string. Method also works out how * big the image is and stores this in the $image array. * * @param string $imgFile The image filename. */ public function ImageManipulation($imgfile) { //detect image format $this->image["format"] = strtolower(substr(strrchr($imgfile, '.'), 1)); $this->image["format"] = strtoupper($this->image["format"]); // convert image into usable format. if ($this->image["format"] == "JPG" || $this->image["format"] == "JPEG") { //JPEG $this->image["format"] = "JPEG"; $this->image["src"] = ImageCreateFromJPEG($imgfile); } elseif ($this->image["format"] == "PNG") { //PNG $this->image["format"] = "PNG"; $this->image["src"] = imagecreatefrompng($imgfile); } elseif ($this->image["format"] == "GIF") { //GIF $this->image["format"] = "GIF"; $this->image["src"] = ImageCreateFromGif($imgfile); } elseif ($this->image["format"] == "WBMP") { //WBMP $this->image["format"] = "WBMP"; $this->image["src"] = ImageCreateFromWBMP($imgfile); } else { //DEFAULT return false; } // Image is ok $this->imageok = true; // Work out image size $this->image["sizex"] = imagesx($this->image["src"]); $this->image["sizey"] = imagesy($this->image["src"]); }
function pcs_href_image($src_path) { $strRet = DIR_WS_IMAGES . 'pcs_images/' . basename($src_path) . '_' . MODULE_ADDONS_PCSLIDESHOW_MAX_IMAGE_HEIGHT . '_' . MODULE_ADDONS_PCSLIDESHOW_MAX_IMAGE_WIDTH . '_' . MODULE_ADDONS_PCSLIDESHOW_IMAGE_QUALITY . '.jpg'; #This will be the filename of the resized image. if (!file_exists($strRet)) { #Create the file if it does not exist #check to see if source file exists if (!file_exists($src_path)) { return 'error1'; #check to see if source file is readable } elseif (!is_readable($src_path)) { return 'error2'; } #check if gif if (stristr(strtolower($src_path), '.gif')) { $oldImage = ImageCreateFromGif($src_path); } elseif (stristr(strtolower($src_path), '.jpg') || stristr(strtolower($src_path), '.jpeg')) { $oldImage = ImageCreateFromJpeg($src_path); } elseif (stristr(strtolower($src_path), '.png')) { $oldImage = ImageCreateFromPng($src_path); } else { return 'error3'; } #Create the new image if (function_exists("ImageCreateTrueColor")) { $newImage = ImageCreateTrueColor(MODULE_ADDONS_PCSLIDESHOW_MAX_IMAGE_WIDTH, MODULE_ADDONS_PCSLIDESHOW_MAX_IMAGE_HEIGHT); } else { $newImage = ImageCreate(MODULE_ADDONS_PCSLIDESHOW_MAX_IMAGE_WIDTH, MODULE_ADDONS_PCSLIDESHOW_MAX_IMAGE_HEIGHT); } $backgroundColor = imagecolorallocate($newImage, 255, 255, 255); imagefill($newImage, 0, 0, $backgroundColor); #calculate the rezised image's dimmensions if (imagesx($oldImage) > MODULE_ADDONS_PCSLIDESHOW_MAX_IMAGE_WIDTH || imagesy($oldImage) > MODULE_ADDONS_PCSLIDESHOW_MAX_IMAGE_HEIGHT) { #Resize image if (imagesx($oldImage) / MODULE_ADDONS_PCSLIDESHOW_MAX_IMAGE_WIDTH > imagesy($oldImage) / MODULE_ADDONS_PCSLIDESHOW_MAX_IMAGE_HEIGHT) { #Width is leading in beeing to large $newWidth = (int) MODULE_ADDONS_PCSLIDESHOW_MAX_IMAGE_WIDTH; $newHeight = (int) MODULE_ADDONS_PCSLIDESHOW_MAX_IMAGE_WIDTH / imagesx($oldImage) * imagesy($oldImage); } else { #Height is leading in beeing to large $newHeight = (int) MODULE_ADDONS_PCSLIDESHOW_MAX_IMAGE_HEIGHT; $newWidth = (int) MODULE_ADDONS_PCSLIDESHOW_MAX_IMAGE_HEIGHT / imagesy($oldImage) * imagesx($oldImage); } } else { #Don't rezise image $newWidth = imagesx($oldImage); $newHeight = imagesy($oldImage); } #Copy the old image onto the new image ImageCopyResampled($newImage, $oldImage, MODULE_ADDONS_PCSLIDESHOW_MAX_IMAGE_WIDTH / 2 - $newWidth / 2, MODULE_ADDONS_PCSLIDESHOW_MAX_IMAGE_HEIGHT / 2 - $newHeight / 2, 0, 0, $newWidth, $newHeight, imagesx($oldImage), imagesy($oldImage)); imagejpeg($newImage, $strRet, MODULE_ADDONS_PCSLIDESHOW_IMAGE_QUALITY); #save the image imagedestroy($oldImage); #Free Memory imagedestroy($newImage); #Free memory } return $strRet; }
function ResizeImage($Filename, $Thumbnail, $Size) { $Path = pathinfo($Filename); $Extension = $Path['extension']; $ImageData = @GetImageSize($Filename); $Width = $ImageData[0]; $Height = $ImageData[1]; if ($Width >= $Height and $Width > $Size) { $NewWidth = $Size; $NewHeight = $Size / $Width * $Height; } elseif ($Height >= $Width and $Height > $Size) { $NewWidth = $Size / $Height * $Width; $NewHeight = $Size; } else { $NewWidth = $Width; $NewHeight = $Height; } $NewImage = @ImageCreateTrueColor($NewWidth, $NewHeight); if (preg_match('/^gif$/i', $Extension)) { $Image = @ImageCreateFromGif($Filename); } elseif (preg_match('/^png$/i', $Extension)) { $Image = @ImageCreateFromPng($Filename); } else { $Image = @ImageCreateFromJpeg($Filename); } if ($ImageData[2] == IMAGETYPE_GIF or $ImageData[2] == IMAGETYPE_PNG) { $TransIndex = imagecolortransparent($Image); // If we have a specific transparent color if ($TransIndex >= 0) { // Get the original image's transparent color's RGB values $TransColor = imagecolorsforindex($Image, $TransIndex); // Allocate the same color in the new image resource $TransIndex = imagecolorallocate($NewImage, $TransColor['red'], $TransColor['green'], $TransColor['blue']); // Completely fill the background of the new image with allocated color. imagefill($NewImage, 0, 0, $TransIndex); // Set the background color for new image to transparent imagecolortransparent($NewImage, $TransIndex); } elseif ($ImageData[2] == IMAGETYPE_PNG) { // Turn off transparency blending (temporarily) imagealphablending($NewImage, false); // Create a new transparent color for image $color = imagecolorallocatealpha($NewImage, 0, 0, 0, 127); // Completely fill the background of the new image with allocated color. imagefill($NewImage, 0, 0, $color); // Restore transparency blending imagesavealpha($NewImage, true); } } @ImageCopyResampled($NewImage, $Image, 0, 0, 0, 0, $NewWidth, $NewHeight, $Width, $Height); if (preg_match('/^gif$/i', $Extension)) { @ImageGif($NewImage, $Thumbnail); } elseif (preg_match('/^png$/i', $Extension)) { @ImagePng($NewImage, $Thumbnail); } else { @ImageJpeg($NewImage, $Thumbnail); } @chmod($Thumbnail, 0644); }
public static function createFromFile($filename, $mime_type, $objAlbum) { $objPicture = new clsPicture(); /* Decide which incoming mime type it is. */ switch ($mime_type) { case 'image/jpeg': $img = ImageCreateFromJpeg($filename); break; case 'image/png': $img = ImageCreateFromPng($filename); break; case 'image/gif': $img = ImageCreateFromGif($filename); break; default: return 'image_filetype'; } list($intWidth, $intHeight) = getImageSize($filename); $intMaxWidth = $objAlbum->get('max_width'); $intMaxHeight = $objAlbum->get('max_height'); if ($intMaxWidth <= 0) { $intMaxWidth = DEFAULT_X; } if ($intMaxHeight <= 0) { $intMaxHeight = DEFAULT_Y; } if ($intWidth > $intMaxWidth || $intHeight > $intMaxHeight) { /* Check whether the image needs to be resized vertically or horizonally more. */ if ($intWidth / $intMaxWidth > $intHeight / $intMaxHeight) { /* Right-left needs to have priority. */ $ratio = $intMaxWidth / $intWidth; } else { /* Up-down needs to have priority. */ $ratio = $intMaxHeight / $intHeight; } $intNewWidth = $intWidth * $ratio; $intNewHeight = $intHeight * $ratio; $imgNew = @ImageCreateTrueColor($intNewWidth, $intNewHeight); if (!@ImageCopyResized($imgNew, $img, 0, 0, 0, 0, $intNewWidth, $intNewHeight, $intWidth, $intHeight)) { return "image_noresize"; } $intWidth = $intNewWidth; $intHeight = $intNewHeight; ImageDestroy($img); $img = $imgNew; } /* This has to be done before setImage() because setImage() needs data from the album. */ $objPicture->set('album_id', $objAlbum->get('id')); $result = $objPicture->setImage($img); ImageDestroy($img); if ($result) { return $result; } $objPicture->set('width', $intWidth); $objPicture->set('height', $intHeight); $objPicture->save(); return $objPicture; }
public function __construct($fileName) { // garante que a biblioteca GD está instalado if (!function_exists("gd_info")) { echo 'Você não tem a biblioteca GD instalada. Esta classe exige a biblioteca GD para funcionar corretamente.'; exit; } // inicializar variáveis $this->errmsg = ''; $this->error = false; $this->currentDimensions = array(); $this->newDimensions = array(); $this->fileName = $fileName; $this->imageMeta = array(); $this->percent = 100; $this->maxWidth = 0; $this->maxHeight = 0; // verifique se o arquivo existe if (!file_exists($this->fileName)) { $this->errmsg = 'Arquivo não encontrado'; $this->error = true; } elseif (!is_readable($this->fileName)) { $this->errmsg = 'O arquivo não é legível'; $this->error = true; } //inicializar os recursos se não houver erros if ($this->error == false) { switch (exif_imagetype($this->fileName)) { case 1: $this->format = "GIF"; $this->oldImage = ImageCreateFromGif($this->fileName); break; case 2: $this->format = "JPG"; $this->oldImage = @ImageCreateFromJpeg($this->fileName); break; case 3: $this->format = "PNG"; $this->oldImage = ImageCreateFromPng($this->fileName); break; default: $this->errmsg = 'formato de arquivo desconhecido'; $this->error = true; break; } $size = GetImageSize($this->fileName); $this->currentDimensions = array('width' => $size[0], 'height' => $size[1]); $this->newImage = $this->oldImage; $this->gatherImageMeta(); } if ($this->error == true) { $this->showErrorImage(); // break; } }
public static function CreateGifThumbnail($imageDirectory, $imageName, $thumbDirectory, $thumbWidth) { $srcImg = ImageCreateFromGif($imageDirectory . $imageName); $origWidth = imagesx($srcImg); $origHeight = imagesy($srcImg); $ratio = $thumbWidth / $origWidth; $thumbHeight = $origHeight * $ratio; $thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight); imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, imagesx($srcImg), imagesy($srcImg)); imageGif($thumbImg, $thumbDirectory . "tn_" . $imageName); }
private static function img_resizer($src, $quality, $w, $h, $saveas) { /* v2.5 with auto crop */ $r = 1; $e = strtolower(substr($src, strrpos($src, ".") + 1, 3)); if ($e == "jpg" || $e == "jpeg") { $OldImage = imagecreatefromjpeg($src) or $r = 0; } elseif ($e == "gif") { $OldImage = ImageCreateFromGif($src) or $r = 0; } elseif ($e == "bmp") { $OldImage = ImageCreateFromwbmp($src) or $r = 0; } elseif ($e == "png") { $OldImage = ImageCreateFromPng($src) or $r = 0; } else { _o("No es una imagen válida! (" . $e . ") -- " . $src); $r = 0; } if ($r) { list($width, $height) = getimagesize($src); // check if ratios match $_ratio = array($width / $height, $w / $h); if ($_ratio[0] != $_ratio[1]) { // crop image // find the right scale to use $_scale = min((double) ($width / $w), (double) ($height / $h)); // coords to crop $cropX = (double) ($width - $_scale * $w); $cropY = (double) ($height - $_scale * $h); // cropped image size $cropW = (double) ($width - $cropX); $cropH = (double) ($height - $cropY); $crop = ImageCreateTrueColor($cropW, $cropH); // crop the middle part of the image to fit proportions ImageCopy($crop, $OldImage, 0, 0, (int) ($cropX / 2), (int) ($cropY / 2), $cropW, $cropH); } // do the thumbnail $NewThumb = ImageCreateTrueColor($w, $h); if (isset($crop)) { // been cropped ImageCopyResampled($NewThumb, $crop, 0, 0, 0, 0, $w, $h, $cropW, $cropH); ImageDestroy($crop); } else { // ratio match, regular resize ImageCopyResampled($NewThumb, $OldImage, 0, 0, 0, 0, $w, $h, $width, $height); } _ckdir($saveas); ImageJpeg($NewThumb, $saveas, $quality); ImageDestroy($NewThumb); ImageDestroy($OldImage); } return $r; }
private function createimageByType($data, $file) { if ($data['type'] === "image/jpeg") { $image = ImageCreateFromJpeg($file); } if ($data['type'] === "image/png") { $image = ImageCreateFromPng($file); } if ($data['type'] === "image/gif") { $image = ImageCreateFromGif($file); } return $image; }
private function create_image_container($file, $type) { $path = $this->config->item("upload_dir"); if (strtolower($type) === ".jpg" || strtolower($type) === ".jpeg") { $image = ImageCreateFromJpeg($path . $file . $type); } elseif (strtolower($type) === ".png") { $image = ImageCreateFromPng($path . $file . $type); } elseif (strtolower($type) === ".gif") { $image = ImageCreateFromGif($path . $file . $type); } else { $image = false; } return $image; }
function ImageCreateFromType($type,$filename) { $im = null; switch ($type) { case 1: $im = ImageCreateFromGif($filename); break; case 2: $im = ImageCreateFromJpeg($filename); break; case 3: $im = ImageCreateFromPNG($filename); break; } return $im; }
function image_resize($upfile, $output_filename, $output_path, $dst_w = 100, $dst_h = 100, $isRadio = 1, $trans_color = array(254, 254, 254)) { $imagedata = GetImageSize($upfile); // Read the size $src_w = $imagedata[0]; $src_h = $imagedata[1]; $src_type = $imagedata[2]; $re_dst_x = 0; $re_dst_y = 0; if ($isRadio | 0 > 0) { if ($dst_w >= $src_w && $dst_h >= $src_h) { $re_dst_w = $src_w; $re_dst_h = $src_h; } else { $p_w = $dst_w / $src_w; $p_h = $dst_h / $src_h; $p = min($p_w, $p_h); $re_dst_w = $src_w * $p; $re_dst_h = $src_h * $p; } } else { $re_dst_w = $dst_w; $re_dst_h = $dst_h; } if ($src_type == 1) { $src_image = ImageCreateFromGif($upfile); } else { if ($src_type == 2) { $src_image = ImageCreateFromJpeg($upfile); } else { if ($src_type == 3) { $src_image = ImageCreateFromPng($upfile); } else { if ($src_type == 16) { $src_image = imagecreatefromxbm($upfile); } } } } //else if ($src_type==6) // return; $dst_image = imagecreatetruecolor($re_dst_w, $re_dst_h); $bgc = imagecolorallocate($dst_image, $trans_color[0], $trans_color[1], $trans_color[2]); imagefilledrectangle($dst_image, 0, 0, $re_dst_w, $re_dst_h, $bgc); imagecolortransparent($dst_image, $bgc); imagecopyresampled($dst_image, $src_image, $re_dst_x, $re_dst_y, 0, 0, $re_dst_w, $re_dst_h, $src_w, $src_h); imagepng($dst_image, $output_path . $output_filename); }
private function getImage($imageUrl) { if (!file_get_contents($imageUrl)) { throw new \Exception("Image not found"); } $ext = strtolower(array_pop(explode('.', $imageUrl))); if ($ext == "jpeg" || $ext == "jpg") { return ImageCreateFromJpeg($imageUrl); } elseif ($ext == "gif") { return ImageCreateFromGif($imageUrl); } elseif ($ext == "png") { return ImageCreateFromPng($imageUrl); } else { throw new \Exception("Image not supported"); } }
/** * Contructor method. Will create a new image from the target file. * Accepts an image filename as a string. Method also works out how * big the image is and stores this in the $image array. * * @param string $imgFile The image filename. */ public function ImageManipulation($imgfile) { $imageinfo = getimagesize($imgfile); // debugLog($imageinfo); //detect image format //@todo: abstract use mime, and realpathparts not regex $this->image["format"] = $this->getFileImageType($imgfile); // convert image into usable format. if ($this->image["format"] == "JPG" || $this->image["format"] == "JPEG") { //JPEG $this->image["format"] = "JPEG"; $this->image["src"] = ImageCreateFromJPEG($imgfile); } elseif ($this->image["format"] == "PNG") { //PNG $this->image["format"] = "PNG"; $this->image["src"] = imagecreatefrompng($imgfile); } elseif ($this->image["format"] == "GIF") { //GIF $this->image["format"] = "GIF"; $this->image["src"] = ImageCreateFromGif($imgfile); } elseif ($this->image["format"] == "WBMP") { //WBMP $this->image["format"] = "WBMP"; $this->image["src"] = ImageCreateFromWBMP($imgfile); } else { //DEFAULT $this->imageok = false; return false; } // Image is ok $this->imageok = true; // Work out image size $this->image['srcfile'] = $imgfile; $this->image['sizex'] = $imageinfo[0]; $this->image['sizey'] = $imageinfo[1]; $this->image['channels'] = $imageinfo[2]; $this->image['bits'] = $imageinfo['bits']; $this->image['mime'] = $imageinfo['mime']; $this->image['width'] = $this->image["sizex"]; $this->image['height'] = $this->image["sizey"]; $this->image["ratio"] = $this->getRatio(); }
/** * Liefert ein Image mit dem Bild aus $dir und $filename. */ function twHoleImg($dir, $filename) { $dirMitFilename = $dir . $filename; if (stristr($filename, ".jpg") == true || stristr($datei, ".jpeg") == true) { if (!($im = ImageCreateFromJPEG($dirMitFilename))) { echo "Fehler beim laden des Upload-Bildes '" . $dirMitFilename . "'!<br />"; } } else { if (stristr($filename, ".gif") == true) { if (!($im = ImageCreateFromGif($dirMitFilename))) { echo "Fehler beim laden des Upload-Bildes '" . $dirMitFilename . "'!<br />"; } } else { if (stristr($filename, ".png") == true) { if (!($im = ImageCreateFromPng($dirMitFilename))) { echo "Fehler beim laden des Upload-Bildes '" . $dirMitFilename . "'!<br />"; } } else { echo "Fehler: das ist kein Bildformat: '" . $filename . "'!"; } } } // Fehler-Bild if ($im == "") { /* $im = ImageCreate (150, 30); $bgc = ImageColorAllocate ($im, 255, 255, 255); $tc = ImageColorAllocate ($im, 0, 0, 0); ImageFilledRectangle ($im, 0, 0, 150, 30, $bgc); ImageString($im, 1, 5, 5, "Fehler beim Öffnen von: $dateiMitPfad", $tc); */ return false; } else { return $im; } }
function DImage($img_src, $img_dest, $max_w = 120, $max_h = 90, $qualite = 80, $crop_from_center = 0) { //ne lit pas l'image source ! if (!function_exists('ImageCreateTrueColor')) { return 0; } if (!is_file($img_src)) { db("!is_file({$img_src})"); return; } $startX = $startY = 0; #return; $size = @GetImageSize($img_src); $src_w = $size[0]; $src_h = $size[1]; $type = $size[2]; $ratio = @round($src_w / $src_h, 2); #$_ENV['db'].="<li>".pre($size); if ($max_w > $src_w) { copy($img_src, $img_dest); return; } #ne pas redimensioner si plus petit $ratiom = round($max_w / $max_h, 2); if ($ratio > $ratiom) { $dst_w = $max_w; $dst_h = ceil($max_w / $ratio); } else { $dst_h = $max_h; $dst_w = ceil($max_h * $ratio); } #if($dst_w==0){$_GET[debug].="<li>$img_dest $ratio> $ratiom? $dst_w $dst_h".($max_h*$rationm);return;} gt(); $dst_im = ImageCreateTrueColor($dst_w, $dst_h); // Copie dedans l'image initiale redimensionnée if (!$dst_im) { $_ENV['db'] .= "<li>{$img_dest} {$ratio}> {$ratiom}? {$type}--- FAIL {$dst_w} {$dst_h}"; return; } switch ($type) { case 3: $src_im = @ImageCreateFromPng($img_src); break; case 2: $src_im = @ImageCreateFromJpeg($img_src); break; case 1: $src_im = @ImageCreateFromGif($img_src); break; } if (!$src_im) { echo "{$img_src},{$img_dest},{$dst_w},{$dst_h},{$type},{$src_w},{$src_h}, {$type},<hr>Erreur d'upload de photo pour cause de Format JPEG Pourri !"; } ReMapTree($img_dest); if (imagecopyresized($dst_im, $src_im, 0, 0, $startX, $startY, $dst_w, $dst_h, $src_w, $src_h)) { $_ENV['db'] .= " Miniature Générée"; } //RESIZE TO 640 ELSE INCLUS switch ($type) { case 1: ImageGif($dst_im, $img_dest); break; case 2: ImageJpeg($dst_im, $img_dest, $qualite); break; case 3: ImagePng($dst_im, $img_dest, 9); break; } ImageDestroy($dst_im); ImageDestroy($src_im); $_ENV['db'] .= "<li>{$dst_w},{$dst_h},{$src_w},{$src_h} {$img_dest} {$ratiom}={$ratio} {$type} -"; return; // Détruis les tampons }
/** * Class constructor * * @param string $fileName * @return Thumbnail */ public function __construct($fileName) { //make sure the GD library is installed if (!function_exists("gd_info")) { echo 'You do not have the GD Library installed. This class requires the GD library to function properly.' . "\n"; echo 'visit http://us2.php.net/manual/en/ref.image.php for more information'; exit; } //initialize variables $this->errmsg = ''; $this->error = false; $this->currentDimensions = array(); $this->newDimensions = array(); $this->fileName = $fileName; $this->imageMeta = array(); $this->percent = 100; $this->maxWidth = 0; $this->maxHeight = 0; //check to see if file exists if (!file_exists($this->fileName)) { $this->errmsg = 'File not found'; $this->error = true; } elseif (!is_readable($this->fileName)) { $this->errmsg = 'File is not readable'; $this->error = true; } //if there are no errors, determine the file format if ($this->error == false) { //check if gif if (stristr(strtolower($this->fileName), '.gif')) { $this->format = 'GIF'; } elseif (stristr(strtolower($this->fileName), '.jpg') || stristr(strtolower($this->fileName), '.jpeg')) { $this->format = 'JPG'; } elseif (stristr(strtolower($this->fileName), '.png')) { $this->format = 'PNG'; } else { $this->errmsg = 'Unknown file format'; $this->error = true; } } //initialize resources if no errors if ($this->error == false) { switch ($this->format) { case 'GIF': $this->oldImage = ImageCreateFromGif($this->fileName); break; case 'JPG': $this->oldImage = ImageCreateFromJpeg($this->fileName); break; case 'PNG': $this->oldImage = ImageCreateFromPng($this->fileName); break; } $size = GetImageSize($this->fileName); $this->currentDimensions = array('width' => $size[0], 'height' => $size[1]); $this->newImage = $this->oldImage; $this->gatherImageMeta(); } if ($this->error == true) { $this->showErrorImage(); break; } }
/** * * @param string $psImagem * @param string $psDestino * @param int $pnLarguraMax * @param int $pnAlturaMax * @return boolean */ public static function gravarImagem($psImagem, $psDestino, $pnLarguraMax, $pnAlturaMax) { //Verificando se foi setada uma cor para preenchimento de fundo no config if (defined('IMAGE_BGCOLOR')) { $lsCorFundo = IMAGE_BGCOLOR; } else { $lsCorFundo = self::$csCorFundo; } //Verificando se foi setada a opção de esticar ou encolher imagem no config if (defined('IMAGE_STRETCH')) { $lbEsticarImagem = IMAGE_STRETCH; } else { $lbEsticarImagem = self::$cbEsticarImagem; } //Verificando se foi setada a opção de esticar ou encolher imagem no config if (defined('IMAGE_BORDER')) { $lbBorder = IMAGE_BORDER; } else { $lbBorder = self::$cbBorder; } Debug::debug("Cor de fundo: " . $lsCorFundo); Debug::debug("Esticar: " . $lbEsticarImagem); Debug::debug("Borda: " . $lbBorder); //Extraindo a extensão do nome da imagem $lsTipo = substr($psImagem, -3, 3); $lsTipo = strtolower($lsTipo); //Verificando qual o tipo da imagem e utilizando sua função específica de carregamento if ($lsTipo == "jpg" || $lsTipo == "peg") { $lrImg2 = ImageCreateFromJpeg($psImagem); } else { if ($lsTipo == "gif") { $lrImg2 = ImageCreateFromGif($psImagem); } } if ($lsTipo == "png") { $lrImg2 = ImageCreateFromPng($psImagem); } Debug::debug("Tipo: " . $lsTipo); //Se a imagem tiver sido carregada com sucesso, deve continuar o tratamento if (!empty($lrImg2)) { //Recuperando as dimensões da imagem $lnAlturaReal = ImageSY($lrImg2); $lnLarguraReal = ImageSX($lrImg2); if ($pnLarguraMax == "" || $pnLarguraMax == 0) { $lnLarguraMax = $lnLarguraReal; } else { $lnLarguraMax = $pnLarguraMax; } if ($pnAlturaMax == "" || $pnAlturaMax == 0) { $lnAlturaMax = $lnAlturaReal; } else { $lnAlturaMax = $pnAlturaMax; } //Criando um handle para tratamento da imagem nas dimensões da mesma $lrImg = imagecreatetruecolor($lnLarguraMax, $lnAlturaMax); //Explodindo definições de cor de fundo para pegar separadamente cada camada $laCorFundo = explode(',', $lsCorFundo); //Inicializando novas dimenções da imagem a partir da dimensão atual $lnAlturaNova = $lnAlturaReal; $lnLarguraNova = $lnLarguraReal; if ($lbBorder && !empty($pnAlturaMax) && !empty($pnLarguraMax)) { Debug::debug("com borda"); //Se a imagem puder ser esticada proporcionalmente if ($lbEsticarImagem) { //Se a largura atual ou nova for menor que a largura Máxima ou ideal if ($lnLarguraNova < $lnLarguraMax) { Debug::debug("esticando largura"); //A altura deve aumentar proporcionalmente em relação a largura máxima ou ideal $lnAlturaNova = $lnLarguraMax * ($lnAlturaNova / $lnLarguraNova); $lnLarguraNova = (int) $lnLarguraMax; //Aumenta para a largura máxima $lnAlturaNova = (int) $lnAlturaNova; //Aumenta para a altura máxima } } //Se a altura atual ou nova for maior que altura máxima if ($lnAlturaNova > $lnAlturaMax) { Debug::debug("reduzindo altura"); //A largura deve diminuir proporcionalmente em relação a altura máxima ou ideal $lnLarguraNova = $lnAlturaMax * ($lnLarguraNova / $lnAlturaNova); $lnAlturaNova = (int) $lnAlturaMax; //Diminui para a altura máxima $lnLarguraNova = (int) $lnLarguraNova; //Diminui para nova largura } //Se a largura atual ou nova for maior que a largura máxima if ($lnLarguraNova > $lnLarguraMax) { Debug::debug("reduzindo largura"); //A altura deve diminuir proporcionalmente em relação a largura máxima ou ideal $lnAlturaNova = $lnLarguraMax * ($lnAlturaNova / $lnLarguraNova); $lnLarguraNova = (int) $lnLarguraMax; //Diminui para a largura máxima $lnAlturaNova = (int) $lnAlturaNova; //Diminui para a nova altura } } else { Debug::debug("sem borda"); Debug::debug($lnAlturaNova . ">" . $lnAlturaMax); //Se a altura atual ou nova for maior que altura máxima if ($lnAlturaNova > $lnAlturaMax) { Debug::debug("reduzindo altura"); //A largura deve diminuir proporcionalmente em relação a altura máxima ou ideal $lnLarguraNova = $lnAlturaMax * ($lnLarguraNova / $lnAlturaNova); $lnAlturaNova = (int) $lnAlturaMax; //Diminui para a altura máxima $lnLarguraNova = (int) $lnLarguraNova; //Diminui para nova largura } Debug::debug($lnLarguraNova . ">" . $lnLarguraMax); //Se a largura atual ou nova for maior que a largura máxima if ($lnLarguraNova > $lnLarguraMax) { Debug::debug("reduzindo largura"); //A altura deve diminuir proporcionalmente em relação a largura máxima ou ideal $lnAlturaNova = $lnLarguraMax * ($lnAlturaNova / $lnLarguraNova); $lnLarguraNova = (int) $lnLarguraMax; //Diminui para a largura máxima $lnAlturaNova = (int) $lnAlturaNova; //Diminui para a nova altura } //Se a imagem puder ser esticada proporcionalmente if ($lbEsticarImagem) { //Se a largura atual ou nova for menor que a largura Máxima ou ideal if ($lnLarguraNova < $lnLarguraMax) { Debug::debug("esticando largura"); //A altura deve aumentar proporcionalmente em relação a largura máxima ou ideal $lnAlturaNova = $lnLarguraMax * ($lnAlturaNova / $lnLarguraNova); $lnLarguraNova = (int) $lnLarguraMax; //Aumenta para a largura máxima $lnAlturaNova = (int) $lnAlturaNova; //Aumenta para a altura máxima } //Se a altura atual ou nova for menor que a altura Máxima ou ideal if ($lnAlturaNova < $lnAlturaMax) { Debug::debug("esticando altura"); //A largura deve aumentar proporcionalmente em relação a altura máxima ou ideal $lnLarguraNova = $lnAlturaMax * ($lnLarguraNova / $lnAlturaNova); $lnAlturaNova = (int) $lnAlturaMax; //Aumenta para a altura máxima $lnLarguraNova = (int) $lnLarguraNova; //Aumenta para nova largura } } } //Centralizando imagem dentro do frame $lnPosX = ($lnLarguraMax - $lnLarguraNova) / 2; $lnPosY = ($lnAlturaMax - $lnAlturaNova) / 2; Debug::debug("Dimensão Original: " . $lnLarguraReal . "x" . $lnAlturaReal); Debug::debug("Dimensão Nova: " . $lnLarguraNova . "x" . $lnAlturaNova); if ($lsTipo == "png") { Debug::debug("criando png"); //Ativa a camada de transparência para a imagem imagealphablending($lrImg, true); //Aloca a cor transparente e preenche a nova imagem com isto. //Sem isto a imagem vai ficar com fundo preto ao invés de transparente. $loTransparent = imagecolorallocatealpha($lrImg, 0, 0, 0, 127); imagefill($lrImg, 0, 0, $loTransparent); //copia o frame na imagem final imagecopyresampled($lrImg, $lrImg2, $lnPosX, $lnPosY, 0, 0, $lnLarguraNova, $lnAlturaNova, $lnLarguraReal, $lnAlturaReal); imagealphablending($lrImg, false); //Salva a camada alpha (transparência) imagesavealpha($lrImg, true); } elseif ($lsTipo == "gif") { Debug::debug("criando gif"); //redimencionando a imagem e criando a imagem final imagecopyresized($lrImg, $lrImg2, $lnPosX, $lnPosY, 0, 0, $lnLarguraNova, $lnAlturaNova, $lnLarguraReal, $lnAlturaReal); } else { Debug::debug("criando jpg"); //definindo a cor de fundo da imagem e preenchendo a camada $lrFundo = imagecolorallocate($lrImg, $laCorFundo[0], $laCorFundo[1], $laCorFundo[2]); imagefill($lrImg, 0, 0, $lrFundo); //redimencionando a imagem e criando a imagem final imagecopyresized($lrImg, $lrImg2, $lnPosX, $lnPosY, 0, 0, $lnLarguraNova, $lnAlturaNova, $lnLarguraReal, $lnAlturaReal); } if ($lsTipo == "jpg" || $lsTipo == "peg") { //header("Content-Type: image/jpeg"); if (!imagejpeg($lrImg, $psDestino)) { Event::log(array("userId" => null, "class" => "Image", "method" => "gravarImagem", "msg" => "Create image JPG failed!"), Event::ERR); Debug::debug("Create image JPG failed!"); } } else { if ($lsTipo == "gif") { //header("Content-Type: image/gif"); if (!imagegif($lrImg, $psDestino)) { Event::log(array("userId" => null, "class" => "Image", "method" => "gravarImagem", "msg" => "Create image GIF failed!"), Event::ERR); Debug::debug("Create image GIF failed!"); } } else { if ($lsTipo == "png") { //header("Content-Type: image/png"); if (!imagepng($lrImg, $psDestino)) { Event::log(array("userId" => null, "class" => "Image", "method" => "gravarImagem", "msg" => "Create image PNG failed!"), Event::ERR); Debug::debug("Create image PNG failed!"); } } } } imagedestroy($lrImg); return true; } else { Event::log(array("userId" => null, "class" => "Image", "method" => "gravarImagem", "msg" => "Image truncated!"), Event::ERR); Debug::debug("Image truncated!"); return false; } }
/** * image::addlogo() * * @param mixed $logo * @param string $align * @param string $valign * @return */ function addlogo($logo, $align = 'right', $valign = 'bottom') { if (empty($this->error)) { if ($this->is_destroy) { $this->get_createImage(); } $logo_info = nv_is_image($logo); if ($logo_info != array() and $logo_info['width'] != 0 and $logo_info['width'] + 20 <= $this->create_Image_info['width'] and $logo_info['height'] != 0 and $logo_info['height'] + 20 <= $this->create_Image_info['height'] and preg_match("#imagetype\\_(gif|jpeg|png)\$#is", $logo_info['type']) and preg_match("#image\\/[x\\-]*(jpg|pjpeg|gif|png)#is", $logo_info['mime'])) { $this->set_memory_limit(); switch ($logo_info['type']) { case 'IMAGETYPE_GIF': $this->logoimg = ImageCreateFromGif($logo); break; case 'IMAGETYPE_JPEG': $this->logoimg = ImageCreateFromJpeg($logo); break; case 'IMAGETYPE_PNG': $this->logoimg = ImageCreateFromPng($logo); break; } switch ($align) { case 'left': $X = 10; break; case 'center': $X = ceil(($this->create_Image_info['width'] - $logo_info['width']) / 2); break; default: $X = $this->create_Image_info['width'] - ($logo_info['width'] + 10); } switch ($valign) { case 'top': $Y = 10; break; case 'middle': $Y = ceil(($this->create_Image_info['height'] - $logo_info['height']) / 2); break; default: $Y = $this->create_Image_info['height'] - ($logo_info['height'] + 10); } ImageCopyResampled($this->createImage, $this->logoimg, $X, $Y, 0, 0, $logo_info['width'], $logo_info['height'], $logo_info['width'], $logo_info['height']); } } }
// str - текстовая строка // тип преобразования, если не указаны размеры $f = $_POST["filename"]; //"/storage/0b3e6bb4e833f345a14ebf255411a113.jpg"; if (substr($f, 0, 3) == "htt") { $f = substr($f, 7); $ff = strpos($f, "/"); $f = substr($f, $ff); } $ff = folderview($f); $f = "../../" . $f; $format = strtolower(substr(strrchr($f, "."), 1)); switch ($format) { case 'gif': $type = "gif"; $img = ImageCreateFromGif($f); break; case 'png': $type = "png"; $img = ImageCreateFromPng($f); break; case 'jpg': $type = "jpg"; $img = ImageCreateFromJpeg($f); break; case 'jpeg': $type = "jpg"; $img = ImageCreateFromJpeg($f); break; default: return false;
function plugin_ref_make_thumb($url, $s_file_base, $width, $height, $org_w, $org_h) { $s_file = MOD_PUKI_UPLOAD_DIR . $s_file_base; // GD fuction のチェック if (!function_exists("ImageCreate")) { return $url; } //GDをサポートしていない $gifread = ''; if (MOD_PUKI_REF_GD_VERSION == 2) { $imagecreate = "ImageCreateTrueColor"; $imageresize = "ImageCopyResampled"; } else { $imagecreate = "ImageCreate"; $imageresize = "ImageCopyResized"; } if (function_exists("ImageCreateFromGif")) { $gifread = "on"; } $size = @GetImageSize($url); $dst_im = $imagecreate($width, $height); switch ($size[2]) { case "1": //gif形式 if ($gifread == "on") { $src_im = ImageCreateFromGif($url); $imageresize($dst_im, $src_im, 0, 0, 0, 0, $width, $height, $size[0], $size[1]); ImageJpeg($dst_im, $s_file); $url = MOD_PUKI_UPLOAD_URL . $s_file_base; } break; case "2": //jpg形式 $src_im = ImageCreateFromJpeg($url); $imageresize($dst_im, $src_im, 0, 0, 0, 0, $width, $height, $size[0], $size[1]); ImageJpeg($dst_im, $s_file); $url = MOD_PUKI_UPLOAD_URL . $s_file_base; break; case "3": //png形式 $src_im = ImageCreateFromPng($url); $imageresize($dst_im, $src_im, 0, 0, 0, 0, $width, $height, $size[0], $size[1]); ImageJpeg($dst_im, $s_file); $url = MOD_PUKI_UPLOAD_URL . $s_file_base; break; default: break; } return $url; }
/** * @package Codingfish Discussions * @subpackage com_discussions * @copyright Copyright (C) 2010 Codingfish (Achim Fischer). All rights reserved. * @license GNU General Public License <http://www.gnu.org/copyleft/gpl.html> * @link http://www.codingfish.com */ function add_image($user_id, $image, $absolute_path, $db) { $af_dir_ads = $absolute_path . "/images/discussions/users/"; $max_image_size = 209715200; // 200 KByte ? $discussions_folder = $absolute_path . "/images/discussions/"; if (!is_dir($discussions_folder)) { mkdir($discussions_folder); } $users_folder = $absolute_path . "/images/discussions/users/"; if (!is_dir($users_folder)) { mkdir($users_folder); } $image_too_big = 0; if (isset($_FILES['avatar'])) { if ($_FILES['avatar']['size'] > $max_image_size) { $image_too_big = 1; } } if ($image_too_big == 1) { echo "<font color='#CC0000'>"; echo "The uploaded image is too big"; echo "</font>"; echo "<br>"; echo "<br>"; } else { $af_size = GetImageSize($_FILES[$image]['tmp_name']); switch ($af_size[2]) { case 1: $thispicext = 'gif'; break; case 2: $thispicext = 'jpg'; break; case 3: $thispicext = 'png'; break; } // if ( $af_size[2] >= 1 && $af_size[2] <= 3) { // 1=GIF, 2=JPG or 3=PNG if ($af_size[2] >= 2 && $af_size[2] <= 3) { // 2=JPG or 3=PNG $pict_jpg = $absolute_path . "/images/discussions/users/" . $user_id . "_t.jpg"; if (file_exists($pict_jpg)) { unlink($pict_jpg); } $pic_jpg = $absolute_path . "/images/discussions/users/" . $user_id . ".jpg"; if (file_exists($pic_jpg)) { unlink($pic_jpg); } $pict_png = $absolute_path . "/images/discussions/users/" . $user_id . "_t.png"; if (file_exists($pict_png)) { unlink($pict_png); } $pic_png = $absolute_path . "/images/discussions/users/" . $user_id . ".png"; if (file_exists($pic_png)) { unlink($pic_png); } $pict_gif = $absolute_path . "/images/discussions/users/" . $user_id . "_t.gif"; if (file_exists($pict_gif)) { unlink($pict_gif); } $pic_gif = $absolute_path . "/images/discussions/users/" . $user_id . ".gif"; if (file_exists($pic_gif)) { unlink($pic_gif); } chmod($_FILES[$image]['tmp_name'], 0644); // 1. if directory ./avatars/USERID does not exist, create it // 2. create the subdirs for ORIGINAL, LARGE (128) and SMALL(32) if (!is_dir($af_dir_ads . $user_id)) { mkdir($af_dir_ads . $user_id); mkdir($af_dir_ads . $user_id . "/original"); // ORIGINAL mkdir($af_dir_ads . $user_id . "/large"); // LARGE (128) mkdir($af_dir_ads . $user_id . "/small"); // SMALL (32) } $original_image = $af_dir_ads . $user_id . "/original/" . $user_id . "." . $thispicext; $large_image = $af_dir_ads . $user_id . "/large/" . $user_id . "." . $thispicext; $small_image = $af_dir_ads . $user_id . "/small/" . $user_id . "." . $thispicext; // copy original image to folder "original" move_uploaded_file($_FILES[$image]['tmp_name'], $original_image); // create "large" image 128px switch ($af_size[2]) { case 1: $src = ImageCreateFromGif($original_image); break; case 2: $src = ImageCreateFromJpeg($original_image); break; case 3: $src = ImageCreateFromPng($original_image); break; } $width_before = ImageSx($src); $height_before = ImageSy($src); if ($width_before >= $height_before) { $width_new = min(128, $width_before); $scale = $width_before / $height_before; $height_new = round($width_new / $scale); } else { $height_new = min(128, $height_before); $scale = $height_before / $width_before; $width_new = round($height_new / $scale); } $dst = ImageCreateTrueColor($width_new, $height_new); // GD Lib 2 ImageCopyResampled($dst, $src, 0, 0, 0, 0, $width_new, $height_new, $width_before, $height_before); switch ($af_size[2]) { case 1: ImageGIF($dst, $large_image); break; case 2: ImageJPEG($dst, $large_image); break; case 3: ImagePNG($dst, $large_image); break; } imagedestroy($dst); imagedestroy($src); // create "small" image 32px switch ($af_size[2]) { case 1: $src = ImageCreateFromGif($original_image); break; case 2: $src = ImageCreateFromJpeg($original_image); break; case 3: $src = ImageCreateFromPng($original_image); break; } $width_before = ImageSx($src); $height_before = ImageSy($src); if ($width_before >= $height_before) { $width_new = min(32, $width_before); $scale = $width_before / $height_before; $height_new = round($width_new / $scale); } else { $height_new = min(32, $height_before); $scale = $height_before / $width_before; $width_new = round($height_new / $scale); } $dst = ImageCreateTrueColor($width_new, $height_new); // GD Lib 2 ImageCopyResampled($dst, $src, 0, 0, 0, 0, $width_new, $height_new, $width_before, $height_before); switch ($af_size[2]) { case 1: ImageGIF($dst, $small_image); break; case 2: ImageJPEG($dst, $small_image); break; case 3: ImagePNG($dst, $small_image); break; } imagedestroy($dst); imagedestroy($src); // DB update $sql = "UPDATE #__discussions_users SET avatar='" . $user_id . "." . $thispicext . "' WHERE id=" . $user_id; $db->setQuery($sql); if ($db->getErrorNum()) { echo $db->stderr(); } else { $db->query(); } } } }
/** * Return a resource corresponding to image type * * @param string $path Image path * * @return resource */ private function _getImageAsResource($path) { $image = null; switch ($this->img_type) { case IMAGETYPE_JPEG: $image = ImageCreateFromJpeg($path); break; case IMAGETYPE_PNG: $image = ImageCreateFromPng($path); break; case IMAGETYPE_GIF: $image = ImageCreateFromGif($path); break; case IMAGETYPE_TIFF_II: case IMAGETYPE_TIFF_MM: /** Gd cannot handle TIFF images. */ throw new \RuntimeException(_('TIFF images cannot be handled using Gd library!')); break; } return $image; }
<?php if (!isset($label)) { $label = "Hello"; } # $gif = ImageCreate(125,30); $gif = ImageCreateFromGif("/home/www/pals/html/campbell/src/iowa.gif"); # $bg = ImageColorTransparent($gif,1); $white = ImageColorAllocate($gif, 250, 250, 250); $black = ImageColorAllocate($gif, 0, 0, 0); $green = ImageColorAllocate($gif, 0, 255, 0); ImageFilledRectangle($gif, 0, 0, 125, 30, $green); ImageFilledRectangle($gif, 2, 2, 123, 28, $white); # ImageArc($gif, 100, 100, 100, 50, 145, 90, $black); ImageTTFText($gif, 20, 0, 10, 20, $black, "/usr/X11R6/lib/X11/fonts/winttf/handgotn.TTF", "Weather"); # ImageString($gif, 5, 70, 5,$label,$black); # ImageString($gif, 5, 71, 6,$label,$white); # header("content-type: image/gif"); ImageGif($gif);
function show($name = "") { if ($this->error) { $this->show_error_image(); return; } $size = GetImageSize($this->file); $new_size = $this->calc_image_size($size[0], $size[1]); # # Good idea from Mariano Cano P�rez # Requires GD 2.0.1 (PHP >= 4.0.6) # if (function_exists("ImageCreateTrueColor")) { $new_image = ImageCreateTrueColor($new_size[0], $new_size[1]); } else { $new_image = ImageCreate($new_size[0], $new_size[1]); } switch ($this->format) { case "GIF": $old_image = ImageCreateFromGif($this->file); break; case "JPEG": $old_image = ImageCreateFromJpeg($this->file); break; case "PNG": $old_image = ImageCreateFromPng($this->file); break; } # # Good idea from Michael Wald # Requires GD 2.0.1 (PHP >= 4.0.6) # if (function_exists("ImageCopyResampled")) { ImageCopyResampled($new_image, $old_image, 0, 0, 0, 0, $new_size[0], $new_size[1], $size[0], $size[1]); } else { ImageCopyResized($new_image, $old_image, 0, 0, 0, 0, $new_size[0], $new_size[1], $size[0], $size[1]); } switch ($this->format) { case "GIF": if (!empty($name)) { ImageGif($new_image, $name); } else { header("Content-type: image/gif"); ImageGif($new_image); } break; case "JPEG": if (!empty($name)) { ImageJpeg($new_image, $name, $this->jpeg_quality); } else { header("Content-type: image/jpeg"); ImageJpeg($new_image, "", $this->jpeg_quality); } break; case "PNG": if (!empty($name)) { ImagePng($new_image, $name); } else { header("Content-type: image/png"); ImagePng($new_image); } break; } ImageDestroy($new_image); ImageDestroy($old_image); return; }
/** * Create a thumbnail image * @param string $fileName The image filename */ function createThumb($fileName, $filePath) { //copy image $oldFile = $this->mediaPath . $filePath . $fileName; $newFile = $this->mediaPath . "thumbs/" . $fileName; $arrSettings = $this->getSettings(); $arrInfo = getimagesize($oldFile); //ermittelt die Größe des Bildes $setSize = $arrSettings['thumbSize']['value']; $strType = $arrInfo[2]; //type des Bildes if ($arrInfo[0] >= $setSize || $arrInfo[1] >= $setSize) { if ($arrInfo[0] <= $arrInfo[1]) { $intFactor = $arrInfo[1] / $setSize; $intHeight = $setSize; $intWidth = $arrInfo[0] / $intFactor; } else { $intFactor = $arrInfo[0] / $setSize; $intResult = $arrInfo[1] / $intFactor; if ($intResult > $setSize) { $intHeight = $setSize; $intWidth = $arrInfo[0] / $intFactor; } else { $intWidth = $setSize; $intHeight = $arrInfo[1] / $intFactor; } } } else { $intWidth = $arrInfo[0]; $intHeight = $arrInfo[1]; } if (imagetypes() & IMG_GIF) { $boolGifEnabled = true; } if (imagetypes() & IMG_JPG) { $boolJpgEnabled = true; } if (imagetypes() & IMG_PNG) { $boolPngEnabled = true; } @touch($newFile); switch ($strType) { case 1: //GIF if ($boolGifEnabled) { $handleImage1 = ImageCreateFromGif($oldFile); $handleImage2 = @ImageCreateTrueColor($intWidth, $intHeight); ImageCopyResampled($handleImage2, $handleImage1, 0, 0, 0, 0, $intWidth, $intHeight, $arrInfo[0], $arrInfo[1]); ImageGif($handleImage2, $newFile); ImageDestroy($handleImage1); ImageDestroy($handleImage2); } break; case 2: //JPG if ($boolJpgEnabled) { $handleImage1 = ImageCreateFromJpeg($oldFile); $handleImage2 = @ImageCreateTrueColor($intWidth, $intHeight); ImageCopyResampled($handleImage2, $handleImage1, 0, 0, 0, 0, $intWidth, $intHeight, $arrInfo[0], $arrInfo[1]); ImageJpeg($handleImage2, $newFile, 95); ImageDestroy($handleImage1); ImageDestroy($handleImage2); } break; case 3: //PNG if ($boolPngEnabled) { $handleImage1 = ImageCreateFromPNG($oldFile); ImageAlphaBlending($handleImage1, true); ImageSaveAlpha($handleImage1, true); $handleImage2 = @ImageCreateTrueColor($intWidth, $intHeight); ImageCopyResampled($handleImage2, $handleImage1, 0, 0, 0, 0, $intWidth, $intHeight, $arrInfo[0], $arrInfo[1]); ImagePNG($handleImage2, $newFile); ImageDestroy($handleImage1); ImageDestroy($handleImage2); } break; } }
/** * Image Resource ID for Watermark * * @var string * */ function ngg_Thumbnail($fileName, $no_ErrorImage = false) { //make sure the GD library is installed if (!function_exists("gd_info")) { echo 'You do not have the GD Library installed. This class requires the GD library to function properly.' . "\n"; echo 'visit http://us2.php.net/manual/en/ref.image.php for more information'; C_NextGEN_Bootstrap::shutdown(); } //initialize variables $this->errmsg = ''; $this->error = false; $this->currentDimensions = array(); $this->newDimensions = array(); $this->fileName = $fileName; $this->percent = 100; $this->maxWidth = 0; $this->maxHeight = 0; $this->watermarkImgPath = ''; $this->watermarkText = ''; //check to see if file exists if (!file_exists($this->fileName)) { $this->errmsg = 'File not found'; $this->error = true; } elseif (!is_readable($this->fileName)) { $this->errmsg = 'File is not readable'; $this->error = true; } //if there are no errors, determine the file format if ($this->error == false) { $data = @getimagesize($this->fileName); if (isset($data) && is_array($data)) { $extensions = array('1' => 'GIF', '2' => 'JPG', '3' => 'PNG'); $extension = array_key_exists($data[2], $extensions) ? $extensions[$data[2]] : ''; if ($extension) { $this->format = $extension; } else { $this->errmsg = 'Unknown file format'; $this->error = true; } } else { $this->errmsg = 'File is not an image'; $this->error = true; } } // increase memory-limit if possible, GD needs this for large images // @ini_set('memory_limit', '128M'); if ($this->error == false) { // Check memory consumption if file exists $this->checkMemoryForImage($this->fileName); } //initialize resources if no errors if ($this->error == false) { switch ($this->format) { case 'GIF': $this->oldImage = ImageCreateFromGif($this->fileName); break; case 'JPG': $this->oldImage = ImageCreateFromJpeg($this->fileName); break; case 'PNG': $this->oldImage = ImageCreateFromPng($this->fileName); break; } if (!$this->oldImage) { $this->errmsg = 'Create Image failed. Check memory limit'; $this->error = true; } else { $size = GetImageSize($this->fileName); $this->currentDimensions = array('width' => $size[0], 'height' => $size[1]); $this->newImage = $this->oldImage; } } if ($this->error == true) { if (!$no_ErrorImage) { $this->showErrorImage(); } return; } }
$img = Imagejpeg($dst_img, '', $_quality_); $ob_contents = ob_get_contents(); // Save file $fp = fopen("{$path}", 'wb'); fwrite($fp, $ob_contents); fclose($fp); ob_end_flush(); } } if (substr($_GET['img'], -3) == "gif") { header("Content-type: image/gif"); if (file_exists($path)) { echo file_get_contents($path); } else { $dst_img = ImageCreate($new_w, $new_h); $src_img = ImageCreateFromGif($_image_); ImagePaletteCopy($dst_img, $src_img); ImageCopyResized($dst_img, $src_img, 0, 0, 0, 0, $new_w, $new_h, ImageSX($src_img), ImageSY($src_img)); ob_start(); $img = Imagegif($dst_img, '', $_quality_); $ob_contents = ob_get_contents(); // Save file $fp = fopen("{$path}", 'wb'); fwrite($fp, $ob_contents); fclose($fp); ob_end_flush(); } } if (substr($_GET['img'], -3) == "png") { header("Content-type: image/png"); if (file_exists($path)) {
function generateImage($source_file, $cache_file, $resolution) { global $sharpen, $jpg_quality; $extension = strtolower(pathinfo($source_file, PATHINFO_EXTENSION)); // Check the image dimensions $dimensions = GetImageSize($source_file); $width = $dimensions[0]; $height = $dimensions[1]; // Do we need to downscale the image? if ($width <= $resolution) { // no, because the width of the source image is already less than the client width return $source_file; } // We need to resize the source image to the width of the resolution breakpoint we're working with $ratio = $height / $width; $new_width = $resolution; $new_height = ceil($new_width * $ratio); $dst = ImageCreateTrueColor($new_width, $new_height); // re-sized image switch ($extension) { case 'png': $src = @ImageCreateFromPng($source_file); // original image break; case 'gif': $src = @ImageCreateFromGif($source_file); // original image break; default: $src = @ImageCreateFromJpeg($source_file); // original image ImageInterlace($dst, true); // Enable interlancing (progressive JPG, smaller size file) break; } if ($extension == 'png') { imagealphablending($dst, false); imagesavealpha($dst, true); $transparent = imagecolorallocatealpha($dst, 255, 255, 255, 127); imagefilledrectangle($dst, 0, 0, $new_width, $new_height, $transparent); } ImageCopyResampled($dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height); // do the resize in memory ImageDestroy($src); // sharpen the image? // NOTE: requires PHP compiled with the bundled version of GD (see http://php.net/manual/en/function.imageconvolution.php) if ($sharpen == TRUE && function_exists('imageconvolution')) { $intSharpness = findSharp($width, $new_width); $arrMatrix = array(array(-1, -2, -1), array(-2, $intSharpness + 12, -2), array(-1, -2, -1)); imageconvolution($dst, $arrMatrix, $intSharpness, 0); } $cache_dir = dirname($cache_file); // does the directory exist already? if (!is_dir($cache_dir)) { if (!mkdir($cache_dir, 0755, true)) { // check again if it really doesn't exist to protect against race conditions if (!is_dir($cache_dir)) { // uh-oh, failed to make that directory ImageDestroy($dst); sendErrorImage("Failed to create cache directory: {$cache_dir}"); } } } if (!is_writable($cache_dir)) { sendErrorImage("The cache directory is not writable: {$cache_dir}"); } // save the new file in the appropriate path, and send a version to the browser switch ($extension) { case 'png': $gotSaved = ImagePng($dst, $cache_file); break; case 'gif': $gotSaved = ImageGif($dst, $cache_file); break; default: $gotSaved = ImageJpeg($dst, $cache_file, $jpg_quality); break; } ImageDestroy($dst); if (!$gotSaved && !file_exists($cache_file)) { sendErrorImage("Failed to create image: {$cache_file}"); } return $cache_file; }
/** * @since 2.0 */ public final function createImageFromFile() { if ($this->isJPEG()) { $this->image = ImageCreateFromJpeg($this->fullPath()); } else { if ($this->isGIF()) { $this->image = ImageCreateFromGif($this->fullPath()); } else { if ($this->isPNG()) { $this->image = ImageCreateFromPng($this->fullPath()); } } } }
/** * Contructor method. Will create a new image from the target file. * Accepts an image filename as a string. Method also works out how * big the image is and stores this in the $image array. * * @param string $imgFile The image filename. */ public function ImageManipulation($imgfile) { //detect image format $this->image["format"] = preg_replace("/.*\\.(.*)\$/", "\\1", $imgfile); //$this->image["format"] = preg_replace(".*\.(.*)$", "\\1", $imgfile); $this->image["format"] = strtoupper($this->image["format"]); // convert image into usable format. if ($this->image["format"] == "JPG" || $this->image["format"] == "JPEG") { //JPEG $this->image["format"] = "JPEG"; $this->image["src"] = ImageCreateFromJPEG($imgfile); } elseif ($this->image["format"] == "PNG") { //PNG $this->image["format"] = "PNG"; $this->image["src"] = imagecreatefrompng($imgfile); } elseif ($this->image["format"] == "GIF") { //GIF $this->image["format"] = "GIF"; $this->image["src"] = ImageCreateFromGif($imgfile); } elseif ($this->image["format"] == "WBMP") { //WBMP $this->image["format"] = "WBMP"; $this->image["src"] = ImageCreateFromWBMP($imgfile); } else { //DEFAULT return false; } // Image is ok $this->imageok = true; // Work out image size $this->image["sizex"] = imagesx($this->image["src"]); $this->image["sizey"] = imagesy($this->image["src"]); }