简体   繁体   English

上传带有水印文字的图片

[英]upload image with watermark text

i have php code for upload image and add text watermark, but i have a little problem with the output. 我有用于上传图片和添加文本水印的php代码,但我在输出方面存在一些问题。

my code success result image with text watermark like this: result 1 我的代码成功结果图像带有文本水印,如下所示: 结果1

but i want the output like this: result 2 但我想要这样的输出: 结果2

this is my code: 这是我的代码:

  function UploadImage($img_name){
   $vdir_upload = "img/upload/";
   $vfile_upload = $vdir_upload . $img_name;
   $file_name = basename($_FILES["img_1"]["name"]);
   move_uploaded_file($_FILES["img_1"]["tmp_name"], $vfile_upload);

   switch (strtolower(pathinfo($file_name, PATHINFO_EXTENSION))) {
          case "jpg" :
               $im_src = imagecreatefromjpeg($vfile_upload);
          break;
          case "jpeg" :
               $im_src = imagecreatefromjpeg($vfile_upload);
          break;
          case "gif" :
               $im_src = imagecreatefromgif($vfile_upload);
          break;
          case "png" :
               $im_src = imagecreatefrompng($vfile_upload);
          break;
          default :
                trigger_error("Error Bad Extention");
                exit();
          break;
     }
     $src_width = imageSX($im_src);
     $src_height = imageSY($im_src);
     $dst_width = 1979;
     $dst_height = ($dst_width/$src_width)*$src_height;
     $im = imagecreatetruecolor($dst_width,$dst_height);
     imagecopyresampled($im, $im_src, 0, 0, 0, 0, $dst_width, $dst_height, $src_width, $src_height);
     $font = 'Aliquam.ttf';
     $red = imagecolorallocate($im, 255, 0, 0);
     imagettftext($im, 30, 0, 10, 50, $red, $font, $_POST["color"]);
     imagejpeg($im,$vdir_upload . $_POST["number"].".jpg");
     imagedestroy($im_src);
     imagedestroy($im);
   }

how can I get the result as above? 我如何获得如上所述的结果? sorry for my bad english, thanks in advance... 对不起,我的英语不好,谢谢。

First of all - if you want to extend the width of the image by a margin I would take the original width of the image, add the width of your margin (lets call it $extraWidth and assume it is defined somewhere) and adjust your imagecreatetruecolor call with the new width. 首先-如果您想将图像的宽度扩大一点,我将采用图像的原始宽度,添加您的边界的宽度(我们将其称为$ extraWidth并假设它在某处定义)并调整您的图像。用新的宽度调用。 Then you allocate a color and fill the remaining space with a rectangle for your color as shown below. 然后分配一种颜色,并用矩形填充剩余空间,如下所示。

$im = imagecreatetruecolor($dst_width+$extraWidth, $dst_height);
$color = imagecolorallocate($im, 0, 0, 255); // this is blue - change to what you want
imagefilledrectangle($im, $dst_width, 0, $dst_width+$extraWidth, $dst_height, $color);

Please note I have not tested this code, merely referred to the documentation. 请注意,我尚未测试此代码,仅参考了文档。

$pixel_height_of_character = 30; // change this to actual pixel height of a char
$pixel_gap_between_chars = 3;
$start_from_edge_of_margin = 3;
$string_chars = str_split($_POST['color']);
$start = ($dst_height / 2) - ((count($string_chars) * ($pixel_height_of_character+$pixel_gap_between_chars)) / 2)
// probably should round this
// also need to deduct one half of pixel gap from the result for centering purposes - i think - double check my math.
$left = $start_from_edge_of_margin + $dst_width;
foreach($string_chars as $char){
    $top = $start + $pixel_height_of_character;
    imagettftext($im, 30, 0, $left, $top, $red, $font, $char);
    $start = $top + $pixel_gap_between_chars;
}

So. 所以。 That is quite a bit to explain. 可以解释很多。

Basically you calculate the dimensions of each character - then using those dimensions calculate where the first character must start - then draw on the characters one at a time in a loop. 基本上,您要计算每个字符的尺寸-然后使用这些尺寸计算第一个字符必须在哪里开始-然后在一个循环中一次绘制一个字符。

