为PHP生成的图像创建文件名?

时间:2014-01-16 08:59:08

标签: php wordpress

我写了几个文件,形成一个自动发布到WordPress的插件。我试图上传和附加PHP生成的图像作为帖子的特色图像。除了下面的文件外,一切正常。

它通过包含文件生成我想要输入到插件其余部分的图像。

就像我说它可以工作但只是在我直接访问URL时生成图像但是当我将其包含在我的上传/附加脚本中时,它会尝试使用与长URL相同的文件名保存文件。 IE,此文件被称为“imagegen.php”,因此它尝试使用文件名“imagegen?title = 5454”上传它。因此它实际上并不会上传和附加除空文件之外的任何内容。

我需要它是一个名字如下的文件:image001.jpg

该文件肯定有效,因为我甚至可以将生成的图像作为JPG保存到桌面,我只是无法上传并按原样附加它。

        <?php
    function sanitize($s) {
        return str_replace('&amp;#',"&#",str_replace('"',"&#34;",str_replace ("'","&#39;",str_replace ("<","&#60;",str_replace (">","&#62;",str_replace ("%","",$s))))));
    }

    function bst($a) {
        $bst0=strtotime('Sunday, 25 March 2012 2:00am');
        $bst1=strtotime('Sunday, 28 October 2012 2:00am');
        return ($a+((($a>$bst0)&&($a<$bst1))?3600:0));
    }

    function duration($sec) {
        $hours = intval(intval($sec) / 3600);
        $minutes = intval(($sec / 60) % 60);
        return (($hours==0)?'':(($hours==2)?($hours.' hr '):($hours.' hrs '))).(($minutes==0)?'':(($minutes==1)?($minutes.' min'):($minutes.' mins')));
    }

    $live=1;
    if ($live==0) {
    define('__DB_SERVER','localhost');
    define('_user','wrdp1');
    define('_pass','password');
    define('_db','wrdp1');
    }
    else {
    define('__DB_SERVER','localhost');
    define('_user','wrdp1');
    define('_pass','password');
    define('_db','wrdp1');
    }
    mysql_connect (__DB_SERVER,_user,_pass);
    mysql_select_db (_db);

        $stitle = $_GET['title'];

        $dt1=date('Y-m-d H:i:s',bst(time()+(10*60)));
        $dt2=date('Y-m-d H:i:s',bst(time()-(7*24*60*60)));

    $result = mysql_query("SELECT * FROM streams
    WHERE channelsequence='$stitle'");

    while($row = mysql_fetch_array($result))
      {
      $awesomeimage = $row['sequence_name'] ;

      $auto=$row['auto'];
            $balls=$row['description'];
            $title=$row['sequence_name'];
            $channel=$row['channel_name'];
            $info=$row['description'];
            $stream=$row['stream'];
            $seqid=$row['channel_sequenceid'];

            $views=$row['views'];
            $dt=date('l jS \of F Y h:i A',strtotime($row['starts_at']));
      }
    ?><?php

    //* $file1 = "http://example.com/style/images/shows/exampleimage.jpg"; *//

    $file1 = "http://example.com/file.php?t=100000000000";


    // Constants
    $copyrightSymbol = 169;  // ASCII value for the Copyright Symbol
    $padding = 40;      // offset for positioning and appearance
    $basePath = getcwd() . '/';
    $clickheretowatch = "Click to watch";
    $DTTEST = "Sunday 30th of December 2012 09:40 AM";
    $awesomeimage1 = str_replace("'", "39", "$awesomeimage" );
    $awesomeimage11 = str_replace(" ", "", "$awesomeimage1" );
    $awesomeimage111 = str_replace("&", "", "$awesomeimage11" );
    $awesomeimage1111 = str_replace("#", "", "$awesomeimage111" );
    $awesomeimage11111 = str_replace(";", "", "$awesomeimage1111" );
    $awesomeimage111111 = str_replace("!", "", "$awesomeimage11111" );
    $awesomeimage1111111 = str_replace("?", "", "$awesomeimage111111" );
    $awesomeimage11111111 = str_replace("&#39;", "", "$awesomeimage1111111" );
    $preawesomeimage2 = "http://example.co.uk/style/images/phpThumb.php?src=prog/" . "$awesomeimage11111111" . ".jpg";
    $missingimage = "http://ipsumimage.appspot.com/300x250?l=EXCLUSIVE";
    $file2 = "$preawesomeimage2";

    $missingtitle = str_replace(" ", "+", "$title");

    if ( sha1_file ( $file1 ) === sha1_file ( $file2 ) ) {
    $color = substr(md5(rand()), 0, 3);
      $awesomeimage2 = "http://ipsumimage.appspot.com/300x250,$color?l=Example.com|EXCLUSIVE||$missingtitle&s=25&t=jpg";
      // They're identical
    } else {
    $awesomeimage2 = "http://example.com/images/shows/" . "$awesomeimage11111" . ".jpg";
      // They're not
    }



    $autogenbg = "http://ipsumimage.appspot.com/300x250,000?l=$clickheretowatch|$title||||||||$dt&f=fff&s=15&t=jpg";

    $autogenbg1 = str_replace("&#39;", "'", "$autogenbg" );
    $autogenbg11 = str_replace("&;", "And", "$autogenbg1" );
    $autogenbg2 = str_replace(" ", "%20", "$autogenbg11");

    // User Settings
    $fontPath = 'fonts/';  // IMPORTANT! Set this to the path to the fonts on your server or a local child/sub directory.
    $fontArial = $fontPath . 'arial.ttf';
    $fontTahoma = $fontPath . 'Tahoma.ttf';
    $wm_font = $fontTahoma;   // See the note above!
    $message = chr($copyrightSymbol) . " Rainbo Design";  // Message text for watermark

    $wm_image = $awesomeimage2;  



    // Defaults
    $wm_type = 'msg';  // Default watermarking method/type
    $fontColor = 'white';   // Default font color White
    $fontSize = 11;         // Default font size (in pixels for GD v1.x, in point size for GD v2.x+.  Use gdinfo.php to check your server.)
    $wm_bg = f;        // Fill background for message text watermarks flag (true/false)
    $position = 'bottom';   // Default watermark vertical position
    $wm_factor = (1);  // Default watermark image overlay reduction factor (multiplier) - set to 1 to retain original size
    $wm_opacity = 100; // Default watermark image overlay opacity
    $wm_rotate = 0;        // Default watermark image overlay rotation (in degrees)
    $dest_x = 25;      // Default watermark x/horizontal position (in pixels)

    // Handle Query String option parameters
    // type, color, size, pos, wmsize, op, rot, x, m
     if (isset($_GET['type'])) { $wm_type = $_GET['type']; }
     if (isset($_GET['color'])) { $fontColor = $_GET['color']; }
     if (isset($_GET['size'])) { $fontSize = $_GET['size']; }
     if (isset($_GET['bg'])) { $wm_bg = $_GET['bg']; }
     if (isset($_GET['pos'])) { $position = $_GET['pos']; }
     if (isset($_GET['wmsize'])) { $wm_factor = 1/($_GET['wmsize']); }
     if (isset($_GET['op'])) { $wm_opacity = $_GET['op']; }
     if (isset($_GET['rot'])) { $wm_rotate = $_GET['rot']; }
     if (isset($_GET['x'])) { $dest_x = $_GET['x']; }
     if (isset($_GET['m'])) { $message = $_GET['m']; }

    // Get info about image to be watermarked

    $old_image = "$autogenbg2";
    $size = getimagesize($old_image);
    $imagetype = $size[2];

    // Create GD Image Resource from original image
      switch($imagetype) {
      case(1):
        $image = imagecreatefromgif($old_image);
        break;

      case(2):
        $image = imagecreatefromjpeg($old_image);
        break;

      case(3):
        $image = imagecreatefrompng($old_image);
        break;

      case(6):
        $image = imagecreatefrombmp($old_image);
        break;

      } // end switch($imagetype)

      if ($wm_type == 'img') {

    $watermark = imagecreatefromjpeg($wm_image);  // Create a GD image resource from overlay image
    $wm_width = imagesx($watermark);      // get the original width
    $wm_height = imagesy($watermark);     // get the original height
    $watermark_rWidth = 250;   // calculate new, reduced width
    $watermark_rHeight = 150;  // calculate new, reduced height
    $watermark_r = @imagecreatetruecolor($watermark_rWidth, $watermark_rHeight);
    // Reduce the size of the overlay image GD resource
    // imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )

    imagecopyresampled($watermark_r, $watermark, 0, 0, 0, 0, $watermark_rWidth, $watermark_rHeight, $wm_width, $wm_height);
     imagedestroy($watermark);  // original watermark image no longer needed

      } // endif $wm_image

     if ($wm_type == 'msg') {

    // Calculate size of overlay image for text
    // array imagettfbbox ( float $size , float $angle , string $fontfile , string $text )
    $wm_bBox = imagettfbbox($fontSize, 0, $wm_font, $message);
    $lowerLeftX = $wm_bBox[0];
    $lowerLeftY = $wm_bBox[1];
    $lowerRightX = $wm_bBox[2];
    $lowerRightY = $wm_bBox[3];
    $upperRightX = $wm_bBox[4];
    $upperRightY = $wm_bBox[5];
    $upperLeftX = $wm_bBox[6];
    $upperLeftY = $wm_bBox[7];
    $watermark_rWidth = ($upperRightX - $upperLeftX) + $padding;
    $watermark_rHeight = ($lowerLeftY - $upperLeftY) + $padding;

    // Create the overlay image
    $watermark_r = imagecreatetruecolor($watermark_rWidth, $watermark_rHeight);

     $txtColorBk = hex2int(validHexColor('000000','ffffff'));  // black
     $txtColorR = hex2int(validHexColor('800000','ffffff'));   // red
     $txtColorG = hex2int(validHexColor('008000','ffffff'));   // green
     $txtColorBl = hex2int(validHexColor('000080','ffffff'));  // blue
     $txtColorYl = hex2int(validHexColor('ffff00','ffffff'));  // yellow
     $txtColorWht = hex2int(validHexColor('ffffff','ffffff')); // white

       switch($fontColor) {
       case('black'):
     $txtColor = imageColorAllocate($watermark_r, $txtColorBk['r'], $txtColorBk['g'], $txtColorBk['b']);
      break;
       case('red'):
     $txtColor = imageColorAllocate($watermark_r, $txtColorR['r'], $txtColorR['g'], $txtColorR['b']);
      break;
       case('green'):
     $txtColor = imageColorAllocate($watermark_r, $txtColorG['r'], $txtColorG['g'], $txtColorG['b']);
      break;
       case('blue'):
     $txtColor = imageColorAllocate($watermark_r, $txtColorBl['r'], $txtColorBl['g'], $txtColorBl['b']);
      break;
       case('yellow'):
     $txtColor = imageColorAllocate($watermark_r, $txtColorYl['r'], $txtColorYl['g'], $txtColorYl['b']);
      break;
       case('white'):
     $txtColor = imageColorAllocate($watermark_r, $txtColorWht['r'], $txtColorWht['g'], $txtColorWht['b']);
      break;
     } // end switch($fontColor)

     if (!isset($txtColor)) {
        $userColor = hex2int(validHexColor($fontColor, 'ffffff'));
        $txtColor = imageColorAllocate($watermark_r, $userColor['r'], $userColor['g'], $userColor['b']);
     } // endif (!isset($txtColor)

    // Set an appropriate background color
      if (($fontColor == 'white') || ($fontColor == 'ffffff')) {
        $watermark_rBGColor = imageColorAllocate($watermark_r, $txtColorBk['r'], $txtColorBk['g'], $txtColorBk['b']);
        } else {
        $watermark_rBGColor = imageColorAllocate($watermark_r, $txtColorWht['r'], $txtColorWht['g'], $txtColorWht['b']);
      }

    imagefilledrectangle($watermark_r, 0, 0, $watermark_rWidth, $watermark_rHeight, $watermark_rBGColor);


    // Make the background transparent?
     if (!$wm_bg) {
     $bg = imagecolortransparent($watermark_r, $watermark_rBGColor);
     }

    // array imageTTFText  ( resource image, int size, int angle, int x, int y, int color, string fontfile, string text)
     imageFTText($watermark_r, $fontSize, 0, 1, $watermark_rHeight-$padding, $txtColor, $wm_font, $message);

     } // endif $wm_type == 'msg'

    // Handle rotation
      if ($wm_rotate != 0) {
      if (phpversion() >= 5.1) { 
        $bg = imagecolortransparent($watermark_r);
        $watermark_r = imagerotate($watermark_r, $wm_rotate, $bg, 1);
      } else {
        $watermark_r = imagerotate($watermark_r, $wm_rotate, 0);
     } // endif phpversion()

        $watermark_rWidth = imagesx($watermark_r);
        $watermark_rHeight = imagesy($watermark_r);
      } // endif $wm_rotate !=0


    // Calculate overlay image position
      if ($position == 'bottom') {
      $dest_y = $size[1] - ($watermark_rHeight + $padding);
       } else {
      $dest_y = 4;
      } // endif $position

    // Overlay the logo watermark image on the original image
    // int imagecopymerge ( resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct );
     imagecopymerge($image, $watermark_r, $dest_x, $dest_y, 0, 0, $watermark_rWidth, $watermark_rHeight, $wm_opacity);
     imagedestroy($watermark_r);

      switch(

$imagetype) {
  case(1):
    header('Content-type: image/gif');
    imagegif($image);  
    break;

  case(2):
    header('Content-type: image/jpeg');
    imagejpeg($image);  
    break;

  case(3):
    header('Content-type: image/png');
    imagepng($image);  
    break;

  case(6):
    header('Content-type: image/bmp');
    imagewbmp($image);  
    break;

  } // end switch($imagetype)

imagedestroy($image);

exit;

/**
 * @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
                    );
}

/**
 * @param $input string     6-digit hexadecimal string to be validated
 * @param $default string   default color to be returned if $input isn't valid
 * @return string           the validated 6-digit hexadecimal color
 * @desc returns $input if it is a valid hexadecimal color, 
 *       otherwise returns $default (which defaults to black)
 */
function validHexColor($input = '000000', $default = '000000') {
    // A valid Hexadecimal color is exactly 6 characters long
    // and eigher a digit or letter from a to f
    return (eregi('^[0-9a-f]{6}$', $input)) ? $input : $default ;
}

// function imageRotate courtesy beau@dragonflydevelopment.com on www.php.net
function rotateImage($img, $rotation) {
  $width = imagesx($img);
  $height = imagesy($img);
  switch($rotation) {
    case 90: $newimg= @imagecreatetruecolor($height , $width );break;
    case 180: $newimg= @imagecreatetruecolor($width , $height );break;
    case 270: $newimg= @imagecreatetruecolor($height , $width );break;
    case 0: return $img;break;
    case 360: return $img;break;
  }
  if($newimg) {
    for($i = 0;$i < $width ; $i++) {
      for($j = 0;$j < $height ; $j++) {
        $reference = imagecolorat($img,$i,$j);
        switch($rotation) {
          case 90: if(!@imagesetpixel($newimg, ($height - 1) - $j, $i, $reference )){return false;}break;
          case 180: if(!@imagesetpixel($newimg, $width - $i, ($height - 1) - $j, $reference )){return false;}break;
          case 270: if(!@imagesetpixel($newimg, $j, $width - $i, $reference )){return false;}break;
        }
      }
    } return $newimg;
  }
  return false;
} // end rotateImage()

// outputting to the browser
// header() needed for browser
header('Content-Type: image/jpeg');
imagejpeg($newimg);

// saving to a file
// you do not need a header() function to save to a file
imagejpeg($newimg, "../images/image001.jpg");

// outputting to the browser including quality parameter.
// skipping parameter2 to output to browser
header('Content-Type: image/jpeg');
imagejpeg($newimg, 90);

// saving to a file including quality parameter.
// all parameters used for saving to a file with quality adjustment
imagejpeg($newimg, "../images/image001.jpg", 90);

?>

1 个答案:

答案 0 :(得分:0)

听起来好像在寻找Content-Disposition标题:

// ...

header('Content-Type: image/jpeg');
header('Content-Disposition: attachment; filename="ImageName.jpg"');
imagejpeg(/* ... */);

// ...

我不认为它是标准化的,但大多数主流浏览器都会尊重它。

FYI - 如果您还没有,那么您应该在脚本底部的四个imagejpeg选项中删除/评论三个 - 否则可能会导致错误/警告。