示例#1
1
 public static function copyFromUrl($url, $target)
 {
     if (!@copy($url, $target)) {
         $http = new JO_Http();
         $http->useCurl(true);
         if (($host = JO_Validate::validateHost($url)) !== false) {
             $http->setReferrer('http://' . $host);
         }
         $http->execute($url);
         if ($http->error) {
             return false;
         } else {
             $im = @ImageCreateFromString($http->result);
             if (!$im) {
                 return false;
             }
             return @file_put_contents($target, $im);
         }
     } else {
         return true;
     }
 }
 function getimagesize_remote($image_url)
 {
     $handle = fopen($image_url, "rb");
     $contents = '';
     if ($handle) {
         do {
             $count += 1;
             $data = fread($handle, 8192);
             if (strlen($data) == 0) {
                 break;
             }
             $contents .= $data;
         } while (true);
     } else {
         return false;
     }
     fclose($handle);
     $im = ImageCreateFromString($contents);
     if (!$im) {
         return false;
     }
     $gis[0] = ImageSX($im);
     $gis[1] = ImageSY($im);
     $gis[3] = "width={$gis[0]} height={$gis[1]}";
     ImageDestroy($im);
     return $gis;
 }
示例#3
0
function getimagesize_remote($image_url)
{
    if (($handle = @fopen($image_url, "rb")) != true) {
        return;
    }
    $contents = "";
    $count = 0;
    if ($handle) {
        do {
            $count += 1;
            $data = fread($handle, 8192);
            if (strlen($data) == 0) {
                break;
            }
            $contents .= $data;
        } while (true);
    } else {
        return false;
    }
    fclose($handle);
    $im = ImageCreateFromString($contents);
    if (!$im) {
        return false;
    }
    $gis[0] = ImageSX($im);
    $gis[1] = ImageSY($im);
    // array member 3 is used below to keep with current getimagesize standards
    $gis[3] = "width={$gis[0]} height={$gis[1]}";
    ImageDestroy($im);
    return $gis;
}
示例#4
0
 function loadImageFromString($string)
 {
     $this->_imgOrig = @ImageCreateFromString($string);
     if (!$this->_imgOrig) {
         $this->_debug('loadImageFromString', 'The image could not be loaded.');
         return false;
     }
     return true;
 }
示例#5
0
function Error()
{
    header('Content-Type: image/gif');
    header('Content-Disposition: inline; filename="fakeapple.gif"');
    $blank = 'R0lGODlhAQABAPAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';
    // A transparent 1x1 GIF image
    $image = ImageCreateFromString(base64_decode($blank));
    ImageGif($image);
    ImageDestroy($image);
    die;
}
示例#6
0
 public function getImage($objUser)
 {
     $img = ImageCreateFromString(base64_decode($this->getFrom('imagedata', 'data')));
     $objPicture = new clsPicture($this->get('picture_id'));
     if (!$objPicture->hasViewed($objUser)) {
         $newImage = clsThumbnail::getNewImage();
         list($newWidth, $newHeight) = clsThumbnail::getNewSize();
         ImageCopyMerge($img, $newImage, $this->get('actual_width') - $newWidth, $this->get('actual_height') - $newHeight, 0, 0, $newWidth, $newHeight, 75);
         ImageDestroy($newImage);
     }
     return $img;
 }
function dissimilarityIndexCalculator($str_img, $str_match)
{
    //Try to make images from the urls, on fail return false.
    $img_source = @ImageCreateFromString($str_img);
    $img_match = @ImageCreateFromString($str_match);
    if (!$img_source || !$img_match) {
        return false;
    }
    //Get image sizes.
    //list($int_img_source_width, $int_img_source_height)     = getimagesizefromstring ($str_img);
    //list($int_img_match_width, $int_img_match_height)   = getimagesizefromstring ($str_match);
    $int_img_source_width = imagesx($img_source);
    $int_img_source_height = imagesy($img_source);
    $int_img_match_width = imagesx($img_match);
    $int_img_match_height = imagesy($img_match);
    //Resample to 16px each
    $compareSize = 16;
    $img_16source = imagecreatetruecolor($compareSize, $compareSize);
    $bg = imagecolorallocate($img_16source, 96, 96, 96);
    imagefilledrectangle($img_16source, 0, 0, $compareSize, $compareSize, $bg);
    $img_16match = imagecreatetruecolor($compareSize, $compareSize);
    $bg = imagecolorallocate($img_16match, 96, 96, 96);
    imagefilledrectangle($img_16match, 0, 0, $compareSize, $compareSize, $bg);
    imagecopyresampled($img_16source, $img_source, 0, 0, 0, 0, $compareSize, $compareSize, $int_img_source_width, $int_img_source_width);
    imagecopyresampled($img_16match, $img_match, 0, 0, 0, 0, $compareSize, $compareSize, $int_img_match_width, $int_img_match_width);
    $difference = 0;
    for ($x = 0; $x < $compareSize; $x++) {
        for ($y = 0; $y < $compareSize; $y++) {
            //Get the color of the resulting image
            $arr_img_source_color[$x][$y] = imagecolorsforindex($img_16source, imagecolorat($img_16source, $x, $y));
            $arr_img_match_color[$x][$y] = imagecolorsforindex($img_16match, imagecolorat($img_16match, $x, $y));
            //Calculate the index
            $difference += abs($arr_img_source_color[$x][$y]['red'] - $arr_img_match_color[$x][$y]['red']) + abs($arr_img_source_color[$x][$y]['green'] - $arr_img_match_color[$x][$y]['green']) + abs($arr_img_source_color[$x][$y]['blue'] - $arr_img_match_color[$x][$y]['blue']) + abs($arr_img_source_color[$x][$y]['alpha'] - $arr_img_match_color[$x][$y]['alpha']);
            //error_log("[$x,$y], " . $arr_img_source_color[$x][$y]['red'] . ', ' . $arr_img_match_color[$x][$y]['red']);
        }
    }
    $difference = $difference / 256;
    //Return an array with the information
    $arr_return = array("dissimilarityIndex" => $difference, "sourceImage" => array("width" => $int_img_source_width, "height" => $int_img_source_height), "matchImage" => array("width" => $int_img_match_width, "height" => $int_img_match_height));
    /*
    	imagepng($img_16source, "temp/left-{$compareSize}px.png");
    	imagepng($img_16match, "temp/right-{$compareSize}px.png");
    	// */
    return $arr_return;
}
示例#8
0
 function create($data)
 {
     $this->destroy();
     if (file_exists($data)) {
         $this->img = @ImageCreateFromJpeg($data);
         $this->fileInfo = basename($data);
         $this->fullName = $data;
     } else {
         $this->img = @ImageCreateFromString($data);
     }
     if (!$this->img) {
         $this->destroy();
         return false;
     } else {
         $this->orgX = ImageSX($this->img);
         $this->orgY = ImageSY($this->img);
         return true;
     }
 }