By no means is this code complete - if the provided word is too long it will exceed the bounds of the image so you should test for that. 此代码绝不完整-如果提供的单词太长,它将超出图像的边界,因此您应该对此进行测试。 Also it may not get alignments perfect - but it's a good start. 同样,它可能无法使对齐方式完美-但这是一个好的开始。

The modified code: 修改后的代码:

  function UploadImage($img_name){
   $vdir_upload = "img/upload/";
   $vfile_upload = $vdir_upload . $img_name;
   $file_name = basename($_FILES["img_1"]["name"]);
   move_uploaded_file($_FILES["img_1"]["tmp_name"], $vfile_upload);

   switch (strtolower(pathinfo($file_name, PATHINFO_EXTENSION))) {
          case "jpg" :
               $im_src = imagecreatefromjpeg($vfile_upload);
          break;
          case "jpeg" :
               $im_src = imagecreatefromjpeg($vfile_upload);
          break;
          case "gif" :
               $im_src = imagecreatefromgif($vfile_upload);
          break;
          case "png" :
               $im_src = imagecreatefrompng($vfile_upload);
          break;
          default :
                trigger_error("Error Bad Extention");
                exit();
          break;
     }
     $src_width = imageSX($im_src);
     $src_height = imageSY($im_src);
     $dst_width = 1979;
     $dst_height = ($dst_width/$src_width)*$src_height;
         $im = imagecreatetruecolor($dst_width+$extraWidth, $dst_height);
         $color = imagecolorallocate($im, 0, 0, 255); // this is blue - change to what you want
         imagefilledrectangle($im, $dst_width, 0, $dst_width+$extraWidth, $dst_height, $color);
     imagecopyresampled($im, $im_src, 0, 0, 0, 0, $dst_width, $dst_height, $src_width, $src_height);
     $font = 'Aliquam.ttf';
     $red = imagecolorallocate($im, 255, 0, 0);
     $pixel_height_of_character = 30; // change this to actual pixel height of a char
    $pixel_gap_between_chars = 3;
    $start_from_edge_of_margin = 3;
    $string_chars = str_split($_POST['color']);
    $start = ($dst_height / 2) - ((count($string_chars) * ($pixel_height_of_character+$pixel_gap_between_chars)) / 2)
    // probably should round this
    // also need to deduct one half of pixel gap from the result for centering purposes - i think - double check my math.
    $left = $start_from_edge_of_margin + $dst_width;
    foreach($string_chars as $char){
        $top = $start + $pixel_height_of_character;
        imagettftext($im, 30, 0, $left, $top, $red, $font, $char);
        $start = $top + $pixel_gap_between_chars;
    }
     imagejpeg($im,$vdir_upload . $_POST["number"].".jpg");
     imagedestroy($im_src);
     imagedestroy($im);
   }
