Example #1
0
 /**
  * Method to apply a background color to an image resource.
  *
  * @param   array  $options  An array of options for the filter.
  *                           color  Background matte color
  *
  * @return  void
  *
  * @since   3.4
  * @throws  InvalidArgumentException
  * @deprecated  5.0  Use Joomla\Image\Filter\Backgroundfill::execute() instead
  */
 public function execute(array $options = array())
 {
     // Validate that the color value exists and is an integer.
     if (!isset($options['color'])) {
         throw new InvalidArgumentException('No color value was given. Expected string or array.');
     }
     $colorCode = !empty($options['color']) ? $options['color'] : null;
     // Get resource dimensions
     $width = imagesX($this->handle);
     $height = imagesY($this->handle);
     // Sanitize color
     $rgba = $this->sanitizeColor($colorCode);
     // Enforce alpha on source image
     if (imageIsTrueColor($this->handle)) {
         imageAlphaBlending($this->handle, false);
         imageSaveAlpha($this->handle, true);
     }
     // Create background
     $bg = imageCreateTruecolor($width, $height);
     imageSaveAlpha($bg, empty($rgba['alpha']));
     // Allocate background color.
     $color = imageColorAllocateAlpha($bg, $rgba['red'], $rgba['green'], $rgba['blue'], $rgba['alpha']);
     // Fill background
     imageFill($bg, 0, 0, $color);
     // Apply image over background
     imageCopy($bg, $this->handle, 0, 0, 0, 0, $width, $height);
     // Move flattened result onto curent handle.
     // If handle was palette-based, it'll stay like that.
     imageCopy($this->handle, $bg, 0, 0, 0, 0, $width, $height);
     // Free up memory
     imageDestroy($bg);
     return;
 }
Example #2
0
 public function createImage($text = '', $fontSize = 5)
 {
     // GD's built-in fonts are numbered from 1 - 5
     $font_size = $fontSize;
     // Calculate the appropriate image size
     $image_height = intval(imageFontHeight($font_size) * 2);
     $image_width = intval(strlen($text) * imageFontWidth($font_size) * 1.3);
     // Create the image
     $image = imageCreate($image_width, $image_height);
     // Create the colors to use in the image
     // gray background
     $back_color = imageColorAllocate($image, 216, 216, 216);
     // blue text
     $text_color = imageColorAllocate($image, 0, 0, 255);
     // black border
     $rect_color = imageColorAllocate($image, 0, 0, 0);
     // Figure out where to draw the text
     // (Centered horizontally and vertically
     $x = ($image_width - imageFontWidth($font_size) * strlen($text)) / 2;
     $y = ($image_height - imageFontHeight($font_size)) / 2;
     // Draw the text
     imageString($image, $font_size, $x, $y, $text, $text_color);
     // Draw a black border
     imageRectangle($image, 0, 0, imageSX($image) - 1, imageSY($image) - 1, $rect_color);
     // Send the image to the browser
     header('Content-Type: image/png');
     imagePNG($image);
     imageDestroy($image);
 }
Example #3
0
 public function resize_image($data, $imgX, $sizedef, $lid, $imgid)
 {
     $file = $data["raw_name"];
     $type = $data["file_ext"];
     $outfile = $imgX[$sizedef]['dir'] . "/" . $lid . "/" . $file . '.jpg';
     $path = $this->config->item("upload_dir");
     $image = $this->create_image_container($file, $type);
     if ($image) {
         $size = GetImageSize($path . $file . $type);
         $old = $image;
         // сей форк - не просто так. непонятно, правда, почему...
         if ($size['1'] < $size['0']) {
             $h_new = round($imgX[$sizedef]['max_dim'] * ($size['1'] / $size['0']));
             $measures = array($imgX[$sizedef]['max_dim'], $h_new);
         }
         if ($size['1'] >= $size['0']) {
             $h_new = round($imgX[$sizedef]['max_dim'] * ($size['0'] / $size['1']));
             $measures = array($h_new, $imgX[$sizedef]['max_dim']);
         }
         $new = ImageCreateTrueColor($measures[0], $measures[1]);
         ImageCopyResampled($new, $image, 0, 0, 0, 0, $measures[0], $measures[1], $size['0'], $size['1']);
         imageJpeg($new, $outfile, $imgX[$sizedef]['quality']);
         $this->db->query("UPDATE `images` SET `images`.`" . $sizedef . "` = ? WHERE `images`.`id` = ?", array(implode($measures, ","), $imgid));
         imageDestroy($new);
     }
 }
Example #4
0
 static function add($file, $wpath)
 {
     if (file_exists($file)) {
         $new_h = 1200;
         // new height for resize image
         $new_w = 1200;
         // new width for resize image
         $image = imagecreatefromjpeg($file);
         // Load the logo image
         $logoImage = imagecreatefrompng(self::getWebDir() . self::WATERMARK);
         // Get dimensions
         $imageWidth = imagesx($image);
         $imageHeight = imagesy($image);
         $logoWidth = imagesx($logoImage);
         $logoHeight = imagesy($logoImage);
         // Paste the lo$filego
         imagecopy($image, $logoImage, ($imageWidth - $logoWidth) / 2, ($imageHeight - $logoHeight) / 2, 0, 0, $logoWidth, $logoHeight);
         // Paste the logo
         $new_image = imagecreatetruecolor($new_w, $new_h);
         imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_w, $new_h, $imageWidth, $imageHeight);
         $mime = self::getMimeType($file);
         $name = self::getName($file);
         if ($mime == 'image/png') {
             imagejpeg($new_image, $wpath, 100);
         } elseif ($mime == 'image/jpeg') {
             imagejpeg($new_image, $wpath, 100);
         } elseif ($mime == 'image/gif') {
             imagejpeg($new_image, $wpath, 100);
         }
         // Release memory
         imageDestroy($image);
         imageDestroy($new_image);
         imageDestroy($logoImage);
     }
 }
Example #5
0
 private function resizeImage($file, $data, $tmd = 600, $quality = 100)
 {
     $data['type'] = "image/jpeg";
     $basename = basename($file);
     $filesDir = $this->input->post('uploadDir');
     // хэш нередактируемой карты!
     $uploaddir = implode(array($this->input->server('DOCUMENT_ROOT'), 'storage', $tmd, $filesDir), DIRECTORY_SEPARATOR);
     $srcFile = implode(array($this->input->server('DOCUMENT_ROOT'), 'storage', 'source', $filesDir, $basename), DIRECTORY_SEPARATOR);
     $image = $this->createimageByType($data, $srcFile);
     if (!file_exists($uploaddir)) {
         mkdir($uploaddir, 0775, true);
     }
     $size = GetImageSize($srcFile);
     $new = ImageCreateTrueColor($size['1'], $size['0']);
     if ($size['1'] > $tmd || $size['0'] > $tmd) {
         if ($size['1'] < $size['0']) {
             $hNew = round($tmd * $size['1'] / $size['0']);
             $new = ImageCreateTrueColor($tmd, $hNew);
             ImageCopyResampled($new, $image, 0, 0, 0, 0, $tmd, $hNew, $size['0'], $size['1']);
         }
         if ($size['1'] >= $size['0']) {
             $hNew = round($tmd * $size['0'] / $size['1']);
             $new = ImageCreateTrueColor($hNew, $tmd);
             ImageCopyResampled($new, $image, 0, 0, 0, 0, $hNew, $tmd, $size['0'], $size['1']);
         }
     }
     //print $uploaddir."/".TMD."/".$filename.".jpg<br>";
     imageJpeg($new, $uploaddir . DIRECTORY_SEPARATOR . $basename, $quality);
     //header("content-type: image/jpeg");// активировать для отладки
     //imageJpeg ($new, "", 100);//активировать для отладки
     imageDestroy($new);
 }
Example #6
0
function king_def()
{
    global $king;
    header("Cache-Control: no-cache, must-revalidate");
    // HTTP/1.1
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
    // 过去的时间
    header("Content-type: image/png");
    $salt = kc_get('salt', 1, 1);
    $width = $king->config('verifywidth');
    //图片长度
    $height = $king->config('verifyheight');
    //图片高度
    $size = $king->config('verifysize');
    //文字大小
    $num = $king->config('verifynum');
    //文字数量
    $content = $king->config('verifycontent');
    //随机字符
    $array_content = explode('|', $content);
    $array_content = array_diff($array_content, array(null));
    $array_font = kc_f_getdir('system/verify_font', 'ttf|ttc');
    $str = '';
    $img = imageCreate($width, $height);
    //创建一个空白图像
    imageFilledRectangle($img, 0, 0, $width, $height, imagecolorallocate($img, 255, 255, 255));
    //写字
    for ($i = 0; $i < $num; $i++) {
        $code = $array_content[array_rand($array_content)];
        $str .= $code;
        //验证码字符
        $color = imageColorAllocate($img, rand(0, 128), rand(0, 128), rand(0, 128));
        $font = 'verify_font/' . $array_font[array_rand($array_font)];
        //随机读取一个字体
        $left = rand(round($size * 0.2), round($size * 0.4)) + $i * $size;
        imagettftext($img, rand(round($size * 0.7), $size), rand(-20, 20), $left, rand(round($size * 1.2), $size * 1.4), $color, $font, $code);
    }
    //画星号
    $max = $width * $height / 400;
    for ($i = 0; $i < $max; $i++) {
        imagestring($img, 15, rand(0, $width), rand(0, $height), '*', rand(192, 250));
    }
    //画点
    $max = $width * $height / 40;
    for ($i = 0; $i < $max; $i++) {
        imageSetPixel($img, rand(0, $width), rand(0, $height), rand(1, 200));
    }
    //画线
    $max = $width * $height / 800;
    for ($i = 0; $i < $max; $i++) {
        imageline($img, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), rand(0, 255));
    }
    //写验证码到verify中
    $verify = new KC_Verify_class();
    $verify->Put($salt, $str);
    imagePng($img);
    imageDestroy($img);
    $verify->Clear();
}
 public function __destruct()
 {
     if ($this->avatar) {
         imageDestroy($this->avatar);
     }
     if ($this->overlay) {
         imageDestroy($this->overlay);
     }
 }
Example #8
0
function create_thumb($path, $thumb_path, $width = THUMB_WIDTH, $height = THUMB_HEIGHT)
{
    $image_info = getImageSize($path);
    // see EXIF for faster way
    switch ($image_info['mime']) {
        case 'image/gif':
            if (imagetypes() & IMG_GIF) {
                // not the same as IMAGETYPE
                $o_im = @imageCreateFromGIF($path);
            } else {
                throw new Exception('GIF images are not supported');
            }
            break;
        case 'image/jpeg':
            if (imagetypes() & IMG_JPG) {
                $o_im = @imageCreateFromJPEG($path);
            } else {
                throw new Exception('JPEG images are not supported');
            }
            break;
        case 'image/png':
            if (imagetypes() & IMG_PNG) {
                $o_im = @imageCreateFromPNG($path);
            } else {
                throw new Exception('PNG images are not supported');
            }
            break;
        case 'image/wbmp':
            if (imagetypes() & IMG_WBMP) {
                $o_im = @imageCreateFromWBMP($path);
            } else {
                throw new Exception('WBMP images are not supported');
            }
            break;
        default:
            throw new Exception($image_info['mime'] . ' images are not supported');
            break;
    }
    list($o_wd, $o_ht, $html_dimension_string) = $image_info;
    $ratio = $o_wd / $o_ht;
    $t_ht = $width;
    $t_wd = $height;
    if (1 > $ratio) {
        $t_wd = round($o_wd * $t_wd / $o_ht);
    } else {
        $t_ht = round($o_ht * $t_ht / $o_wd);
    }
    $t_wd = $t_wd < 1 ? 1 : $t_wd;
    $t_ht = $t_ht < 1 ? 1 : $t_ht;
    $t_im = imageCreateTrueColor($t_wd, $t_ht);
    imageCopyResampled($t_im, $o_im, 0, 0, 0, 0, $t_wd, $t_ht, $o_wd, $o_ht);
    imagejpeg($t_im, $thumb_path, 85);
    chmod($thumb_path, 0664);
    imageDestroy($o_im);
    imageDestroy($t_im);
    return array($t_wd, $t_ht);
}
Example #9
0
 /**
  * Free the memory of the image
  * @return null
  */
 public function __destruct()
 {
     if (!$this->resource) {
         return;
     }
     try {
         imageDestroy($this->resource);
     } catch (Exception $exception) {
     }
 }
Example #10
0
 /**
  * Draws the pie chart, with optional supersampled anti-aliasing.
  * @param int $aa
  */
 public function draw($aa = 4)
 {
     $this->canvas = imageCreateTrueColor($this->width, $this->height);
     // Set anti-aliasing for the pie chart.
     imageAntiAlias($this->canvas, true);
     imageFilledRectangle($this->canvas, 0, 0, $this->width, $this->height, $this->_convertColor($this->backgroundColor));
     $total = 0;
     $sliceStart = -90;
     // Start at 12 o'clock.
     $titleHeight = $this->_drawTitle();
     $legendWidth = $this->_drawLegend($titleHeight);
     // Account for the space occupied by the legend and its padding.
     $pieCentreX = ($this->width - $legendWidth) / 2;
     // Account for the space occupied by the title.
     $pieCentreY = $titleHeight + ($this->height - $titleHeight) / 2;
     // 10% padding on the top and bottom of the pie.
     $pieDiameter = round(min($this->width - $legendWidth, $this->height - $titleHeight) * 0.85);
     foreach ($this->slices as $slice) {
         $total += $slice['value'];
     }
     // If anti-aliasing is enabled, we supersample the pie to work around
     // the fact that GD does not provide anti-aliasing natively.
     if ($aa > 0) {
         $ssDiameter = $pieDiameter * $aa;
         $ssCentreX = $ssCentreY = $ssDiameter / 2;
         $superSample = imageCreateTrueColor($ssDiameter, $ssDiameter);
         imageFilledRectangle($superSample, 0, 0, $ssDiameter, $ssDiameter, $this->_convertColor($this->backgroundColor));
         foreach ($this->slices as $slice) {
             $sliceWidth = 360 * $slice['value'] / $total;
             // Skip slices that are too small to draw / be visible.
             if ($sliceWidth == 0) {
                 continue;
             }
             $sliceEnd = $sliceStart + $sliceWidth;
             imageFilledArc($superSample, $ssCentreX, $ssCentreY, $ssDiameter, $ssDiameter, $sliceStart, $sliceEnd, $this->_convertColor($slice['color']), IMG_ARC_PIE);
             // Move along to the next slice.
             $sliceStart = $sliceEnd;
         }
         imageCopyResampled($this->canvas, $superSample, $pieCentreX - $pieDiameter / 2, $pieCentreY - $pieDiameter / 2, 0, 0, $pieDiameter, $pieDiameter, $ssDiameter, $ssDiameter);
         imageDestroy($superSample);
     } else {
         // Draw the slices.
         foreach ($this->slices as $slice) {
             $sliceWidth = 360 * $slice['value'] / $total;
             // Skip slices that are too small to draw / be visible.
             if ($sliceWidth == 0) {
                 continue;
             }
             $sliceEnd = $sliceStart + $sliceWidth;
             imageFilledArc($this->canvas, $pieCentreX, $pieCentreY, $pieDiameter, $pieDiameter, $sliceStart, $sliceEnd, $this->_convertColor($slice['color']), IMG_ARC_PIE);
             // Move along to the next slice.
             $sliceStart = $sliceEnd;
         }
     }
 }