示例#9
0
文件: GH21Test.php 项目: lsolesen/pel
 function testThisDoesNotWorkAsExpected()
 {
     $scale = 0.75;
     $input_jpeg = new PelJpeg($this->file);
     $original = ImageCreateFromString($input_jpeg->getBytes());
     $original_w = ImagesX($original);
     $original_h = ImagesY($original);
     $scaled_w = $original_w * $scale;
     $scaled_h = $original_h * $scale;
     $scaled = ImageCreateTrueColor($scaled_w, $scaled_h);
     ImageCopyResampled($scaled, $original, 0, 0, 0, 0, $scaled_w, $scaled_h, $original_w, $original_h);
     $output_jpeg = new PelJpeg($scaled);
     $exif = $input_jpeg->getExif();
     if ($exif !== null) {
         $output_jpeg->setExif($exif);
     }
     file_put_contents($this->file, $output_jpeg->getBytes());
     $jpeg = new PelJpeg($this->file);
     $exifin = $jpeg->getExif();
     $this->assertEquals($exif, $exifin);
 }
示例#10
0
function dissimilarityIndexCalculator($str_img, $str_match)
{
    //Try to make images from the urls, on fail return false.
    $img_source = @ImageCreateFromString($str_img);
    $img_match = @ImageCreateFromString($str_match);
    if (!$img_source || !$img_match) {
        return false;
    }
    //Get image sizes.
    //list($int_img_source_width, $int_img_source_height)     = getimagesizefromstring ($str_img);
    //list($int_img_match_width, $int_img_match_height)   = getimagesizefromstring ($str_match);
    $int_img_source_width = imagesx($img_source);
    $int_img_source_height = imagesy($img_source);
    $int_img_match_width = imagesx($img_match);
    $int_img_match_height = imagesy($img_match);
    //Resample to 16px each
    $img_16source = imagecreatetruecolor(16, 16);
    $img_16match = imagecreatetruecolor(16, 16);
    imagecopyresampled($img_16source, $img_source, 0, 0, 0, 0, 16, 16, $int_img_source_width, $int_img_source_width);
    imagecopyresampled($img_16match, $img_match, 0, 0, 0, 0, 16, 16, $int_img_match_width, $int_img_match_width);
    $difference = 0;
    for ($x = 0; $x < 16; $x++) {
        for ($y = 0; $y < 16; $y++) {
            //Get the color of the resulting image
            $arr_img_source_color[$x][$y] = imagecolorsforindex($img_16source, imagecolorat($img_16source, $x, $y));
            $arr_img_match_color[$x][$y] = imagecolorsforindex($img_16match, imagecolorat($img_16match, $x, $y));
            //Calculate the index
            //echo $arr_img_source_color[$x][$y]['red']  ." - ". $arr_img_match_color['red'] ."\n";
            $difference += abs($arr_img_source_color[$x][$y]['red'] - $arr_img_match_color[$x][$y]['red']) + abs($arr_img_source_color[$x][$y]['green'] - $arr_img_match_color[$x][$y]['green']) + abs($arr_img_source_color[$x][$y]['blue'] - $arr_img_match_color[$x][$y]['blue']);
        }
    }
    $difference = $difference / 256;
    //Return an array with the information
    $arr_return = array("dissimilarityIndex" => $difference, "sourceImage" => array("width" => $int_img_source_width, "height" => $int_img_source_height), "matchImage" => array("width" => $int_img_match_width, "height" => $int_img_match_height));
    return $arr_return;
}
示例#11
0
 function ImageCreateFromStringReplacement(&$RawImageData, $DieOnErrors = false)
 {
     // there are serious bugs in the non-bundled versions of GD which may cause
     // PHP to segfault when calling ImageCreateFromString() - avoid if at all possible
     // when not using a bundled version of GD2
     if (!phpthumb_functions::gd_version()) {
         if ($DieOnErrors) {
             if (!headers_sent()) {
                 // base64-encoded error image in GIF format
                 $ERROR_NOGD = 'R0lGODlhIAAgALMAAAAAABQUFCQkJDY2NkZGRldXV2ZmZnJycoaGhpSUlKWlpbe3t8XFxdXV1eTk5P7+/iwAAAAAIAAgAAAE/vDJSau9WILtTAACUinDNijZtAHfCojS4W5H+qxD8xibIDE9h0OwWaRWDIljJSkUJYsN4bihMB8th3IToAKs1VtYM75cyV8sZ8vygtOE5yMKmGbO4jRdICQCjHdlZzwzNW4qZSQmKDaNjhUMBX4BBAlmMywFSRWEmAI6b5gAlhNxokGhooAIK5o/pi9vEw4Lfj4OLTAUpj6IabMtCwlSFw0DCKBoFqwAB04AjI54PyZ+yY3TD0ss2YcVmN/gvpcu4TOyFivWqYJlbAHPpOntvxNAACcmGHjZzAZqzSzcq5fNjxFmAFw9iFRunD1epU6tsIPmFCAJnWYE0FURk7wJDA0MTKpEzoWAAskiAAA7';
                 header('Content-Type: image/gif');
                 echo base64_decode($ERROR_NOGD);
             } else {
                 echo '*** ERROR: No PHP-GD support available ***';
             }
             exit;
         } else {
             $this->DebugMessage('ImageCreateFromStringReplacement() failed: gd_version says "' . phpthumb_functions::gd_version() . '"', __FILE__, __LINE__);
             return false;
         }
     }
     if (phpthumb_functions::gd_is_bundled()) {
         $this->DebugMessage('ImageCreateFromStringReplacement() calling built-in ImageCreateFromString()', __FILE__, __LINE__);
         return @ImageCreateFromString($RawImageData);
     }
     if ($this->issafemode) {
         $this->DebugMessage('ImageCreateFromStringReplacement() failed: cannot create temp file in SAFE_MODE', __FILE__, __LINE__);
         return false;
     }
     switch (substr($RawImageData, 0, 3)) {
         case 'GIF':
             $ICFSreplacementFunctionName = 'ImageCreateFromGIF';
             break;
         case "ÿØÿ":
             $ICFSreplacementFunctionName = 'ImageCreateFromJPEG';
             break;
         case "‰" . 'PN':
             $ICFSreplacementFunctionName = 'ImageCreateFromPNG';
             break;
         default:
             $this->DebugMessage('ImageCreateFromStringReplacement() failed: unknown fileformat signature "' . phpthumb_functions::HexCharDisplay(substr($RawImageData, 0, 3)) . '"', __FILE__, __LINE__);
             return false;
             break;
     }
     if ($tempnam = $this->phpThumb_tempnam()) {
         if ($fp_tempnam = @fopen($tempnam, 'wb')) {
             fwrite($fp_tempnam, $RawImageData);
             fclose($fp_tempnam);
             if ($ICFSreplacementFunctionName == 'ImageCreateFromGIF' && !function_exists($ICFSreplacementFunctionName)) {
                 // Need to create from GIF file, but ImageCreateFromGIF does not exist
                 ob_start();
                 if (!@(include_once dirname(__FILE__) . '/phpthumb.gif.php')) {
                     $ErrorMessage = 'Failed to include required file "' . dirname(__FILE__) . '/phpthumb.gif.php" in ' . __FILE__ . ' on line ' . __LINE__;
                     $this->DebugMessage($ErrorMessage, __FILE__, __LINE__);
                 }
                 ob_end_clean();
                 // gif_loadFileToGDimageResource() cannot read from raw data, write to file first
                 if ($tempfilename = $this->phpThumb_tempnam()) {
                     if ($fp_tempfile = @fopen($tempfilename, 'wb')) {
                         fwrite($fp_tempfile, $RawImageData);
                         fclose($fp_tempfile);
                         $gdimg_source = gif_loadFileToGDimageResource($tempfilename);
                         $this->DebugMessage('gif_loadFileToGDimageResource(' . $tempfilename . ') completed', __FILE__, __LINE__);
                         $this->DebugMessage('deleting "' . $tempfilename . '"', __FILE__, __LINE__);
                         unlink($tempfilename);
                         return $gdimg_source;
                         //							break;
                     } else {
                         $ErrorMessage = 'Failed to open tempfile in ' . __FILE__ . ' on line ' . __LINE__;
                         $this->DebugMessage($ErrorMessage, __FILE__, __LINE__);
                     }
                 } else {
                     $ErrorMessage = 'Failed to open generate tempfile name in ' . __FILE__ . ' on line ' . __LINE__;
                     $this->DebugMessage($ErrorMessage, __FILE__, __LINE__);
                 }
             } elseif (function_exists($ICFSreplacementFunctionName) && ($gdimg_source = @$ICFSreplacementFunctionName($tempnam))) {
                 // great
                 $this->DebugMessage($ICFSreplacementFunctionName . '(' . $tempnam . ') succeeded', __FILE__, __LINE__);
                 $this->DebugMessage('deleting "' . $tempnam . '"', __FILE__, __LINE__);
                 unlink($tempnam);
                 return $gdimg_source;
             } else {
                 // GD functions not available, or failed to create image
                 $this->DebugMessage($ICFSreplacementFunctionName . '(' . $tempnam . ') ' . (function_exists($ICFSreplacementFunctionName) ? 'failed' : 'does not exist'), __FILE__, __LINE__);
                 if (isset($_GET['phpThumbDebug'])) {
                     $this->phpThumbDebug();
                 }
             }
         } else {
             $ErrorMessage = 'Failed to fopen(' . $tempnam . ', "wb") in ' . __FILE__ . ' on line ' . __LINE__ . "\n" . 'You may need to set $PHPTHUMB_CONFIG[temp_directory] in phpThumb.config.php';
             if ($this->issafemode) {
                 $ErrorMessage = 'ImageCreateFromStringReplacement() failed in ' . __FILE__ . ' on line ' . __LINE__ . ': cannot create temp file in SAFE_MODE';
             }
             $this->DebugMessage($ErrorMessage, __FILE__, __LINE__);
         }
         $this->DebugMessage('deleting "' . $tempnam . '"', __FILE__, __LINE__);
         @unlink($tempnam);
     } else {
         $ErrorMessage = 'Failed to generate phpThumb_tempnam() in ' . __FILE__ . ' on line ' . __LINE__ . "\n" . 'You may need to set $PHPTHUMB_CONFIG[temp_directory] in phpThumb.config.php';
         if ($this->issafemode) {
             $ErrorMessage = 'ImageCreateFromStringReplacement() failed in ' . __FILE__ . ' on line ' . __LINE__ . ': cannot create temp file in SAFE_MODE';
         }
     }
     if ($DieOnErrors && $ErrorMessage) {
         return $this->ErrorImage($ErrorMessage);
     }
     return false;
 }
示例#12
0
function calculate_image_luminance($image_url)
{
    if (!function_exists('ImageCreateFromString')) {
        return 1;
    }
    // Get original image dimensions
    $size = getimagesize($image_url);
    // Create image resource from source image
    $image = ImageCreateFromString(file_get_contents($image_url));
    // Allocate image resource
    $sample = ImageCreateTrueColor(1, 1);
    // Flood fill with a white background (to properly calculate luminance of PNGs with alpha)
    ImageFill($sample, 0, 0, ImageColorAllocate($sample, 255, 255, 255));
    // Downsample to 1x1 image
    ImageCopyResampled($sample, $image, 0, 0, 0, 0, 1, 1, $size[0], $size[1]);
    // Get the RGB value of the pixel
    $rgb = ImageColorAt($sample, 0, 0);
    $red = $rgb >> 16 & 0xff;
    $green = $rgb >> 8 & 0xff;
    $blue = $rgb & 0xff;
    // Calculate relative luminance value (https://en.wikipedia.org/wiki/Relative_luminance)
    return 0.2126 * $red + 0.7151999999999999 * $green + 0.0722 * $blue;
}
示例#13
0
 /**
  *  根据文件名和类型创建图片
  *
  * @param string $type 图片的类型,包括gif,jpg,png
  * @param string $img_name 图片文件名,包括路径名,例如 " ./mouse.jpg"
  * @return string 字符串类型的返回结果
  */
 private function createImage($type, $img_name)
 {
     if (!$type) {
         $type = $this->get_type($img_name);
     }
     switch ($type) {
         case 'gif':
             if (function_exists('imagecreatefromgif')) {
                 $tmp_img = @ImageCreateFromGIF($img_name);
             }
             break;
         case 'jpg':
             $tmp_img = ImageCreateFromJPEG($img_name);
             break;
         case 'jpeg':
             $tmp_img = ImageCreateFromJPEG($img_name);
             break;
         case 'png':
             $tmp_img = ImageCreateFromPNG($img_name);
             break;
         default:
             $tmp_img = ImageCreateFromString($img_name);
             break;
     }
     return $tmp_img;
 }
示例#14
0
 public function getImage($objUser)
 {
     return ImageCreateFromString(base64_decode($this->getFrom('imagedata', 'data')));
 }
 function thumbnail($url, $filename, $width = 120, $height = true)
 {
     // download and create gd image
     $image = ImageCreateFromString(file_get_contents($url));
     // calculate resized ratio
     // Note: if $height is set to TRUE then we automatically calculate the height based on the ratio
     $height = $height === true ? ImageSY($image) * $width / ImageSX($image) : $height;
     // create image
     $output = ImageCreateTrueColor($width, $height);
     ImageCopyResampled($output, $image, 0, 0, 0, 0, $width, $height, ImageSX($image), ImageSY($image));
     // save image
     ImageJPEG($output, $filename, 95);
     // return resized image
     return $output;
     // if you need to use it
 }
示例#16
0
 /**
  * 加载水印图
  */
 private function _loadMaskImg()
 {
     $mask_type = $this->_getImgType($this->mask_img);
     $this->_checkValid($mask_type);
     // file_get_contents函数要求php版本>4.3.0
     $src = '';
     if (function_exists("file_get_contents")) {
         $src = file_get_contents($this->mask_img);
     } else {
         $handle = fopen($this->mask_img, "r");
         while (!feof($handle)) {
             $src .= fgets($fd, 4096);
         }
         fclose($handle);
     }
     if (empty($this->mask_img)) {
         echo "水印图片为空";
         return false;
     }
     $this->h_mask = ImageCreateFromString($src);
     $this->mask_w = $this->getImgWidth($this->h_mask);
     $this->mask_h = $this->getImgHeight($this->h_mask);
 }
示例#17
0
 /**
  * image_dimensions
  * This returns the dimensions of the passed song of the passed type
  * returns an empty array if PHP-GD is not currently installed, returns
  * false on error
  */
 public static function image_dimensions($image_data)
 {
     if (!function_exists('ImageCreateFromString')) {
         return false;
     }
     $image = ImageCreateFromString($image_data);
     if (!$image) {
         return false;
     }
     $width = imagesx($image);
     $height = imagesy($image);
     if (!$width || !$height) {
         return false;
     }
     return array('width' => $width, 'height' => $height);
 }
 $outX = BORDER_LEFT + BORDER_RIGHT + IMAGES_ACROSS * THUMB_SIZE + (IMAGES_ACROSS - 1) * GAP_SIZE;
 $outY = BORDER_TOP + BORDER_BOTTOM + IMAGES_DOWN * THUMB_SIZE + (IMAGES_DOWN - 1) * GAP_SIZE;
 $imageOut = ImageCreateTrueColor($outX, $outY);
 // Paint the image white
 ImageFill($imageOut, 0, 0, ImageColorAllocate($imageOut, 255, 255, 255));
 // Draw a border in destination image
 ImageRectangle($imageOut, 0, 0, $outX - 1, $outY - 1, ImageColorAllocate($imageOut, 0, 0, 0));
 // Do the work
 $nextX = BORDER_LEFT;
 $nextY = BORDER_TOP;
 foreach ($imageKeys as $imageKey) {
     // Fetch the image
     print "  Fetch image '{$imageKey}'\n";
     $image = $s3->get_object(BOOK_BUCKET, $imageKey);
     // Convert it to GD format
     $imageBits = ImageCreateFromString($image->body);
     // Copy it to proper spot in the destination
     print "  Render image at {$nextX}, {$nextY}\n";
     ImageCopy($imageOut, $imageBits, $nextX, $nextY, 0, 0, ImageSx($imageBits), ImageSy($imageBits));
     // Draw a border around it
     ImageRectangle($imageOut, $nextX, $nextY, $nextX + ImageSx($imageBits), $nextY + ImageSy($imageBits), ImageColorAllocate($imageOut, 0, 0, 0));
     // Update position for next image
     $nextX += THUMB_SIZE + GAP_SIZE;
     if ($nextX + THUMB_SIZE > $outX) {
         $nextX = BORDER_LEFT;
         $nextY += THUMB_SIZE + GAP_SIZE;
     }
 }
 // Get the bits of the destination image
 $imageFileOut = tempnam('/tmp', 'aws') . '.png';
 ImagePNG($imageOut, $imageFileOut, 0);
示例#19
0
 /**
  * test_image
  * Runs some sanity checks on the putative image
  */
 public static function test_image($source)
 {
     if (strlen($source) < 10) {
         debug_event('Art', 'Invalid image passed', 1);
         return false;
     }
     // Check to make sure PHP:GD exists.  If so, we can sanity check
     // the image.
     if (function_exists('ImageCreateFromString')) {
         $image = ImageCreateFromString($source);
         if (!$image || imagesx($image) < 5 || imagesy($image) < 5) {
             debug_event('Art', 'Image failed PHP-GD test', 1);
             return false;
         }
     }
     return true;
 }
示例#20
0
function getPrintToImage($txt_X, $txt_Y, $serial, $num, $szFilePath, &$objFont, $serial, $nFontAlign = 0x12)
{
    # 이미지 파일이 존재하는지 체크한다.
    if (!file_exists($szFilePath))
    {
        return FALSE;
    }

    # 이미지 파일 정보를 구한다.(크기및 타입)
    $arrImgInfo = GetImageSize($szFilePath);

    # 해당 이미지 포멧이 지원되는지 체크한다. 
    switch ($arrImgInfo[2])
    {
    case 1:
        # GIF
        if (!(ImageTypes() & IMG_GIF))
        {
            return FALSE;
        }

        $szContentType = "image/gif";

        break;
    case 2:
        # JPG
        if (!(ImageTypes() & IMG_JPG))
        {
            return FALSE;
        }

        $szContentType = "image/jpeg";

        break;
    case 3:
        # PNG
        if (!(ImageTypes() & IMG_PNG))
        {
            return FALSE;
        }

        $szContentType = "image/png";

        break;
    default:
        return FALSE;
    }

    //header ("Content-type: ".$szContentType);
    # 이미지 파일을 읽어 이미지를 생성한다.
    $fp = fopen($szFilePath, "rb");
    $szContent = fread($fp, filesize($szFilePath));
    fclose($fp);

    $nImage = ImageCreateFromString($szContent);

	# 프린트할 글의 색상을 준비한다.
    $nBlue  = $objFont->color & 0xFF;
    $nGreen = $objFont->color >> 0x08 & 0xFF;
    $nRed   = $objFont->color >> 0x10 & 0xFF;

    $nFontColor  = ImageColorAllocate($nImage, $nRed, $nGreen, $nBlue);

    # 프린트할 글의 위치를 결정한다.
    $arrTTFBBox  = ImageTTFBBox($objFont->size, $objFont->angle, $objFont->font, $objFont->text);

    $nMax = max($arrTTFBBox[0], $arrTTFBBox[2], $arrTTFBBox[4], $arrTTFBBox[6]);
    $nMin = min($arrTTFBBox[0], $arrTTFBBox[2], $arrTTFBBox[4], $arrTTFBBox[6]);

    if ($nFontAlign & LEFT)
    {
        $nX = $arrTTFBBox[0] - $nMin;
    }
    else if ($nFontAlign & CENTER)
    {
        $nX = ($arrImgInfo[0] - ($nMax + $nMin)) / 2 + $arrTTFBBox[0];
    }
    else
    {
        $nX = $arrImgInfo[0] - $nMax + $arrTTFBBox[0];
    }

    $nMax = max($arrTTFBBox[1], $arrTTFBBox[3], $arrTTFBBox[5], $arrTTFBBox[7]);
    $nMin = min($arrTTFBBox[1], $arrTTFBBox[3], $arrTTFBBox[5], $arrTTFBBox[7]);

    if ($nFontAlign & TOP)
    {
        $nY = $arrTTFBBox[1] - $nMin;
    }
    else if ($nFontAlign & MIDDLE)
    {
        $nY = ($arrImgInfo[1] - ($nMax + $nMin)) / 2 + $arrTTFBBox[1];
    }
    else
    {
        $nY = $arrImgInfo[1] - $nMax + $arrTTFBBox[1];
    }
	$nX = $txt_X;
	$nY = $txt_Y;
    ImageTTFText($nImage, $objFont->size, $objFont->angle, $nX, $nY, $nFontColor, $objFont->font, $objFont->text);

	$mydir = "certi_images/".date("d"); 
	 if(@mkdir($mydir, 0777)) { 
		if(is_dir($mydir)) { 
			@chmod($mydir, 0777); 
		} 
	 }

    switch ($arrImgInfo[2])
    {
		case 1:
			# GIF
			ImageGIF($nImage,'simpletext.gif');
			break;
		case 2:
			# JPG
			ImageJPEG($nImage,'./files/'.$serial.'/medium/final_'.$serial.'_'.$num.'.jpg',100);
			break;
		case 3:
			# PNG
			ImagePNG($nImage,'baby_merge1.jpg');
			break;
		default:
			return FALSE;
    }
	imagedestroy($nImage);
	//echo "complete";
    return TRUE;
}
function gif_outputAsJpeg($gif, $lpszFileName, $bgColor = -1)
{
    // JPEG output that does not require cjpeg added by James Heinrich <*****@*****.**> - December 10, 2003
    if (strtoupper(substr(PHP_OS, 0, 3)) != 'WIN' && (file_exists('/usr/local/bin/cjpeg') || `which cjpeg`)) {
        if (gif_outputAsBmp($gif, $lpszFileName . '.bmp', $bgColor)) {
            exec('cjpeg ' . $lpszFileName . '.bmp >' . $lpszFileName . ' 2>/dev/null');
            @unLink($lpszFileName . '.bmp');
            if (@file_exists($lpszFileName)) {
                if (@fileSize($lpszFileName) > 0) {
                    return true;
                }
                @unLink($lpszFileName);
            }
        }
    } else {
        // either Windows, or cjpeg not found in path
        if ($img = @ImageCreateFromString($gif->getPng($bgColor))) {
            if (@ImageJPEG($img, $lpszFileName)) {
                return true;
            }
        }
    }
    return false;
}
示例#22
0
 public function getimagesize2($image_url)
 {
     $image_url = urldecode($image_url);
     $user_agent = ini_get('user_agent');
     ini_set('user_agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/2.0.0.9');
     $handle = @fopen($image_url, "rb");
     $contents = "";
     $count = 0;
     if ($handle) {
         do {
             $count += 1;
             $data = fread($handle, 8192);
             if (strlen($data) == 0) {
                 break;
             }
             $contents .= $data;
         } while (true);
     } else {
         return false;
     }
     fclose($handle);
     $im = @ImageCreateFromString($contents);
     if (!$im) {
         return false;
     }
     $gis[0] = ImageSX($im);
     $gis[1] = ImageSY($im);
     // array member 3 is used below to keep with current getimagesize standards
     $gis[3] = "width={$gis[0]} height={$gis[1]}";
     ImageDestroy($im);
     ini_set('user_agent', $user_agent);
     return $gis;
 }
 function getimagesize_remote($image_url)
 {
     //$image_url = urlencode($image_url);
     $handle = fopen($image_url, "rb");
     $contents = "";
     if ($handle) {
         do {
             $count += 1;
             $data = fread($handle, 8192);
             if (strlen($data) == 0) {
                 break;
             }
             $contents .= $data;
         } while (true);
         $im = ImageCreateFromString($contents);
         fclose($handle);
     }
     if (!$im) {
         $ch = curl_init($image_url);
         curl_setopt($ch, CURLOPT_HEADER, 0);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
         $raw = curl_exec($ch);
         curl_close($ch);
         $im = ImageCreateFromString($raw);
     }
     //if (!$im) {
     //	$raw = file_get_contents($image_url);
     //	$im = ImageCreateFromString($raw);
     //}
     if (!$im) {
         return false;
     }
     $gis[0] = ImageSX($im);
     $gis[1] = ImageSY($im);
     ImageDestroy($im);
     return $gis;
 }
示例#24
0
 /**
  * This method calculates the image and delivers it to the client.
  *
  * @param $folder
  * @param $file
  * @param $width
  * @param $height
  * @param $mode
  */
 public function resize($folder, $file, $width = -1, $height = -1, $mode = 'nocrop')
 {
     $jpeg_orientation_translation = array(1 => 0, 2 => 0, 3 => 180, 4 => 0, 5 => 0, 6 => -90, 7 => 0, 8 => 90);
     /**
      * @var JApplicationSite $app
      */
     $app = JFactory::getApplication();
     $params = $app->getParams();
     if (strcmp($mode, 'full') == 0) {
         $mode = 'nocrop';
         $width = COM_EVENTGALLERY_IMAGE_ORIGINAL_MAX_WIDTH;
         $height = COM_EVENTGALLERY_IMAGE_ORIGINAL_MAX_WIDTH;
     }
     if ($height > $width) {
         $width = $height;
     }
     $sizeSet = new EventgalleryHelpersSizeset();
     $saveAsSize = $sizeSet->getMatchingSize($width);
     $file = STR_REPLACE("\\.\\.", "", $file);
     $folder = STR_REPLACE("\\.\\.", "", $folder);
     $width = STR_REPLACE("\\.\\.", "", $width);
     $mode = STR_REPLACE("\\.\\.", "", $mode);
     $file = STR_REPLACE("/", "", $file);
     $folder = STR_REPLACE("/", "", $folder);
     $width = STR_REPLACE("/", "", $width);
     $mode = STR_REPLACE("/", "", $mode);
     $file = STR_REPLACE("\\", "", $file);
     $folder = STR_REPLACE("\\", "", $folder);
     $width = STR_REPLACE("\\", "", $width);
     $mode = STR_REPLACE("\\", "", $mode);
     $basedir = COM_EVENTGALLERY_IMAGE_FOLDER_PATH;
     $sourcedir = $basedir . $folder;
     $cachebasedir = COM_EVENTGALLERY_IMAGE_CACHE_PATH;
     $cachedir = $cachebasedir . $folder;
     $cachedir_thumbs = $cachebasedir . $folder;
     if (!is_dir(JPATH_CACHE)) {
         //mkdir($cachebasedir, 0777);
         mkdir(JPATH_CACHE);
     }
     if (!is_dir($cachebasedir)) {
         //mkdir($cachebasedir, 0777);
         mkdir($cachebasedir);
     }
     if (!is_dir($cachedir)) {
         //mkdir($cachedir, 0777);
         mkdir($cachedir);
     }
     if (!is_dir($cachedir_thumbs)) {
         //mkdir($cachedir_thumbs, 0777);
         mkdir($cachedir_thumbs);
     }
     $image_file = $sourcedir . DIRECTORY_SEPARATOR . $file;
     $image_thumb_file = $cachedir_thumbs . DIRECTORY_SEPARATOR . $mode . $saveAsSize . $file;
     //$last_modified = gmdate('D, d M Y H:i:s T', filemtime ($image_file));
     $last_modified = gmdate('D, d M Y H:i:s T', mktime(0, 0, 0, 1, 1, 2100));
     #echo "<br>".$image_thumb_file."<br>";
     $debug = false;
     if ($debug || !file_exists($image_thumb_file)) {
         $ext = pathinfo($image_file, PATHINFO_EXTENSION);
         $input_jpeg = null;
         $exif = null;
         if (strtolower($ext) == "gif") {
             if (!($im_original = imagecreatefromgif($image_file))) {
                 echo "Error opening {$image_file}!";
                 exit;
             }
         } else {
             if (strtolower($ext) == "jpg" || strtolower($ext) == "jpeg") {
                 // try to use PEL first. If things fail, use the php internal method to get the JPEG
                 try {
                     $input_jpeg = new PelJpeg($image_file);
                     /* Retrieve the original Exif data in $jpeg (if any). */
                     $exif = $input_jpeg->getExif();
                     /* The input image is already loaded, so we can reuse the bytes stored
                      * in $input_jpeg when creating the Image resource. */
                     if (!($im_original = ImageCreateFromString($input_jpeg->getBytes()))) {
                         echo "Error opening {$image_file}!";
                         exit;
                     }
                 } catch (Exception $e) {
                     if (!($im_original = imagecreatefromjpeg($image_file))) {
                         echo "Error opening {$image_file}!";
                         exit;
                     }
                 }
             } else {
                 if (strtolower($ext) == "png") {
                     if (!($im_original = imagecreatefrompng($image_file))) {
                         echo "Error opening {$image_file}!";
                         exit;
                     }
                 } else {
                     die("{$ext} not supported");
                 }
             }
         }
         if ($params->get('use_autorotate', 1) == 1 && $exif != NULL) {
             $tiff = $exif->getTiff();
             $ifd0 = $tiff->getIfd();
             $orientation = $ifd0->getEntry(PelTag::ORIENTATION);
             if ($orientation != null) {
                 $im_original = imagerotate($im_original, $jpeg_orientation_translation[$orientation->getValue()], 0);
                 $orientation->setValue(1);
             }
         }
         $orig_width = imagesx($im_original);
         $orig_height = imagesy($im_original);
         $orig_ratio = imagesx($im_original) / imagesy($im_original);
         $sizeCalc = new EventgalleryHelpersSizecalculator($orig_width, $orig_height, $width, strcmp('crop', $mode) == 0);
         $height = $sizeCalc->getHeight();
         $width = $sizeCalc->getWidth();
         //print_r($sizeCalc);
         // create canvas/border image
         //adjust height to not enlarge images
         if ($width > $orig_width) {
             $width = $orig_width;
         }
         if ($height > $orig_height) {
             $height = $orig_height;
         }
         if (strcmp('crop', $mode) != 0) {
             $canvasWidth = $width;
             $canvasHeight = ceil($width / $orig_ratio);
             if ($canvasHeight > $height) {
                 $canvasHeight = $height;
                 $canvasWidth = ceil($height * $orig_ratio);
             }
             $width = $canvasWidth;
             $height = $canvasHeight;
         } else {
             $height = $width;
         }
         $isOriginalSize = false;
         if ($height == $orig_height && $width == $orig_width) {
             $isOriginalSize = true;
         }
         /**
          * Do not recalculate the image if we don't need to resize it.
          */
         if ($isOriginalSize && $params->get('use_sharpening_for_originalsize', 1) == 0) {
             $im_output = $im_original;
         } else {
             $im_output = imagecreatetruecolor($width, $height);
             $resize_faktor = $orig_height / $height;
             $new_height = $height;
             $new_width = $orig_width / $resize_faktor;
             if ($new_width < $width) {
                 $resize_faktor = $orig_width / $width;
                 $new_width = $width;
                 $new_height = $orig_height / $resize_faktor;
             }
             imagecopyresampled($im_output, $im_original, $width / 2 - $new_width / 2, $height / 2 - $new_height / 2, 0, 0, $new_width, $new_height, $orig_width, $orig_height);
             $use_sharpening = $params->get('use_sharpening', 1);
             if ($use_sharpening == 1) {
                 // configure the sharpening
                 $stringSharpenMatrix = $params->get('image_sharpenMatrix', '[[-1,-1,-1],[-1,16,-1],[-1,-1,-1]]');
                 $sharpenMatrix = json_decode($stringSharpenMatrix);
                 if (null == $sharpenMatrix || count($sharpenMatrix) != 3) {
                     $sharpenMatrix = array(array(-1, -1, -1), array(-1, 16, -1), array(-1, -1, -1));
                 }
                 $divisor = array_sum(array_map('array_sum', $sharpenMatrix));
                 $offset = 0;
                 if (function_exists('imageconvolution')) {
                     if (version_compare(phpversion(), '5.5.9', '=')) {
                         $this->imageconvolution($im_output, $sharpenMatrix, $divisor, $offset);
                     } else {
                         imageconvolution($im_output, $sharpenMatrix, $divisor, $offset);
                     }
                 }
             }
         }
         /**
          * @var EventgalleryLibraryManagerFolder $folderMgr
          * @var EventgalleryLibraryFolder $folder
          */
         $folderMgr = EventgalleryLibraryManagerFolder::getInstance();
         $folder = $folderMgr->getFolder($folder);
         $watermark = $folder->getWatermark();
         // load default watermark
         if (null == $watermark || !$watermark->isPublished()) {
             /**
              * @var EventgalleryLibraryManagerWatermark $watermarkMgr
              * @var EventgalleryLibraryWatermark $watermark
              */
             $watermarkMgr = EventgalleryLibraryManagerWatermark::getInstance();
             $watermark = $watermarkMgr->getDefaultWatermark();
         }
         if (null != $watermark && $watermark->isPublished()) {
             $watermark->addWatermark($im_output);
         }
         $image_quality = $params->get('image_quality', 85);
         if ($input_jpeg != null) {
             Pel::setJPEGQuality($image_quality);
             /* We want the raw JPEG data from $scaled. Luckily, one can create a
              * PelJpeg object from an image resource directly: */
             $output_jpeg = new PelJpeg($im_output);
             /* If no Exif data was present, then $exif is null. */
             if ($exif != null) {
                 $output_jpeg->setExif($exif);
             }
             /* We can now save the scaled image. */
             $writeSuccess = true;
             $output_jpeg->saveFile($image_thumb_file);
         } else {
             $writeSuccess = imagejpeg($im_output, $image_thumb_file, $image_quality);
             if (!$writeSuccess) {
                 die("Unable to write to file {$image_thumb_file}");
             }
         }
         if (!$writeSuccess) {
             die("Unable to write to file {$image_thumb_file}");
         }
         $time = time() + 315360000;
         touch($image_thumb_file, $time);
         // add the ICC profile
         try {
             $o = new JPEG_ICC();
             $o->LoadFromJPEG($image_file);
             $o->SaveToJPEG($image_thumb_file);
         } catch (Exception $e) {
         }
     }
     $mime = ($mime = getimagesize($image_thumb_file)) ? $mime['mime'] : $mime;
     $size = filesize($image_thumb_file);
     $fp = fopen($image_thumb_file, "rb");
     if (!($mime && $size && $fp)) {
         // Error.
         return;
     }
     if (!$debug) {
         header("Content-Type: " . $mime);
         header("Content-Length: " . $size);
         header("Last-Modified: {$last_modified}");
     }
     fpassthru($fp);
     die;
     //$app->close();
 }
示例#25
0
 function createImage($type, $img_name)
 {
     switch ($type) {
         case 1:
             if (function_exists('imagecreatefromgif')) {
                 $tmp_img = @ImageCreateFromGIF($img_name);
             } else {
                 return false;
             }
             break;
         case 2:
             $tmp_img = ImageCreateFromJPEG($img_name);
             break;
         case 3:
             $tmp_img = ImageCreateFromPNG($img_name);
             break;
         case 6:
             $tmp_img = imagecreatefrombmp($img_name);
             break;
         default:
             $tmp_img = ImageCreateFromString($img_name);
             break;
     }
     return $tmp_img;
 }
示例#26
0
文件: resize.php 项目: lsolesen/pel
    println('Optional arguments:');
    println('  -d    turn debug output on.');
    println('Mandatory arguments:');
    println('  input   the input filename, a JPEG image.');
    println('  output  filename for saving the changed image.');
    println('  scale   scale factor, say 0.5 to resize to half the ' . 'original size.');
    exit(1);
}
/* The input file is now loaded into a PelJpeg object. */
println('Reading file "%s".', $input);
$input_jpeg = new PelJpeg($input);
/*
 * The input image is already loaded, so we can reuse the bytes stored
 * in $input_jpeg when creating the Image resource.
 */