class Watermark {
/**
 *
 * @var image resource
 */
private $image = null;

/**
 *
 * @var image resource
 */
private $watermark = null;

/**
 *
 * @var string
 */
private $output_file = null;

/**
 *
 * @var int
 */
private $type = '';


const BOTTOM_RIGHT = 1;
const CENTER = 2;
const BOTTOM_RIGHT_SMALL = 3;

/**
 *
 * @param string $path_to_image
 */
public function __construct($path_to_image = ''){
    if (file_exists($path_to_image)){
        $this->image = $path_to_image;
    }
    $this->type = Watermark::BOTTOM_RIGHT;
}

/**
 *
 * @param string $path_to_watermark
 * @return boolean
 */
public function setWatermarkImage($path_to_watermark){
    if (file_exists($path_to_watermark) && preg_match('/\.png$/i',$path_to_watermark)){
        $this->watermark = $path_to_watermark;
        return true;
    }
    return false;
}

/**
 *
 * @return boolean
 */
public function save(){
    $this->output_file = $this->image;
    return $this->process();
}

/**
 *
 * @param string $path_to_image
 * @return boolean
 */
public function saveAs($path_to_image){
    $this->output_file = $path_to_image;
    return $this->process();
}

/**
 *
 * @param int $type
 */
public function setType($type){
    $this->type = $type;
}

/**
 *
 * @return boolean
 */
private function process(){
    $watermark = imagecreatefrompng($this->watermark);
    if ($watermark){
        $image = imagecreatefromjpeg($this->image);
        if ($image){
            switch ($this->type){
                case Watermark::BOTTOM_RIGHT:
                    return $this->watermark_bottom_right($image, $watermark);
                    break;
                case Watermark::CENTER:
                    return $this->watermark_center($image, $watermark);
                    break;
                case Watermark::BOTTOM_RIGHT_SMALL:
                    return $this->watermark_bottom_right_small($image, $watermark);
                    break;
            }
            return true;
        }else{
           return false;
        }
    }else {
        return false;
    }
}

/**
 *
 * @param image resource $image
 * @param image resource $watermark
 * @return boolean
 */
private function watermark_bottom_right(&$image, &$watermark){
    $watermark_width = imagesx($watermark);
    $watermark_height = imagesy($watermark);
    $size = getimagesize($this->image);
    $dest_x = $size[0] - $watermark_width - 5;
    $dest_y = $size[1] - $watermark_height - 5;
    imagecopy($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height);

    imagejpeg($image,$this->output_file,100);
    imagedestroy($image);
    imagedestroy($watermark);
    return true;
}

/**
 *
 * @param image resource $image
 * @param image resource $watermark
 * @return booelan
 */
private function watermark_center(&$image, &$watermark){
    $size = getimagesize($this->image);
    $watermark_x = imagesx($watermark);
    $watermark_y = imagesy($watermark);
    $im_x = $size[0];
    $im_y = $size[1];
    $cof = $im_x/($watermark_x*1.3); // 5/1 = im_x/(wx*cof) ; wx*cof = im_x/5 ; cof = im_x/wx*5
    $w = intval($watermark_x*$cof);
    $h = intval($watermark_y*$cof);

    $watermark_mini = ImageCreateTrueColor($w, $h);
    imagealphablending($watermark_mini, false);
    imagesavealpha($watermark_mini,true);
    ImageCopyResampled ($watermark_mini, $watermark, 0, 0, 0, 0, $w, $h, $watermark_x, $watermark_y);


    $dest_x = $im_x - $w - (($im_x-$w)/2);
    $dest_y = $im_y - $h - (($im_y-$h)/2);

    imagecopy($image, $watermark_mini, $dest_x, $dest_y, 0, 0, $w, $h);

    imagejpeg($image,$this->output_file,100);
    imagedestroy($image);
    imagedestroy($watermark);
    return true;
}

/**
 *
 * @param image resource $image
 * @param image resource $watermark
 * @return boolean
 */
private function watermark_bottom_right_small(&$image, &$watermark){
    $size = getimagesize($this->image);
    $orig_watermark_x = imagesx($watermark);
    $orig_watermark_y = imagesy($watermark);
    $im_x = $size[0];
    $im_y = $size[1];
    $cof = $im_x/($orig_watermark_x*5); // 5/1 = im_x/(wx*cof) ; wx*cof = im_x/5 ; cof = im_x/wx*5
    $w = intval($orig_watermark_x*$cof);
    $h = intval($orig_watermark_y*$cof);

    $watermark_mini = ImageCreateTrueColor($w, $h);
    imagealphablending($watermark_mini, false);
    imagesavealpha($watermark_mini,true);
    ImageCopyResampled ($watermark_mini, $watermark, 0, 0, 0, 0, $w, $h, $orig_watermark_x, $orig_watermark_y);
    //
    $dest_x = $size[0] - $w - 5;
    $dest_y = $size[1] - $h -5;

    imagecopy($image, $watermark_mini, $dest_x,$dest_y , 0, 0, $w, $h);
    imagejpeg($image,$this->output_file,100);
    imagedestroy($image);
    imagedestroy($watermark);
    imagedestroy($watermark_mini);
    return true;
}
}

use 采用

$watermark = new Watermark('file_path.jpg');
$watermark->setWatermarkImage('watermark_path.png');
$watermark->setType(Watermark::CENTER);
$watermark->saveAs('file_path.jpg');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM