php使用Imagick生成图片的方法

这篇文章主要介绍了php使用Imagick生成图片的方法,实例分析了php基于Imagick实现添加水印、文字的图片功能,具有一定参考借鉴价值,需要的朋友可以参考下。

本文实例讲述了php使用Imagick生成图片的方法,分享给大家供大家参考,具体如下:

这里使用Imagick 生成图片

解决了图片写中文文字乱码问题,添加支持的字体

  1. public function getPic(){
  2. header('Content-Type: text/html; charset=utf-8');
  3. $text = '中粮屯河(sh600737)';//中粮屯河(sh600737)
  4. $watermark = '305988103123zczcxzas';
  5. $len = strlen($text);
  6. $width = 10.5*(($len-8)/3*2+8);
  7. $height = 26;
  8. $imagick = new Imagick();
  9. $color_transparent = new ImagickPixel('#ffffff'); //transparent 透明色
  10. $imagick->newImage($width, $height, $color_transparent, 'jpg');
  11. //$imagick->borderimage('#000000', 1, 1);
  12. $style['font_size'] = 12;
  13. $style['fill_color'] = '#000000';
  14. for($num= strlen($watermark); $num>=0; $num--){
  15. $this->add_text($imagick,substr($watermark, $num,1), 2+($num*8), 30, 1,$style);
  16. $this->add_text($imagick,substr($watermark, $num,1), 2+($num*8), 5, 1,$style);
  17. }
  18. //return;
  19. $style['font_size'] = 20;
  20. $style['fill_color'] = '#FF0000';
  21. $style['font'] = './msyh.ttf'; ///微软雅黑字体 解决中文乱码
  22. //$text=mb_convert_encoding($text,'UTF-8'); //iconv("GBK","UTF-8//IGNORE",$text);
  23. $this->add_text($imagick,$text, 2, 20, 0,$style);
  24. header ( 'Content-type: ' . strtolower ($imagick->getImageFormat ()) );
  25. echo $imagick->getImagesBlob ();
  26. }
  27. // 添加水印文字
  28. public function add_text(& $imagick, $text, $x = 0, $y = 0, $angle = 0, $style = array()) {
  29. $draw = new ImagickDraw ();
  30. if (isset ( $style ['font'] ))
  31. $draw->setFont ( $style ['font'] );
  32. if (isset ( $style ['font_size'] ))
  33. $draw->setFontSize ( $style ['font_size'] );
  34. if (isset ( $style ['fill_color'] ))
  35. $draw->setFillColor ( $style ['fill_color'] );
  36. if (isset ( $style ['under_color'] ))
  37. $draw->setTextUnderColor ( $style ['under_color'] );
  38. if (isset ( $style ['font_family'] ))
  39. $draw->setfontfamily( $style ['font_family'] );
  40. if (isset ( $style ['font'] ))
  41. $draw->setfont($style ['font'] );
  42. $draw->settextencoding('UTF-8');
  43. if (strtolower ($imagick->getImageFormat ()) == 'gif') {
  44. foreach ( $imagick as $frame ) {
  45. $frame->annotateImage ( $draw, $x, $y, $angle, $text );
  46. }
  47. } else {
  48. $imagick->annotateImage ( $draw, $x, $y, $angle, $text );
  49. }
  50. }

希望本文所述对大家的php程序设计有所帮助。