$original = ImageCreateFromString($input_jpeg->getBytes());
$original_w = ImagesX($original);
$original_h = ImagesY($original);
$scaled_w = $original_w * $scale;
$scaled_h = $original_h * $scale;
/* Now create the scaled image. */
$scaled = ImageCreateTrueColor($scaled_w, $scaled_h);
ImageCopyResampled($scaled, $original, 0, 0, 0, 0, $scaled_w, $scaled_h, $original_w, $original_h);
/*
 * We want the raw JPEG data from $scaled. Luckily, one can create a
 * PelJpeg object from an image resource directly:
 */
$output_jpeg = new PelJpeg($scaled);
/* Retrieve the original Exif data in $jpeg (if any). */
$exif = $input_jpeg->getExif();
/* If no Exif data was present, then $exif is null. */
示例#27
0
 /**
  * test_image
  * Runs some sanity checks on the putative image
  * @param string $source
  * @return boolean
  */
 public static function test_image($source)
 {
     if (strlen($source) < 10) {
         debug_event('Art', 'Invalid image passed', 1);
         return false;
     }
     // Check image size doesn't exceed the limit
     if (strlen($source) > AmpConfig::get('max_upload_size')) {
         debug_event('Art', 'Image size (' . strlen($source) . ') exceed the limit (' . AmpConfig::get('max_upload_size') . ').', 1);
         return false;
     }
     $test = true;
     // Check to make sure PHP:GD exists.  If so, we can sanity check
     // the image.
     if (function_exists('ImageCreateFromString')) {
         $image = @ImageCreateFromString($source);
         if (!$image || imagesx($image) < 5 || imagesy($image) < 5) {
             debug_event('Art', 'Image failed PHP-GD test', 1);
             $test = false;
         }
         @imagedestroy($image);
     }
     return $test;
 }
示例#28
0
 function submit()
 {
     $this->load->library('form_validation');
     $this->form_validation->set_rules('title', 'titre', 'required|max_length[255]');
     $this->form_validation->set_rules('type', 'type du contenu', 'required|is_natural');
     $this->form_validation->set_rules('categorie', 'champ de la catégorie', 'required|is_natural');
     $this->form_validation->set_rules('idCreation', 'id', 'required|is_natural');
     $type = $this->input->post('type');
     if ($type == 3) {
         // article => image obligatoire
         $this->form_validation->set_rules('image', 'champ de l\'image', 'required');
     }
     // $this->form_validation->set_rules('description', 'champ de la description', 'required');
     $formValid = $this->form_validation->run();
     $errors = $this->form_validation->error_array();
     if ($formValid) {
         $errors['redirectTo'] = site_url('monCompte/contributions');
         if ($type == 2) {
             $categorie = null;
             $parent = $this->input->post('categorie');
             if ($parent == 0) {
                 $parent = null;
             }
         } else {
             $parent = null;
             $categorie = $this->input->post('categorie');
         }
         $data['user'] = $this->session->userdata('id');
         $data['title'] = $this->input->post('title');
         $data['redirect'] = $this->input->post('redirect');
         $data['type'] = $type;
         $data['parent'] = $parent;
         $data['categorie'] = $categorie;
         $data['site'] = $this->contents->getIdSite();
         $data['description'] = $this->input->post('description');
         $data['content'] = $this->input->post('contentTxt');
         $data['editDate'] = date('Y-m-d H:i:s');
         $urlImage = $this->input->post('image');
         // si on fourni une url d'image
         if (trim($urlImage) != '' && in_array($type, array(1, 3))) {
             $image = @ImageCreateFromString(@file_get_contents($urlImage));
             if (is_resource($image) === true) {
                 $width = imagesx($image);
                 $height = imagesy($image);
                 // on cherche le bon format en fonction du type de contenu
                 if ($type == 1) {
                     $goodSize = $this->size_slider;
                 } else {
                     if ($type == 3) {
                         $goodSize = $this->size_article;
                     }
                 }
                 // la taille d'image fourni n'est pas aux proportions correctes, on la recadre
                 if ($width != $goodSize[0] || $height != $goodSize[1]) {
                     $dest = 'public/images_upload/crop/' . str_replace('.', '', microtime(true)) . '.png';
                     imagepng($image, $dest, 0);
                     $config['quality'] = '100%';
                     $config['width'] = intval($this->input->post('w'));
                     $config['height'] = intval($this->input->post('h'));
                     $config['x_axis'] = intval($this->input->post('x'));
                     $config['y_axis'] = intval($this->input->post('y'));
                     $config['source_image'] = $dest;
                     $config['maintain_ratio'] = false;
                     // on recadre
                     $this->load->library('image_lib', $config);
                     $this->image_lib->crop();
                     // et on redimensionne proprement
                     $config['width'] = $goodSize[0];
                     $config['height'] = $goodSize[1];
                     $this->image_lib->initialize($config);
                     $this->image_lib->resize();
                     $data['image'] = $dest;
                 } else {
                     //sinon, on garde la meme
                     $data['image'] = str_replace(base_url(), '', $urlImage);
                 }
             } else {
                 // l'url n'est pas une image, on la vide
                 $data['image'] = '';
             }
         }
         $id = $this->input->post('id');
         $idCreation = $this->input->post('idCreation');
         $editFromVersion = $this->input->post('editFromVersion');
         if ($idCreation == 0) {
             $data['version'] = 1;
             if ($type == 2) {
                 $data['order'] = $this->contents->getLastOrder($parent);
             } else {
                 $data['order'] = 0;
             }
             $data['editFromVersion'] = 1;
             $data['idCreation'] = 0;
             $data['date'] = date('Y-m-d H:i:s');
         } else {
             // on recupere l'ancien contenu pour calculer combien de lignes/caracteres on a modifié
             $resContent = $this->db->select('content')->where('id', $id)->get('contents')->row_array();
             $oldContent = $resContent['content'];
             $data['linesModified'] = nbLines($data['content']) - nbLines($oldContent);
             $data['sizeModified'] = mb_strlen($data['content']) - mb_strlen($oldContent);
             $data['version'] = $this->contents->getLastVersion($idCreation) + 1;
             $data['editFromVersion'] = $this->input->post('editFromVersion');
             $data['idCreation'] = $idCreation;
             $infos = $this->contents->getInfosForNewVersion($idCreation);
             $data['inSlider'] = $infos['inSlider'];
             $data['order'] = $infos['order'];
             $data['date'] = $infos['date'];
             $data['nbComment'] = $infos['nbComment'];
         }
         $lastId = $this->contents->create($data);
         // $this->contents->setCurrent($lastId);
     }
     $this->users->gils(150);
     echo json_encode($errors);
 }
