function reldis_createFile($filename, $uga_part, $agga_part) { $im_uga = @ImageCreateFromPng("good.png"); $im_agga = @ImageCreateFromPng("bad.png"); if (!$im_uga || !$im_agga) { die("Cannot Initialize new GD image stream"); } $width = imagesx($im_uga); $sum = $uga_part + $agga_part; $uga_part /= $sum; $agga_part /= $sum; $uga_part *= $width; $agga_part *= $width; $im = @ImageCreate($width, $width); $white = imagecolorallocate($im, 0xff, 0xff, 0xff); imagefill($im, 0, 0, $white); imagecolortransparent($im, $white); $left = 0; imagecopy($im, $im_uga, $left, 0, $left, 0, $uga_part + 1, $width); $left += $uga_part; imagecopy($im, $im_agga, $left, 0, $left, 0, $agga_part + 1, $width); header("Content-type: image/png"); imagepng($im, $filename); imagedestroy($im); }
function get_hex($location, $extensions = array('PNG', 'png', 'Png', 'JPG', 'jpg', 'Jpg', 'JPEG', 'jpeg', 'Jpeg', 'GIF', 'gif', 'Gif'), $postvar = "myimage", $getvar = "imgclix") { if (isset($_GET[$getvar])) { foreach ($extensions as $var) { if (file_exists($location . str_replace(array("..", ".", $var), '', html_entity_decode($_GET[$getvar])) . "." . $var)) { if (stristr($var, 'png')) { $im = ImageCreateFromPng($location . str_replace(array("..", ".", $var), '', html_entity_decode($_GET[$getvar])) . "." . $var); } elseif (stristr($var, 'gif')) { $im = ImageCreateFromGIF($location . str_replace(array("..", ".", $var), '', html_entity_decode($_GET[$getvar])) . "." . $var); } elseif (stristr($var, 'jpg') || stristr($var, 'jpeg')) { $im = ImageCreateFromJpeg($location . str_replace(array("..", ".", $var), '', html_entity_decode($_GET[$getvar])) . "." . $var); } else { return FALSE; } $rgb = ImageColorAt($im, $_POST[$postvar . '_x'], $_POST[$postvar . '_y']); $rgb = imagecolorsforindex($im, $rgb); $hex = sprintf('#%02X%02X%02X', $rgb['red'], $rgb['green'], $rgb['blue']); break; } } } else { return FALSE; } if (!isset($hex) || $hex == '') { return FALSE; } return $hex; }
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 controller_stitch() { $basefile = "./htdocs/world.topo.bathy.200401.3x21600x21600"; $combined = "./htdocs/big.png"; $tilesize = array(21600, 21600); $finalimg = ImageCreateTrueColor($tilesize[0] * 2, $tilesize[1] * 1); $tiles["A1"] = ImageCreateFromPng($basefile . ".A1.png"); }
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 static function CreatePngThumbnail($imageDirectory, $imageName, $thumbDirectory, $thumbWidth, $imageNewName) { $srcImg = ImageCreateFromPng($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)); imagePng($thumbImg, $thumbDirectory . $imageNewName); }
function Bouton($alt, $image, $police, $taille_police, $hex_bgc, $x, $y, $degre, $cache, $theme) { // on cherche le repertoire ou se trouve les boutons if (is_dir('themes/' . $theme . '/images/')) { $rep = 'themes/' . $theme . '/images/'; } else { $rep = 'tools/templates/themes/' . $theme . '/images/'; } $this->alt = $alt; $this->nom = 'cache/bouton_' . str_replace('.png', '', $image) . '_' . $this->formater($alt) . '.png'; if (is_file($this->nom) && !empty($cache)) { $taille = getimagesize($this->nom); $this->largeur = $taille[0]; $this->hauteur = $taille[1]; } else { // Utilisation des ressources graphiques $fond = $rep . $image; $taille_fond = getimagesize($fond); $img = ImageCreateFromPng($fond); // Parametres du bouton $this->hauteur = $taille_fond[1]; $this->largeur = $taille_fond[0]; // On formate la couleur comme il faut $hex_bgc = str_replace('#', '', $hex_bgc); switch (strlen($hex_bgc)) { case 6: $red = hexdec(substr($hex_bgc, 0, 2)); $green = hexdec(substr($hex_bgc, 2, 2)); $blue = hexdec(substr($hex_bgc, 4, 2)); break; case 3: $red = substr($hex_bgc, 0, 1); $green = substr($hex_bgc, 1, 1); $blue = substr($hex_bgc, 2, 1); $red = hexdec($red . $red); $green = hexdec($green . $green); $blue = hexdec($blue . $blue); break; default: // mauvaises valeurs, on met en noir $red = 0; $green = 0; $blue = 0; } $couleur = ImageColorAllocate($img, $red, $green, $blue); // Texte imagettftext($img, $taille_police, $degre, $x, $y, $couleur, $rep . $police, ' ' . stripslashes(trim($this->alt))); imagealphablending($img, true); imagesavealpha($img, true); //Creation du bouton de type btn_[motif]_[alt].png imagepng($img, $this->nom); } }
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 likebanner_init(&$a) { if (argc() > 1 && argv(1) == 'show' && $_REQUEST['addr']) { header("Content-Type: image/png"); $im = ImageCreateFromPng('addon/likebanner/like_banner.png'); $black = ImageColorAllocate($im, 0, 0, 0); $start_x = 18; $start_y = 110; $fontsize = $_REQUEST['size'] ? intval($_REQUEST['size']) : 28; imagettftext($im, $fontsize, 0, $start_x, $start_y, $black, 'addon/likebanner/FreeSansBold.ttf', $_REQUEST['addr']); imagepng($im); ImageDestroy($im); killme(); } }
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"); } }
public function action_index() { // Remove an image if (isset($_GET['rm'])) { $image = new Content_Image($_GET['rm']); $image->rm_image(); $this->redirect(); } // Add image if (isset($_POST['upload_image'])) { foreach ($_FILES['image']['name'] as $nr => $name) { if ($name != '') { $pathinfo = pathinfo($_FILES['image']['name'][$nr]); if (strtolower($pathinfo['extension']) == 'jpg' || strtolower($pathinfo['extension']) == 'png') { $filename = 'frontimage.' . strtolower($pathinfo['extension']); $new_filename = $filename; $counter = 1; while (!Content_Image::image_name_available($new_filename)) { $new_filename = substr($filename, 0, strlen($filename) - 4) . '_' . $counter . '.' . strtolower($pathinfo['extension']); $counter++; } if (move_uploaded_file($_FILES['image']['tmp_name'][$nr], APPPATH . '/user_content/images/' . $new_filename)) { if (strtolower($pathinfo['extension']) == 'jpg') { $gd_img_object = ImageCreateFromJpeg(Kohana::$config->load('user_content.dir') . '/images/' . $new_filename); } elseif (strtolower($pathinfo['extension']) == 'png') { $gd_img_object = ImageCreateFromPng(Kohana::$config->load('user_content.dir') . '/images/' . $new_filename); } $details = array('width' => array(imagesx($gd_img_object)), 'height' => array(imagesy($gd_img_object)), 'frontimage' => NULL); Content_Image::new_image($new_filename, $details); } else { $this->add_error('Unknown error uploading image(s)'); } } } } } // Images $images = array(); foreach (Content_image::get_images(NULL, array('frontimage' => TRUE)) as $image_name => $image_data) { $images[] = array('name' => $image_name); } $this->xml_content_images = $this->xml_content->appendChild($this->dom->createElement('images')); xml::to_XML($images, $this->xml_content_images, 'image'); }
public static function resizeImage($imageFrom, $imageTo, $fitWidth = 600, $fitHeight = 600, $quality = 75) { $imageFrom = getcwd() . self::$baseImgPath . $imageFrom; $imageTo = getcwd() . self::$baseImgPath . $imageTo; $os = $originalSize = getimagesize($imageFrom); if ($originalSize <= 0 && $originalSize > 3) { return false; } if ($originalSize[0] > $fitWidth || $originalsize[1] > $fitHeight) { $h = $originalSize; if ($h[0] / $fitWidth > $h[1] / $fitHeight) { $fitHeight = $h[1] * $fitWidth / $h[0]; } else { $fitWidth = $h[0] * $fitHeight / $h[1]; } if ($os[2] == 2 || $os[2] >= 9 && $os[2] <= 12) { $i = ImageCreateFromJPEG($imageFrom); } elseif ($os[2] == 3) { $i = ImageCreateFromPng($imageFrom); } elseif ($os[2] == 1) { $i = imagecreatefromgif($imageFrom); } $o = ImageCreateTrueColor($fitWidth, $fitHeight); imagecopyresampled($o, $i, 0, 0, 0, 0, $fitWidth, $fitHeight, $h[0], $h[1]); imagejpeg($o, $imageTo, $quality); chmod($imageTo, 0666); imagedestroy($o); imagedestroy($i); return true; } if ($originalSize[0] <= $fitWidth && $originalSize[1] <= $fitHeight) { if ($os[2] == 2 || $os[2] >= 9 && $os[2] <= 12) { $i = ImageCreateFromJPEG($imageFrom); } elseif ($os[2] == 3) { $i = ImageCreateFromPng($imageFrom); } elseif ($os[2] == 1) { $i = imagecreatefromgif($imageFrom); } imagejpeg($i, $imageTo, $quality); chmod($imageTo, 0666); return true; } }
function forumbadge_run() { global $session; $acctid = httpget("acctid"); page_header("Badge!"); //PHP's GD class functions can create a variety of output image //types, this example creates a jpeg header("Content-Type: image/jpeg"); //open up the image you want to put text over $im = ImageCreateFromPng("modules/buttonbase.png"); //The numbers are the RGB values of the color you want to use $black = ImageColorAllocate($im, 0, 0, 0); //The canvas's (0,0) position is the upper left corner //So this is how far down and to the right the text should start $start_x = 10; $start_y = 20; $sql = "SELECT race, login, level, dragonkills FROM " . db_prefix("accounts") . " WHERE acctid = {$acctid}"; $result = db_fetch_assoc(db_query($sql)); $name = $result['login']; $race = $result['race']; $level = "Level " . $result['level']; $dragonkills = "Drive Kills: " . $result['dragonkills']; debug($result); //This writes your text on the image in 12 point using verdana.ttf //For the type of effects you quoted, you'll want to use a truetype font //And not one of GD's built in fonts. Just upload the ttf file from your //c: windows fonts directory to your web server to use it. Imagettftext($im, 10, 0, 65, 12, $black, 'modules/verdana.ttf', $name); Imagettftext($im, 10, 0, 65, 27, $black, 'modules/verdana.ttf', $race); Imagettftext($im, 10, 0, 65, 42, $black, 'modules/verdana.ttf', $level); Imagettftext($im, 10, 0, 65, 57, $black, 'modules/verdana.ttf', $dragonkills); //Creates the jpeg image and sends it to the browser //100 is the jpeg quality percentage Imagejpeg($im, '', 60); ImageDestroy($im); page_footer(); }
/** * 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']); } } }
public static function beResizeImg($isrc, $idst, $iw, $ih, $ip = 'keep', $imax = 'yes', $iqual = 95) { /* parameters $isrc source file $idst destination folder $iw new width $ih new height $ip='keep' keep proportions $imax='yes' treat width/height as maximums $iqual=95 image quality */ //read array with source image information $imagedata = getimagesize($isrc); //calculate new width and height $srcwid = $imagedata[0]; $srchei = $imagedata[1]; $srcx = $srcy = 0; //if no height is set we calculate it if ($ih == "full") { $ih = (int) ($imagedata[1] * ($iw / $imagedata[0])); } //the new width $new_iw = (int) $iw; //the new height if ($ip == 'keep') { //keep proportions $new_ih = (int) ($imagedata[1] * ($new_iw / $imagedata[0])); if ($new_ih > $ih) { $new_ih = (int) $ih; $new_iw = (int) ($imagedata[0] * ($new_ih / $imagedata[1])); } } else { //set fixed height $new_ih = (int) $ih; //crop if ($imagedata[0] / $new_iw < $imagedata[1] / $new_ih) { //original to heigh $srchei = (int) ($new_ih * ($imagedata[0] / $new_iw)); $srcy = (int) (($imagedata[1] - $srchei) / 2); } elseif ($imagedata[0] / $new_iw > $imagedata[1] / $new_ih) { //original to wide $srcwid = (int) ($new_iw * ($imagedata[1] / $new_ih)); $srcx = (int) (($imagedata[0] - $srcwid) / 2); } } //set image type and set image name $ipath = pathinfo($isrc); $itype = strtolower($ipath["extension"]); $iname = substr($ipath["basename"], 0, -(strlen($itype) + 1)) . "_" . $new_iw . "_" . $new_ih . "_" . $iqual . "." . $itype; //check if $idst is set to a subdirectory and if so add it to the path $idir = $idst != "" ? $ipath["dirname"] . "/" . $idst : $ipath["dirname"]; //check if image exists, else create it if (!JFile::exists($idir . "/" . $iname)) { if ($itype == "jpg" && function_exists("imagecreatefromjpeg")) { $image = imagecreatefromjpeg($isrc); $image_dest = imagecreatetruecolor($new_iw, $new_ih); imagecopyresampled($image_dest, $image, 0, 0, $srcx, $srcy, $new_iw, $new_ih, $srcwid, $srchei); ob_start(); // start a new output buffer imagejpeg($image_dest, NULL, $iqual); $buffer = ob_get_contents(); ob_end_clean(); // stop this output buffer } elseif ($itype == "gif" && function_exists("imagecreatefromgif")) { $image = imagecreatefromgif($isrc); $image_dest = imagecreatetruecolor($new_iw, $new_ih); imagealphablending($image_dest, false); // get and reallocate transparency-color $transindex = imagecolortransparent($image); if ($transindex >= 0) { $transcol = imagecolorsforindex($image, $transindex); $transindex = imagecolorallocatealpha($image_dest, $transcol['red'], $transcol['green'], $transcol['blue'], 127); imagefill($image_dest, 0, 0, $transindex); } // resample imagecopyresampled($image_dest, $image, 0, 0, $srcx, $srcy, $new_iw, $new_ih, $srcwid, $srchei); // restore transparency if ($transindex >= 0) { imagecolortransparent($image_dest, $transindex); for ($y = 0; $y < $new_ih; ++$y) { for ($x = 0; $x < $new_iw; ++$x) { if ((imagecolorat($image_dest, $x, $y) >> 24 & 0x7f) >= 100) { imagesetpixel($image_dest, $x, $y, $transindex); } } } } imagetruecolortopalette($image_dest, true, 255); imagesavealpha($image_dest, false); ob_start(); // start a new output buffer imagegif($image_dest, NULL, $iqual); $buffer = ob_get_contents(); ob_end_clean(); // stop this output buffer } elseif ($itype == "png" && function_exists("imagecreatefrompng")) { $image = ImageCreateFromPng($isrc); $image_dest = ImageCreateTrueColor($new_iw, $new_ih); $transindex = imagecolortransparent($image); $istruecolor = imageistruecolor($image); if ($transindex >= 0) { ImageColorTransparent($image_dest, ImageColorAllocate($image_dest, 0, 0, 0)); ImageAlphaBlending($image_dest, false); } elseif (!$istruecolor) { ImagePaletteCopy($image_dest, $image); } else { ImageColorTransparent($image_dest, ImageColorAllocate($image_dest, 0, 0, 0)); ImageAlphaBlending($image_dest, false); ImageSaveAlpha($image_dest, true); } ImageCopyResized($image_dest, $image, 0, 0, $srcx, $srcy, $new_iw, $new_ih, $srcwid, $srchei); $iqual_png = 100 - $iqual; if (substr(phpversion(), 0, 1) >= 5) { $iqual_png = intval(($iqual - 10) / 10); } ob_start(); // start a new output buffer Imagepng($image_dest, NULL, $iqual_png); $buffer = ob_get_contents(); ob_end_clean(); // stop this output buffer } if (isset($buffer) && $buffer != "") { JFile::write($idir . '/' . $iname, $buffer); unset($buffer); } if (isset($image)) { imagedestroy($image); } if (isset($image_dest)) { imagedestroy($image_dest); } } //utf8_encode and rawurlencode file name $iname = rawurlencode(utf8_encode($iname)); //return path/filename/type/width/height return $thenewimage = array($idir . '/' . $iname, $iname, $itype, $new_iw, $new_ih); }
/** * @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()); } } } }
function make_thumb($img_name, $filename, $new_w, $new_h) { $fsize = filesize($img_name); if (!$fsize) { return; } if ($fsize > 100000) { return; } //get image extension. $ext = getExtension($img_name); //creates the new image using the appropriate function from gd library if (!strcmp("jpg", $ext) || !strcmp("jpeg", $ext)) { $src_img = ImageCreateFromJPEG($img_name); } if (!strcmp("JPG", $ext) || !strcmp("JPEG", $ext)) { $src_img = ImageCreateFromJPEG($img_name); } if (!strcmp("gif", $ext)) { $src_img = ImageCreateFromGIF($img_name); } if (!strcmp("GIF", $ext)) { $src_img = ImageCreateFromGIF($img_name); } if (!strcmp("png", $ext)) { $src_img = ImageCreateFromPng($img_name); } if (!strcmp("PNG", $ext)) { $src_img = ImageCreateFromPng($img_name); } if (isset($src_img)) { if ($src_img != '') { //gets the dimmensions of the image $old_x = imageSX($src_img); $old_y = imageSY($src_img); if ($old_x > new_w | $old_y > new_h) { $ratio1 = $old_x / $new_w; $ratio2 = $old_y / $new_h; if ($ratio1 > $ratio2) { $thumb_w = $new_w; $thumb_h = $old_y / $ratio1; } else { $thumb_h = $new_h; $thumb_w = $old_x / $ratio2; } // we create a new image with the new dimmensions if ($old_x < 1000 and $old_y < 1000) { $dst_img = ImageCreateTrueColor($thumb_w, $thumb_h); // resize the big image to the new created one imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y); // output the created image to the file. Now we will have the thumbnail into the // file named by $filename if (!strcmp("png", $ext)) { imagepng($dst_img, $filename); } else { if (!strcmp("gif", $ext)) { imagegif($dst_img, $filename); } else { imagejpeg($dst_img, $filename); } } } } //destroys source and destination images. imagedestroy($dst_img); imagedestroy($src_img); } } }
/** * @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(); } } } }
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; }
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; }
/** * 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; } }
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; break; } $c_x = $_POST["c_x"]; $c_y = $_POST["c_y"];