Example #11
0
 /**
  * Placeholder code adapted from dummyimage.com
  */
 public static function placeholder($width, $height)
 {
     $file_format = 'gif';
     $width = $width;
     $height = $height;
     $text_angle = 0;
     $font = Load::getModulePath('media') . 'assets/mplus-1c-medium.ttf';
     $img = imageCreate($width, $height);
     $bg_color = imageColorAllocate($img, 196, 196, 196);
     $fg_color = imageColorAllocate($img, 94, 94, 94);
     $lines = 1;
     $text = $width . 'x' . $height;
     $fontsize = max(min($width / strlen($text) * 1.15, $height * 0.5), 5);
     $textBox = self::_imagettfbbox_t($fontsize, $text_angle, $font, $text);
     $textWidth = ceil(($textBox[4] - $textBox[1]) * 1.07);
     $textHeight = ceil((abs($textBox[7]) + abs($textBox[1])) * 1);
     $textX = ceil(($width - $textWidth) / 2);
     $textY = ceil(($height - $textHeight) / 2 + $textHeight);
     imageFilledRectangle($img, 0, 0, $width, $height, $bg_color);
     imagettftext($img, $fontsize, $text_angle, $textX, $textY, $fg_color, $font, $text);
     $offset = 60 * 60 * 24 * 14;
     //14 Days
     $ExpStr = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
     header($ExpStr);
     //Set a far future expire date. This keeps the image locally cached by the user for less hits to the server.
     header('Cache-Control:	max-age=120');
     header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - $offset) . " GMT");
     header('Content-type: image/' . $file_format);
     //Set the header so the browser can interpret it as an image and not a bunch of weird text.
     switch ($file_format) {
         case 'gif':
             imagegif($img);
             break;
         case 'png':
             imagepng($img);
             break;
         case 'jpg':
             imagejpeg($img);
             break;
         case 'jpeg':
             imagejpeg($img);
             break;
     }
     imageDestroy($img);
     exit;
 }
Example #12
0
 function AnimatedOut()
 {
     for ($i = 0; $i < ANIM_FRAMES; $i++) {
         $image = imageCreateTrueColor(imageSX($this->image), imageSY($this->image));
         if (imageCopy($image, $this->image, 0, 0, 0, 0, imageSX($this->image), imageSY($this->image))) {
             Captcha::DoNoise($image, 200, 0);
             Ob_Start();
             imageGif($image);
             imageDestroy($image);
             $f_arr[] = Ob_Get_Contents();
             $d_arr[] = ANIM_DELAYS;
             Ob_End_Clean();
         }
     }
     $GIF = new GIFEncoder($f_arr, $d_arr, 0, 2, -1, -1, -1, 'C_MEMORY');
     return $GIF->GetAnimation();
 }
Example #13
0
 function save($save = "", $gd_version)
 {
     if ($gd_version == 2) {
         $this->img["des"] = imagecreatetruecolor($this->img["lebar_thumb"], $this->img["tinggi_thumb"]);
         @imagecopyresampled($this->img["des"], $this->img["src"], 0, 0, 0, 0, $this->img["lebar_thumb"], $this->img["tinggi_thumb"], $this->img["lebar"], $this->img["tinggi"]);
     }
     if ($gd_version == 1) {
         $this->img["des"] = imagecreate($this->img["lebar_thumb"], $this->img["tinggi_thumb"]);
         @imagecopyresized($this->img["des"], $this->img["src"], 0, 0, 0, 0, $this->img["lebar_thumb"], $this->img["tinggi_thumb"], $this->img["lebar"], $this->img["tinggi"]);
     }
     if ($this->img["format"] == "JPG" || $this->img["format"] == "JPEG") {
         //JPEG
         imageJPEG($this->img["des"], "{$save}", $this->img["quality"]);
     } elseif ($this->img["format"] == "PNG") {
         //PNG
         imagePNG($this->img["des"], "{$save}");
     }
     // Memory cleanup
     @imageDestroy($this->img["des"]);
 }
 /**
  * Create test image.
  *
  * @param string $filename
  * @return void
  */
 protected function createTestImage($filename)
 {
     $filename = $this->getFullPath($filename);
     if (!file_exists($filename)) {
         // Create an image with the specified dimensions
         $image = imageCreate(300, 200);
         // Create a color (this first call to imageColorAllocate
         //  also automatically sets the image background color)
         $colorYellow = imageColorAllocate($image, 255, 255, 0);
         // Draw a rectangle
         imageFilledRectangle($image, 50, 50, 250, 150, $colorYellow);
         $directory = dirname($filename);
         if (!file_exists($directory)) {
             mkdir($directory, 0777, true);
         }
         imageJpeg($image, $filename);
         // Release memory
         imageDestroy($image);
     }
 }
Example #15
0
 public static function resize_bg($image, $model, $id, $width, $height)
 {
     $startImage = $image;
     $test_name = 'test-' . $width . '-' . $height . '-' . time() . '.jpg';
     if (!$image) {
         return '/images/blank.png';
     }
     $directory = self::checkAndCreateDirectory($model, $id, self::RESIZE_BG_PATH, $width, $height);
     $imageParts = explode('/', $image);
     $imageName = end($imageParts);
     try {
         $image_factory = Image::factory(PUBLIC_ROOT . 'files/' . $model . '/' . $id . '/' . $imageName);
     } catch (Exception $e) {
         return $startImage;
     }
     try {
         if (!file_exists($directory . $imageName)) {
             $img = imagecreate($width, $height);
             $white = ImageColorAllocate($img, 255, 255, 255);
             ImageFill($img, 0, 0, $white);
             header('Content-Type: image/jpg;');
             $test_file = APPPATH . 'cache/' . $test_name;
             imageJPEG($img, $test_file);
             $image = Image::factory($test_file);
             $image->watermark($image_factory->resize(intval($width), intval($height), Kohana_Image::AUTO))->save($directory . $imageName, 99);
             imageDestroy($img);
             @unlink($test_file);
         }
     } catch (Exception $e) {
         return $startImage;
     }
     $path = '/files/' . self::RESIZE_BG_PATH . '/' . $width;
     if ($height) {
         $path .= 'x' . $height;
     }
     if (file_exists($directory . $imageName)) {
         return $path . '/' . $model . '/' . $id . '/' . $imageName;
     }
     return $startImage;
 }
Example #16
0
function resizeImage($file, $max_x, $max_y, $forcePng = false)
{
    if ($max_x <= 0 || $max_y <= 0) {
        $max_x = 5;
        $max_y = 5;
    }
    $src = BASEDIR . '/avatars/' . $file;
    list($width, $height, $type) = getImageSize($src);
    $scale = min($max_x / $width, $max_y / $height);
    $newWidth = $width * $scale;
    $newHeight = $height * $scale;
    $img = imagecreatefromstring(file_get_contents($src));
    $black = imagecolorallocate($img, 0, 0, 0);
    $resizedImage = imageCreateTrueColor($newWidth, $newHeight);
    imagecolortransparent($resizedImage, $black);
    imageCopyResampled($resizedImage, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
    imageDestroy($img);
    unlink($src);
    if (!$forcePng) {
        switch ($type) {
            case IMAGETYPE_JPEG:
                imageJpeg($resizedImage, BASEDIR . '/avatars/' . $file);
                break;
            case IMAGETYPE_GIF:
                imageGif($resizedImage, BASEDIR . '/avatars/' . $file);
                break;
            case IMAGETYPE_PNG:
                imagePng($resizedImage, BASEDIR . '/avatars/' . $file);
                break;
            default:
                imagePng($resizedImage, BASEDIR . '/avatars/' . $file);
                break;
        }
    } else {
        imagePng($resizedImage, BASEDIR . '/avatars/' . $file . '.png');
    }
    return;
}
Example #17
0
 /**
  * Create thumbnail
  *
  * @param string $sourceFile
  * @param string $targetFile
  * @param int $maxWidth
  * @param int $maxHeight
  * @param boolean $preserverAspectRatio
  * @param boolean $bmpSupported
  * @return boolean
  * @static
  * @access public
  */
 public static function createThumb($sourceFile, $targetFile, $maxWidth, $maxHeight, $quality, $preserverAspectRatio, $bmpSupported = false)
 {
     $sourceImageAttr = @getimagesize($sourceFile);
     if ($sourceImageAttr === false) {
         return false;
     }
     $sourceImageWidth = isset($sourceImageAttr[0]) ? $sourceImageAttr[0] : 0;
     $sourceImageHeight = isset($sourceImageAttr[1]) ? $sourceImageAttr[1] : 0;
     $sourceImageMime = isset($sourceImageAttr["mime"]) ? $sourceImageAttr["mime"] : "";
     $sourceImageBits = isset($sourceImageAttr["bits"]) ? $sourceImageAttr["bits"] : 8;
     $sourceImageChannels = isset($sourceImageAttr["channels"]) ? $sourceImageAttr["channels"] : 3;
     if (!$sourceImageWidth || !$sourceImageHeight || !$sourceImageMime) {
         return false;
     }
     $iFinalWidth = $maxWidth == 0 ? $sourceImageWidth : $maxWidth;
     $iFinalHeight = $maxHeight == 0 ? $sourceImageHeight : $maxHeight;
     if ($sourceImageWidth <= $iFinalWidth && $sourceImageHeight <= $iFinalHeight) {
         if ($sourceFile != $targetFile) {
             copy($sourceFile, $targetFile);
         }
         return true;
     }
     if ($preserverAspectRatio) {
         // Gets the best size for aspect ratio resampling
         $oSize = CKFinder_Connector_CommandHandler_Thumbnail::GetAspectRatioSize($iFinalWidth, $iFinalHeight, $sourceImageWidth, $sourceImageHeight);
     } else {
         $oSize = array('Width' => $iFinalWidth, 'Height' => $iFinalHeight);
     }
     CKFinder_Connector_Utils_Misc::setMemoryForImage($sourceImageWidth, $sourceImageHeight, $sourceImageBits, $sourceImageChannels);
     switch ($sourceImageAttr['mime']) {
         case 'image/gif':
             if (@imagetypes() & IMG_GIF) {
                 $oImage = @imagecreatefromgif($sourceFile);
             } else {
                 $ermsg = 'GIF images are not supported';
             }
             break;
         case 'image/jpeg':
             if (@imagetypes() & IMG_JPG) {
                 $oImage = @imagecreatefromjpeg($sourceFile);
             } else {
                 $ermsg = 'JPEG images are not supported';
             }
             break;
         case 'image/png':
             if (@imagetypes() & IMG_PNG) {
                 $oImage = @imagecreatefrompng($sourceFile);
             } else {
                 $ermsg = 'PNG images are not supported';
             }
             break;
         case 'image/wbmp':
             if (@imagetypes() & IMG_WBMP) {
                 $oImage = @imagecreatefromwbmp($sourceFile);
             } else {
                 $ermsg = 'WBMP images are not supported';
             }
             break;
         case 'image/bmp':
             /*
              * This is sad that PHP doesn't support bitmaps.
              * Anyway, we will use our custom function at least to display thumbnails.
              * We'll not resize images this way (if $sourceFile === $targetFile),
              * because user defined imagecreatefrombmp and imagecreatebmp are horribly slow
              */
             if ($bmpSupported && @imagetypes() & IMG_JPG && $sourceFile != $targetFile) {
                 $oImage = CKFinder_Connector_Utils_Misc::imageCreateFromBmp($sourceFile);
             } else {
                 $ermsg = 'BMP/JPG images are not supported';
             }
             break;
         default:
             $ermsg = $sourceImageAttr['mime'] . ' images are not supported';
             break;
     }
     if (isset($ermsg) || false === $oImage) {
         return false;
     }
     $oThumbImage = imagecreatetruecolor($oSize["Width"], $oSize["Height"]);
     if ($sourceImageAttr['mime'] == 'image/png') {
         $bg = imagecolorallocatealpha($oThumbImage, 255, 255, 255, 127);
         // (PHP 4 >= 4.3.2, PHP 5)
         imagefill($oThumbImage, 0, 0, $bg);
         imagealphablending($oThumbImage, false);
         imagesavealpha($oThumbImage, true);
     }
     //imagecopyresampled($oThumbImage, $oImage, 0, 0, 0, 0, $oSize["Width"], $oSize["Height"], $sourceImageWidth, $sourceImageHeight);
     CKFinder_Connector_Utils_Misc::fastImageCopyResampled($oThumbImage, $oImage, 0, 0, 0, 0, $oSize["Width"], $oSize["Height"], $sourceImageWidth, $sourceImageHeight, (int) max(floor($quality / 20), 6));
     switch ($sourceImageAttr['mime']) {
         case 'image/gif':
             imagegif($oThumbImage, $targetFile);
             break;
         case 'image/jpeg':
         case 'image/bmp':
             imagejpeg($oThumbImage, $targetFile, $quality);
             break;
         case 'image/png':
             imagepng($oThumbImage, $targetFile);
             break;
         case 'image/wbmp':
             imagewbmp($oThumbImage, $targetFile);
             break;
     }
     $_config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config");
     if (file_exists($targetFile) && ($perms = $_config->getChmodFiles())) {
         $oldUmask = umask(0);
         chmod($targetFile, $perms);
         umask($oldUmask);
     }
     imageDestroy($oImage);
     imageDestroy($oThumbImage);
     return true;
 }
 /**
  * Rotate image
  *
  * @param  string   $path               image file
  * @param  int      $degree             rotete degrees
  * @param  string   $bgcolor            square background color in #rrggbb format
  * @param  string   $destformat         image destination format
  * @return string|false
  * @author nao-pon
  * @author Troex Nevelin
  **/
 protected function imgRotate($path, $degree, $bgcolor = '#ffffff', $destformat = null)
 {
     if (($s = @getimagesize($path)) == false) {
         return false;
     }
     $result = false;
     switch ($this->imgLib) {
         case 'imagick':
             try {
                 $img = new imagick($path);
             } catch (Exception $e) {
                 return false;
             }
             $img->rotateImage(new ImagickPixel($bgcolor), $degree);
             $result = $img->writeImage($path);
             return $result ? $path : false;
             break;
         case 'gd':
             if ($s['mime'] == 'image/jpeg') {
                 $img = imagecreatefromjpeg($path);
             } elseif ($s['mime'] == 'image/png') {
                 $img = imagecreatefrompng($path);
             } elseif ($s['mime'] == 'image/gif') {
                 $img = imagecreatefromgif($path);
             } elseif ($s['mime'] == 'image/xbm') {
                 $img = imagecreatefromxbm($path);
             }
             $degree = 360 - $degree;
             list($r, $g, $b) = sscanf($bgcolor, "#%02x%02x%02x");
             $bgcolor = imagecolorallocate($img, $r, $g, $b);
             $tmp = imageRotate($img, $degree, (int) $bgcolor);
             if ($destformat == 'jpg' || $destformat == null && $s['mime'] == 'image/jpeg') {
                 $result = imagejpeg($tmp, $path, 100);
             } else {
                 if ($destformat == 'gif' || $destformat == null && $s['mime'] == 'image/gif') {
                     $result = imagegif($tmp, $path, 7);
                 } else {
                     $result = imagepng($tmp, $path, 7);
                 }
             }
             imageDestroy($img);
             imageDestroy($tmp);
             return $result ? $path : false;
             break;
     }
     return false;
 }
Example #19
0
<?php

include 'phprandom.php';
$img = imageCreateTrueColor(256, 256);
$colors = array();
for ($i = 0; $i < 256; $i++) {
    $colors[$i] = imageColorAllocate($img, $i, $i, $i);
}
for ($i = 0; $i < 256; $i++) {
    $random = PHPRandom::getBinary(256);
    for ($j = 0; $j < 256; $j++) {
        $value = ord(substr($random, $j, 1));
        imageSetPixel($img, $i, $j, $colors[$value]);
    }
}
header('Content-Type: image/png');
imagePNG($img);
imageDestroy($img);
Example #20
0
    $randH = mt_rand(0, imageSY($im));
    imageSetPixel($im, $randW, $randH, $color);
}
imageSetThickness($im, 2);
$color = imageColorAllocate($im, 100, 100, 100);
imageLine($im, 10, 30, 130, 20, $color);
$color = imageColorAllocate($im, 70, 70, 70);
$n1 = mt_rand(0, 9);
imageTtfText($im, 25, 10, mt_rand(2, 10), mt_rand(25, 45), $color, "times.ttf", $n1);
$color = imageColorAllocate($im, 255, 0, 50);
$str = "ABCDIFGHIJKLMNOPKASTUVWXYZ";
$nw = mt_rand(0, 15);
$n2 = $str[$nw];
imageTtftext($im, 22, -10, mt_rand(25, 35), mt_rand(25, 45), $color, "times.ttf", $n2);
$color = imageColorAllocate($im, 50, 50, 50);
$n3 = mt_rand(0, 9);
imageTtfText($im, 25, 15, mt_rand(60, 70), mt_rand(25, 45), $color, "times.ttf", $n3);
$color = imageColorAllocate($im, 250, 250, 250);
$nw2 = mt_rand(15, 25);
$n4 = $str[$nw2];
imageTtfText($im, 22, 30, mt_rand(90, 100), mt_rand(25, 45), $color, "times.ttf", $n4);
$color = imageColorAllocate($im, 255, 220, 70);
$n5 = mt_rand(0, 9);
imageTtfText($im, 25, -20, mt_rand(115, 125), mt_rand(25, 45), $color, "times.ttf", $n5);
$n = $n1 . $n2 . $n3 . $n4 . $n5;
session_start();
$_SESSION['kap'] = md5(strtolower($n));
header("Content-type: image/jpeg");
imageJpeg($im);
imageDestroy($im);
Example #21
0
 public function createSquareThumbnail($sSrc, $sDestination, $iNewWIdth = 0, $iNewHeight = 0, $bSkipCdn = false, $iZoom = 1, $iQuality = 100)
 {
     if (defined('PHPFOX_IS_HOSTED_SCRIPT')) {
         $sSrc = str_replace(PHPFOX_DIR, rtrim(Phpfox::getParam('core.rackspace_url'), '/') . '/', $sSrc);
     }
     if ($iNewWIdth == 0 && $iNewHeight == 0) {
         $iNewWIdth = 100;
         $iNewHeight = 100;
     }
     switch ($this->sType) {
         case 'jpg':
             $hImage = imagecreatefromjpeg($sSrc);
             break;
         case 'png':
             $hImage = imagecreatefrompng($sSrc);
             break;
         case 'gif':
             $hImage = imagecreatefromgif($sSrc);
             break;
     }
     $iWidth = imagesx($hImage);
     $iHeight = imagesy($hImage);
     $origin_x = 0;
     $origin_y = 0;
     if ($iNewWIdth && !$iNewHeight) {
         $iNewHeight = floor($iHeight * ($iNewWIdth / $iWidth));
     } elseif ($iNewHeight && !$iNewWIdth) {
         $iNewWIdth = floor($iWidth * ($iNewHeight / $iHeight));
     }
     if ($iZoom == 3) {
         $final_height = $iHeight * ($iNewWIdth / $iWidth);
         if ($final_height > $iNewHeight) {
             $iNewWIdth = $iWidth * ($iNewHeight / $iHeight);
         } else {
             $iNewHeight = $final_height;
         }
     }
     $hNewImage = imagecreatetruecolor($iNewWIdth, $iNewHeight);
     imagealphablending($hNewImage, false);
     $color = imagecolorallocatealpha($hNewImage, 0, 0, 0, 127);
     imagefill($hNewImage, 0, 0, $color);
     if ($iZoom == 2) {
         $final_height = $iHeight * ($iNewWIdth / $iWidth);
         if ($final_height > $iNewHeight) {
             $origin_x = $iNewWIdth / 2;
             $iNewWIdth = $iWidth * ($iNewHeight / $iHeight);
             $origin_x = round($origin_x - $iNewWIdth / 2);
         } else {
             $origin_y = $iNewHeight / 2;
             $iNewHeight = $final_height;
             $origin_y = round($origin_y - $iNewHeight / 2);
         }
     }
     imagesavealpha($hNewImage, true);
     if ($iZoom > 0) {
         $sSrc_x = $sSrc_y = 0;
         $sSrc_w = $iWidth;
         $sSrc_h = $iHeight;
         $cmp_x = $iWidth / $iNewWIdth;
         $cmp_y = $iHeight / $iNewHeight;
         if ($cmp_x > $cmp_y) {
             $sSrc_w = round($iWidth / $cmp_x * $cmp_y);
             $sSrc_x = round(($iWidth - $iWidth / $cmp_x * $cmp_y) / 2);
         } elseif ($cmp_y > $cmp_x) {
             $sSrc_h = round($iHeight / $cmp_y * $cmp_x);
             $sSrc_y = round(($iHeight - $iHeight / $cmp_y * $cmp_x) / 2);
         }
         imagecopyresampled($hNewImage, $hImage, $origin_x, $origin_y, $sSrc_x, $sSrc_y, $iNewWIdth, $iNewHeight, $sSrc_w, $sSrc_h);
     } else {
         imagecopyresampled($hNewImage, $hImage, 0, 0, 0, 0, $iNewWIdth, $iNewHeight, $iWidth, $iHeight);
     }
     if (file_exists($sDestination)) {
         if (@unlink($sDestination) != true) {
             @rename($sDestination, $sDestination . '_' . rand(10, 99));
         }
     }
     switch ($this->sType) {
         case 'gif':
             if (!$hNewImage) {
                 @copy($this->sPath, $sDestination);
             } else {
                 @imagegif($hNewImage, $sDestination);
             }
             break;
         case 'png':
             imagepng($hNewImage, $sDestination);
             imagealphablending($hNewImage, false);
             imagesavealpha($hNewImage, true);
             break;
         default:
             @imagejpeg($hNewImage, $sDestination);
             break;
     }
     if (($this->sType == 'jpg' || $this->sType == 'jpeg') && function_exists('exif_read_data')) {
         $exif = exif_read_data($sSrc);
         //d($exif);die();
         if (!empty($exif['Orientation'])) {
             switch ($exif['Orientation']) {
                 case 1:
                 case 2:
                     break;
                 case 3:
                 case 4:
                     // 90 degrees
                     $this->rotate($sDestination, 'right');
                     // 180 degrees
                     $this->rotate($sDestination, 'right');
                     break;
                 case 5:
                 case 6:
                     // 90 degrees right
                     $this->rotate($sDestination, 'right');
                     break;
                 case 7:
                 case 8:
                     // 90 degrees left
                     $this->rotate($sDestination, 'left');
                     break;
                 default:
                     break;
             }
         }
     }
     @imageDestroy($hNewImage);
     @imageDestroy($hImage);
     if (Phpfox::getParam('core.allow_cdn')) {
         if ($bSkipCdn === true && $iNewWIdth > 150 || $bSkipCdn === 'force_skip') {
         } else {
             Phpfox::getLib('cdn')->put($sDestination);
         }
     }
 }
 /**
  * Compressing a GIF file if not already LZW compressed.
  * This function is a workaround for the fact that ImageMagick and/or GD does not compress GIF-files to their minimun size (that is RLE or no compression used)
  *
  * The function takes a file-reference, $theFile, and saves it again through GD or ImageMagick in order to compress the file
  * GIF:
  * If $type is not set, the compression is done with ImageMagick (provided that $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw'] is pointing to the path of a lzw-enabled version of 'convert') else with GD (should be RLE-enabled!)
  * If $type is set to either 'IM' or 'GD' the compression is done with ImageMagick and GD respectively
  * PNG:
  * No changes.
  *
  * $theFile is expected to be a valid GIF-file!
  * The function returns a code for the operation.
  *
  * @param string $theFile Filepath
  * @param string $type See description of function
  * @return string Returns "GD" if GD was used, otherwise "IM" if ImageMagick was used. If nothing done at all, it returns empty string.
  */
 public static function gif_compress($theFile, $type)
 {
     $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
     $returnCode = '';
     // GIF...
     if ($gfxConf['gif_compress'] && strtolower(substr($theFile, -4, 4)) == '.gif') {
         // IM
         if (($type == 'IM' || !$type) && $gfxConf['im'] && $gfxConf['im_path_lzw']) {
             // Use temporary file to prevent problems with read and write lock on same file on network file systems
             $temporaryName = dirname($theFile) . '/' . md5(uniqid('', TRUE)) . '.gif';
             // Rename could fail, if a simultaneous thread is currently working on the same thing
             if (@rename($theFile, $temporaryName)) {
                 $cmd = self::imageMagickCommand('convert', '"' . $temporaryName . '" "' . $theFile . '"', $gfxConf['im_path_lzw']);
                 \TYPO3\CMS\Core\Utility\CommandUtility::exec($cmd);
                 unlink($temporaryName);
             }
             $returnCode = 'IM';
             if (@is_file($theFile)) {
                 self::fixPermissions($theFile);
             }
         } elseif (($type == 'GD' || !$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png']) {
             // GD
             $tempImage = imageCreateFromGif($theFile);
             imageGif($tempImage, $theFile);
             imageDestroy($tempImage);
             $returnCode = 'GD';
             if (@is_file($theFile)) {
                 self::fixPermissions($theFile);
             }
         }
     }
     return $returnCode;
 }
Example #23
0
 public static function createThumb($sourceFile, $targetFile, $maxWidth, $maxHeight, $quality = 80, $preserverAspectRatio = true, $bmpSupported = false)
 {
     $dir = dirname($targetFile);
     @mkdir($dir, 0777, true);
     $sourceImageAttr = @getimagesize($sourceFile);
     if ($sourceImageAttr === false) {
         return false;
     }
     $sourceImageWidth = isset($sourceImageAttr[0]) ? $sourceImageAttr[0] : 0;
     $sourceImageHeight = isset($sourceImageAttr[1]) ? $sourceImageAttr[1] : 0;
     $sourceImageMime = isset($sourceImageAttr["mime"]) ? $sourceImageAttr["mime"] : "";
     $sourceImageBits = isset($sourceImageAttr["bits"]) ? $sourceImageAttr["bits"] : 8;
     $sourceImageChannels = isset($sourceImageAttr["channels"]) ? $sourceImageAttr["channels"] : 3;
     if (!$sourceImageWidth || !$sourceImageHeight || !$sourceImageMime) {
         return false;
     }
     $iFinalWidth = $maxWidth == 0 ? $sourceImageWidth : $maxWidth;
     $iFinalHeight = $maxHeight == 0 ? $sourceImageHeight : $maxHeight;
     if ($sourceImageWidth <= $iFinalWidth && $sourceImageHeight <= $iFinalHeight) {
         if ($sourceFile != $targetFile) {
             copy($sourceFile, $targetFile);
         }
         return true;
     }
     if ($preserverAspectRatio) {
         // Gets the best size for aspect ratio resampling
         $oSize = self::getAspectRatioSize($iFinalWidth, $iFinalHeight, $sourceImageWidth, $sourceImageHeight);
     } else {
         $oSize = ['Width' => $iFinalWidth, 'Height' => $iFinalHeight];
     }
     self::setMemoryForImage($sourceImageWidth, $sourceImageHeight, $sourceImageBits, $sourceImageChannels);
     switch ($sourceImageAttr['mime']) {
         case 'image/gif':
             if (@imagetypes() & IMG_GIF) {
                 $oImage = @imagecreatefromgif($sourceFile);
             } else {
                 $ermsg = 'GIF images are not supported';
             }
             break;
         case 'image/jpeg':
             if (@imagetypes() & IMG_JPG) {
                 $oImage = @imagecreatefromjpeg($sourceFile);
             } else {
                 $ermsg = 'JPEG images are not supported';
             }
             break;
         case 'image/png':
             if (@imagetypes() & IMG_PNG) {
                 $oImage = @imagecreatefrompng($sourceFile);
             } else {
                 $ermsg = 'PNG images are not supported';
             }
             break;
         case 'image/wbmp':
             if (@imagetypes() & IMG_WBMP) {
                 $oImage = @imagecreatefromwbmp($sourceFile);
             } else {
                 $ermsg = 'WBMP images are not supported';
             }
             break;
         case 'image/bmp':
             /*
              * This is sad that PHP doesn't support bitmaps.
              * Anyway, we will use our custom function at least to display thumbnails.
              * We'll not resize images this way (if $sourceFile === $targetFile),
              * because user defined imagecreatefrombmp and imagecreatebmp are horribly slow
              */
             if ($bmpSupported && @imagetypes() & IMG_JPG && $sourceFile != $targetFile) {
                 $oImage = self::imageCreateFromBmp($sourceFile);
             } else {
                 $ermsg = 'BMP/JPG images are not supported';
             }
             break;
         default:
             $ermsg = $sourceImageAttr['mime'] . ' images are not supported';
             break;
     }
     if (isset($ermsg) || false === $oImage) {
         // echo $ermsg."\r\n";
         return false;
     }
     $oThumbImage = imagecreatetruecolor($oSize["Width"], $oSize["Height"]);
     if ($sourceImageAttr['mime'] == 'image/png' || $sourceImageAttr['mime'] == 'image/gif') {
         imagealphablending($oThumbImage, false);
         imagesavealpha($oThumbImage, true);
         $transparent = imagecolorallocatealpha($oThumbImage, 255, 255, 255, 127);
         imagefilledrectangle($oThumbImage, 0, 0, $oSize["Width"], $oSize["Height"], $transparent);
     }
     //imagecopyresampled($oThumbImage, $oImage, 0, 0, 0, 0, $oSize["Width"], $oSize["Height"], $sourceImageWidth, $sourceImageHeight);
     self::fastImageCopyResampled($oThumbImage, $oImage, 0, 0, 0, 0, $oSize["Width"], $oSize["Height"], $sourceImageWidth, $sourceImageHeight, (int) max(floor($quality / 20), 1));
     switch ($sourceImageAttr['mime']) {
         case 'image/gif':
             imagegif($oThumbImage, $targetFile);
             break;
         case 'image/jpeg':
         case 'image/bmp':
             imagejpeg($oThumbImage, $targetFile, $quality);
             break;
         case 'image/png':
             imagepng($oThumbImage, $targetFile);
             break;
         case 'image/wbmp':
             imagewbmp($oThumbImage, $targetFile);
             break;
     }
     if (file_exists($targetFile)) {
         $oldUmask = umask(0);
         chmod($targetFile, 0777);
         umask($oldUmask);
     }
     imageDestroy($oImage);
     imageDestroy($oThumbImage);
     return true;
 }
Example #24
0
 /**
  * ฟังก์ชั่นปรับขนาดของภาพ โดยรักษาอัตราส่วนของภาพตามความกว้างที่ต้องการ
  * หากรูปภาพมีขนาดเล็กกว่าที่กำหนด จะเป็นการ copy file
  * หากรูปภาพมาความสูง หรือความกว้างมากกว่า $width
  * จะถูกปรับขนาดให้มีขนาดไม่เกิน $width (ทั้งความสูงและความกว้าง)
  * และเปลี่ยนชนิดของภาพเป็น jpg
  *
  * @param string $source path และชื่อไฟล์ของไฟล์รูปภาพต้นฉบับ
  * @param string $target path ของไฟล์รูปภาพปลายทาง
  * @param string $name ชื่อไฟล์ของรูปภาพปลายทาง
  * @param int $width ขนาดสูงสุดของรูปภาพที่ต้องการ
  * @param string $watermark (optional) ข้อความลายน้ำ
  * @return array|bool คืนค่าแอเรย์ [name, width, height, mime] ของรูปภาพปลายทาง หรือ false ถ้าไม่สามารถดำเนินการได้
  */
 public static function resize($source, $target, $name, $width, $watermark = '')
 {
     $info = @getImageSize($source);
     if ($info[0] > $width || $info[1] > $width) {
         switch ($info['mime']) {
             case 'image/gif':
                 $o_im = imageCreateFromGIF($source);
                 break;
             case 'image/jpg':
             case 'image/jpeg':
             case 'image/pjpeg':
                 $o_im = self::orient($source);
                 break;
             case 'image/png':
             case 'image/x-png':
                 $o_im = imageCreateFromPNG($source);
                 break;
         }
         $o_wd = @imagesx($o_im);
         $o_ht = @imagesy($o_im);
         if ($o_wd <= $o_ht) {
             $h = $width;
             $w = round($h * $o_wd / $o_ht);
         } else {
             $w = $width;
             $h = round($w * $o_ht / $o_wd);
         }
         $t_im = @ImageCreateTrueColor($w, $h);
         @ImageCopyResampled($t_im, $o_im, 0, 0, 0, 0, $w + 1, $h + 1, $o_wd, $o_ht);
         if ($watermark != '') {
             $t_im = self::watermarkText($t_im, $watermark);
         }
         $newname = substr($name, 0, strrpos($name, '.')) . '.jpg';
         if (!@ImageJPEG($t_im, $target . $newname, self::$quality)) {
             $ret = false;
         } else {
             $ret['name'] = $newname;
             $ret['width'] = $w;
             $ret['height'] = $h;
             $ret['mime'] = 'image/jpeg';
         }
         @imageDestroy($o_im);
         @imageDestroy($t_im);
         return $ret;
     } elseif (@copy($source, $target . $name)) {
         $ret['name'] = $name;
         $ret['width'] = $info[0];
         $ret['height'] = $info[1];
         $ret['mime'] = $info['mime'];
         return $ret;
     }
     return false;
 }
 /**
  * Rotate image
  *
  * @param  string   $path               image file
  * @param  int      $degree             rotete degrees
  * @param  string   $bgcolor            square background color in #rrggbb format
  * @param  string   $destformat         image destination format
  * @return string|false
  * @author nao-pon
  * @author Troex Nevelin
  **/
 protected function imgRotate($path, $degree, $bgcolor = '#ffffff', $destformat = null)
 {
     if (($s = @getimagesize($path)) == false || $degree % 360 === 0) {
         return false;
     }
     $result = false;
     // try lossless rotate
     if ($degree % 90 === 0 && in_array($s[2], array(IMAGETYPE_JPEG, IMAGETYPE_JPEG2000))) {
         $count = $degree / 90 % 4;
         $exiftran = array(1 => '-9', 2 => '-1', 3 => '-2');
         $jpegtran = array(1 => '90', 2 => '180', 3 => '270');
         $quotedPath = escapeshellarg($path);
         $cmds = array('exiftran -i ' . $exiftran[$count] . ' ' . $path, 'jpegtran -rotate ' . $jpegtran[$count] . ' -copy all -outfile ' . $quotedPath . ' ' . $quotedPath);
         foreach ($cmds as $cmd) {
             if ($this->procExec($cmd) === 0) {
                 $result = true;
                 break;
             }
         }
         if ($result) {
             return $path;
         }
     }
     switch ($this->imgLib) {
         case 'imagick':
             try {
                 $img = new imagick($path);
             } catch (Exception $e) {
                 return false;
             }
             if ($img->getNumberImages() > 1) {
                 $img = $img->coalesceImages();
                 do {
                     $img->rotateImage(new ImagickPixel($bgcolor), $degree);
                 } while ($img->nextImage());
                 $img = $img->optimizeImageLayers();
                 $result = $img->writeImages($path, true);
             } else {
                 $img->rotateImage(new ImagickPixel($bgcolor), $degree);
                 $result = $img->writeImage($path);
             }
             $img->destroy();
             return $result ? $path : false;
             break;
         case 'gd':
             $img = self::gdImageCreate($path, $s['mime']);
             $degree = 360 - $degree;
             list($r, $g, $b) = sscanf($bgcolor, "#%02x%02x%02x");
             $bgcolor = imagecolorallocate($img, $r, $g, $b);
             $tmp = imageRotate($img, $degree, (int) $bgcolor);
             $result = self::gdImage($tmp, $path, $destformat, $s['mime']);
             imageDestroy($img);
             imageDestroy($tmp);
             return $result ? $path : false;
             break;
     }
     return false;
 }
Example #26
0
// For now, all borders are dark
//$lightBorder = "000000";
$darkBorder = "000000";


$image = imageCreateFromPNG($iconDirectoryPath . $iconName);
$phpFillIndex = imageColorClosest($image,$existingFill['r'],$existingFill['g'],$existingFill['b']);
imageColorSet($image,$phpFillIndex,$fill['r'],$fill['g'],$fill['b']);
$phpDarkBorderIndex = imageColorClosest($image,$existingDarkBorder['r'],$existingDarkBorder['g'],$existingDarkBorder['b']);
imageColorSet($image,$phpDarkBorderIndex,$darkBorder['r'],$darkBorder['g'],$darkBorder['b']);
$phpLightBorderIndex = imageColorClosest($image,$existingLightBorder['r'],$existingLightBorder['g'],$existingLightBorder['b']);
imageColorSet($image,$phpLightBorderIndex,$lightBorder['r'],$lightBorder['g'],$lightBorder['b']);

header('Content-type: image/png');
imagePNG($image);
imageDestroy($image);


/**
 * @param    $hex string        6-digit hexadecimal color
 * @return    array            3 elements 'r', 'g', & 'b' = int color values
 * @desc Converts a 6 digit hexadecimal number into an array of
 *       3 integer values ('r'  => red value, 'g'  => green, 'b'  => blue)
 */
function hex2int($hex) {
        return array( 'r' => hexdec(substr($hex, 0, 2)), // 1st pair of digits
                      'g' => hexdec(substr($hex, 2, 2)), // 2nd pair
                      'b' => hexdec(substr($hex, 4, 2))  // 3rd pair
                    );
}
Example #27
0
/**
* Generate images of alternate sizes.
*/
function resizeImage($cnvrt_arry)
{
    global $platform, $imgs, $cnvrt_path, $reqd_image, $convert_writable, $convert_magick, $convert_GD, $convert_cmd, $cnvrt_alt, $cnvrt_mesgs, $compat_quote;
    if (empty($imgs) || $convert_writable == FALSE) {
        return;
    }
    if ($convert_GD == TRUE && !($gd_version = gdVersion())) {
        return;
    }
    if ($cnvrt_alt['no_prof'] == TRUE) {
        $strip_prof = ' +profile "*"';
    } else {
        $strip_prof = '';
    }
    if ($cnvrt_alt['mesg_on'] == TRUE) {
        $str = '';
    }
    foreach ($imgs as $img_file) {
        if ($cnvrt_alt['indiv'] == TRUE && $img_file != $reqd_image['file']) {
            continue;
        }
        $orig_img = $reqd_image['pwd'] . '/' . $img_file;
        $cnvrtd_img = $cnvrt_path . '/' . $cnvrt_arry['prefix'] . $img_file;
        if (!is_file($cnvrtd_img)) {
            $img_size = GetImageSize($orig_img);
            $height = $img_size[1];
            $width = $img_size[0];
            $area = $height * $width;
            $maxarea = $cnvrt_arry['maxwid'] * $cnvrt_arry['maxwid'] * 0.9;
            $maxheight = $cnvrt_arry['maxwid'] * 0.75 + 1;
            if ($area > $maxarea || $width > $cnvrt_arry['maxwid'] || $height > $maxheight) {
                if ($width / $cnvrt_arry['maxwid'] >= $height / $maxheight) {
                    $dim = 'W';
                }
                if ($height / $maxheight >= $width / $cnvrt_arry['maxwid']) {
                    $dim = 'H';
                }
                if ($dim == 'W') {
                    $cnvt_percent = round(0.9375 * $cnvrt_arry['maxwid'] / $width * 100, 2);
                }
                if ($dim == 'H') {
                    $cnvt_percent = round(0.75 * $cnvrt_arry['maxwid'] / $height * 100, 2);
                }
                // convert it
                if ($convert_magick == TRUE) {
                    // Image Magick image conversion
                    if ($platform == 'Win32' && $compat_quote == TRUE) {
                        $winquote = '"';
                    } else {
                        $winquote = '';
                    }
                    exec($winquote . $convert_cmd . ' -geometry ' . $cnvt_percent . '%' . ' -quality ' . $cnvrt_arry['qual'] . ' -sharpen ' . $cnvrt_arry['sharpen'] . $strip_prof . ' "' . $orig_img . '"' . ' "' . $cnvrtd_img . '"' . $winquote);
                    $using = $cnvrt_mesgs['using IM'];
                } elseif ($convert_GD == TRUE) {
                    // GD image conversion
                    if (eregi('\\.jpg$|\\.jpeg$', $img_file) == TRUE && (imageTypes() & IMG_JPG) == TRUE) {
                        $src_img = imageCreateFromJpeg($orig_img);
                    } elseif (eregi('\\.gif$', $img_file) == TRUE && (imageTypes() & IMG_PNG) == TRUE) {
                        $src_img = imageCreateFromPng($orig_img);
                    } elseif (eregi('\\.gif$', $img_file) == TRUE && (imageTypes() & IMG_GIF) == TRUE) {
                        $src_img = imageCreateFromGif($orig_img);
                    } else {
                        continue;
                    }
                    $src_width = imageSx($src_img);
                    $src_height = imageSy($src_img);
                    $dest_width = $src_width * ($cnvt_percent / 100);
                    $dest_height = $src_height * ($cnvt_percent / 100);
                    if ($gd_version >= 2) {
                        $dst_img = imageCreateTruecolor($dest_width, $dest_height);
                        imageCopyResampled($dst_img, $src_img, 0, 0, 0, 0, $dest_width, $dest_height, $src_width, $src_height);
                    } else {
                        $dst_img = imageCreate($dest_width, $dest_height);
                        imageCopyResized($dst_img, $src_img, 0, 0, 0, 0, $dest_width, $dest_height, $src_width, $src_height);
                    }
                    imageDestroy($src_img);
                    if (eregi('\\.jpg$|\\.jpeg$/i', $img_file) == TRUE && (imageTypes() & IMG_JPG) == TRUE) {
                        imageJpeg($dst_img, $cnvrtd_img, $cnvrt_arry['qual']);
                    } elseif (eregi('\\.gif$', $img_file) == TRUE && (imageTypes() & IMG_PNG) == TRUE) {
                        imagePng($dst_img, $cnvrtd_img);
                    } elseif (eregi('\\.gif$/i', $img_file) == TRUE && (imageTypes() & IMG_GIF) == TRUE) {
                        imageGif($dst_img, $cnvrtd_img);
                    }
                    imageDestroy($dst_img);
                    $using = $cnvrt_mesgs['using GD'] . $gd_version;
                }
                if ($cnvrt_alt['mesg_on'] == TRUE && is_file($cnvrtd_img)) {
                    $str .= "  <small>\n" . '   ' . $cnvrt_mesgs['generated'] . $cnvrt_arry['txt'] . $cnvrt_mesgs['converted'] . $cnvrt_mesgs['image_for'] . $img_file . $using . ".\n" . "  </small>\n  <br />\n";
                }
            }
        }
    }
    if (isset($str)) {
        return $str;
    }
}
 /**
  * Rotate image
  *
  * @param  string   $path               image file
  * @param  int      $degree             rotete degrees
  * @param  string   $bgcolor            square background color in #rrggbb format
  * @param  string   $destformat         image destination format
  * @return string|false
  * @author nao-pon
  * @author Troex Nevelin
  **/
 protected function imgRotate($path, $degree, $bgcolor = '#ffffff', $destformat = null)
 {
     if (($s = @getimagesize($path)) == false) {
         return false;
     }
     $result = false;
     switch ($this->imgLib) {
         case 'imagick':
             try {
                 $img = new imagick($path);
             } catch (Exception $e) {
                 return false;
             }
             $img->rotateImage(new ImagickPixel($bgcolor), $degree);
             $result = $img->writeImage($path);
             return $result ? $path : false;
             break;
         case 'gd':
             $img = self::gdImageCreate($path, $s['mime']);
             $degree = 360 - $degree;
             list($r, $g, $b) = sscanf($bgcolor, "#%02x%02x%02x");
             $bgcolor = imagecolorallocate($img, $r, $g, $b);
             $tmp = imageRotate($img, $degree, (int) $bgcolor);
             $result = self::gdImage($tmp, $path, $destformat, $s['mime']);
             imageDestroy($img);
             imageDestroy($tmp);
             return $result ? $path : false;
             break;
     }
     return false;
 }
Example #29
0
 /**
  * Destroy the target for the provided temporary object
  *
  * @param Asido_TMP &$tmp
  * @return boolean
  * @access protected
  * @abstract
  */
 function __destroy_target(&$tmp)
 {
     return imageDestroy($tmp->target);
 }
Example #30
0
 /**
  * Destructor: destroy
  *
  * Destroys all allocated resources.
  */
 function destroy()
 {
     imageDestroy($this->image);
 }