示例#29
0
function thumbnailImage($imageBitsIn, $contentType)
{
    // Create a GD image
    $imageIn = ImageCreateFromString($imageBitsIn);
    // Measure the image
    $inX = ImageSx($imageIn);
    $inY = ImageSy($imageIn);
    // Decide how to scale it
    if ($inX > $inY) {
        $outX = THUMB_SIZE;
        $outY = (int) (THUMB_SIZE * ((double) $inY / $inX));
    } else {
        $outX = (int) (THUMB_SIZE * ((double) $inX / $inY));
        $outY = THUMB_SIZE;
    }
    // Create thumbnail image and fill it with white
    $imageOut = ImageCreateTrueColor($outX, $outY);
    ImageFill($imageOut, 0, 0, ImageColorAllocate($imageOut, 255, 255, 255));
    // Copy / resize the original image into the thumbnail image
    ImageCopyResized($imageOut, $imageIn, 0, 0, 0, 0, $outX, $outY, $inX, $inY);
    // Write the image to a temporary file in the requested format
    $fileOut = tempnam("/tmp", "aws") . ".aws";
    switch ($contentType) {
        case "image/jpg":
            $ret = ImageJPEG($imageOut, $fileOut, 100);
            break;
        case "image/png":
            $ret = ImagePNG($imageOut, $fileOut, 0);
            break;
        case "image/gif":
            $ret = ImageGIF($imageOut, $fileOut);
            break;
        default:
            unlink($fileOut);
            return false;
    }
    // Verify success
    if (!$ret) {
        unlink($fileOut);
        return false;
    }
    // Read the image back in
    $imageBitsOut = file_get_contents($fileOut);
    // Clean up
    unlink($fileOut);
    return $imageBitsOut;
}
 function ImageCreateFromStringReplacement(&$RawImageData, $DieOnErrors = false)
 {
     // there are serious bugs in the non-bundled versions of GD which may cause
     // PHP to segfault when calling ImageCreateFromString() - avoid if at all possible
     // when not using a bundled version of GD2
     $gd_info = phpthumb_functions::gd_info();
     if (strpos($gd_info['GD Version'], 'bundled') !== false) {
         return @ImageCreateFromString($RawImageData);
     }
     switch (substr($RawImageData, 0, 3)) {
         case 'GIF':
             $ICFSreplacementFunctionName = 'ImageCreateFromGIF';
             break;
         case "ÿØÿ":
             $ICFSreplacementFunctionName = 'ImageCreateFromJPEG';
             break;
         case "‰" . 'PN':
             $ICFSreplacementFunctionName = 'ImageCreateFromPNG';
             break;
         default:
             $this->ErrorImage('Unknown image type identified by "' . substr($this->rawImageData, 0, 3) . '" (' . phpthumb_functions::HexCharDisplay(substr($this->rawImageData, 0, 3)) . ') in ImageCreateFromStringReplacement()');
             break;
     }
     if ($tempnam = tempnam($this->config_temp_directory, 'pThumb')) {
         if ($fp_tempnam = @fopen($tempnam, 'wb')) {
             fwrite($fp_tempnam, $RawImageData);
             fclose($fp_tempnam);
             if ($ICFSreplacementFunctionName == 'ImageCreateFromGIF' && !function_exists($ICFSreplacementFunctionName)) {
                 // Need to create from GIF file, but ImageCreateFromGIF does not exist
                 if (@(include_once 'phpthumb.gif.php')) {
                     // gif_loadFileToGDimageResource() cannot read from raw data, write to file first
                     if ($tempfilename = tempnam($this->config_temp_directory, 'pThumb')) {
                         if ($fp_tempfile = @fopen($tempfilename, 'wb')) {
                             fwrite($fp_tempfile, $RawImageData);
                             fclose($fp_tempfile);
                             $gdimg_source = gif_loadFileToGDimageResource($tempfilename);
                             unlink($tempfilename);
                             return $gdimg_source;
                             break;
                         } else {
                             $ErrorMessage = 'Failed to open tempfile in ' . __FILE__ . ' on line ' . __LINE__;
                         }
                     } else {
                         $ErrorMessage = 'Failed to open generate tempfile name in ' . __FILE__ . ' on line ' . __LINE__;
                     }
                 } else {
                     $ErrorMessage = 'Failed to include required file "phpthumb.gif.php" in ' . __FILE__ . ' on line ' . __LINE__;
                 }
             } elseif (function_exists($ICFSreplacementFunctionName) && ($gdimg_source = $ICFSreplacementFunctionName($tempnam))) {
                 // great
                 unlink($tempnam);
                 return $gdimg_source;
             } else {
                 // GD functions not available
                 // base64-encoded error image in GIF format
                 $ERROR_NOGD = 'R0lGODlhIAAgALMAAAAAABQUFCQkJDY2NkZGRldXV2ZmZnJycoaGhpSUlKWlpbe3t8XFxdXV1eTk5P7+/iwAAAAAIAAgAAAE/vDJSau9WILtTAACUinDNijZtAHfCojS4W5H+qxD8xibIDE9h0OwWaRWDIljJSkUJYsN4bihMB8th3IToAKs1VtYM75cyV8sZ8vygtOE5yMKmGbO4jRdICQCjHdlZzwzNW4qZSQmKDaNjhUMBX4BBAlmMywFSRWEmAI6b5gAlhNxokGhooAIK5o/pi9vEw4Lfj4OLTAUpj6IabMtCwlSFw0DCKBoFqwAB04AjI54PyZ+yY3TD0ss2YcVmN/gvpcu4TOyFivWqYJlbAHPpOntvxNAACcmGHjZzAZqzSzcq5fNjxFmAFw9iFRunD1epU6tsIPmFCAJnWYE0FURk7wJDA0MTKpEzoWAAskiAAA7';
                 header('Content-type: image/gif');
                 echo base64_decode($ERROR_NOGD);
                 exit;
             }
         } else {
             $ErrorMessage = 'Failed to fopen(' . $tempnam . ', "wb") in ' . __FILE__ . ' on line ' . __LINE__ . "\n" . 'You may need to set $PHPTHUMB_CONFIG[temp_directory] in phpthumb.config.php';
         }
         unlink($tempnam);
     } else {
         $ErrorMessage = 'Failed to generate tempnam() in ' . __FILE__ . ' on line ' . __LINE__ . "\n" . 'You may need to set $PHPTHUMB_CONFIG[temp_directory] in phpthumb.config.php';
     }
     if ($DieOnErrors && !empty($ErrorMessage)) {
         die($ErrorMessage);
     }
     return false;
 }