php 将图片转换为ASCII码的完整示例

前端之家收集整理的这篇文章主要介绍了php 将图片转换为ASCII码的完整示例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编来看看吧。
经测试代码如下:
  1. /**
  2. * 将图片转换为ASCII码
  3. *
  4. * @param
  5. * @arrange (512.笔记) jb51.cc
  6. **/
  7. // 打开一幅图像
  8. $file_name='d:\ascii_dora.png';
  9. $chars = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ";
  10. function getimgchars($color_tran,$chars){
  11. $length = strlen($chars);
  12. $alpha=$color_tran['alpha'];
  13. $r=$color_tran['red'];
  14. $g=$color_tran['green'];
  15. $b=$color_tran['blue'];
  16. $gray = intval(0.2126 * $r + 0.7152 * $g + 0.0722 * $b);
  17. if($gray==0){
  18. return '.';
  19. }
  20. if($gray<196){
  21. $unit = (256.0 + 1)/$length;
  22. return $chars[intval($gray/$unit)];
  23. }
  24. return " ";
  25. }
  26. function color_img($color_tran,$chars){
  27. $length = strlen($chars);
  28. $alpha=$color_tran['alpha'];
  29. $r=$color_tran['red'];
  30. $g=$color_tran['green'];
  31. $b=$color_tran['blue'];
  32. $gray = intval(0.2126 * $r + 0.7152 * $g + 0.0722 * $b);
  33. $rand=rand (0,$length-1);
  34. $color="rgb(".$r.",".$g.",".$b.")";
  35. $char=$chars[$rand];
  36. return '<span style="color:'.$color.'" >'.$char."</span>";;
  37. }
  38. function resize_img($file_name,$chars,$flage=true){
  39. //header('Content-Type: image/jpeg');
  40. list($width,$height,$type) = getimagesize($file_name);
  41. $fun='imagecreatefrom' . image_type_to_extension($type,false);
  42. if($type==3){
  43. $flage=false;
  44. }
  45. $fun($file_name);
  46. $new_height =100;
  47. $percent=$height/$new_height;
  48. $new_width=$width/$percent;
  49. $image_p = imagecreatetruecolor($new_width,$new_height);
  50. $image = $fun($file_name);
  51. imagecopyresampled($image_p,$image,$new_width,$new_height,$width,$height);
  52. if($flage){
  53. return $image_p;
  54. }else{
  55. return $image;
  56. }
  57. }
  58. $im=resize_img($file_name,$chars);
  59. $width=imagesx($im);
  60. $height=imagesy($im);
  61. $back_text="";
  62. for($i=1;$i<=$height;$i++){
  63. for($j=1;$j<=$width;$j++){
  64. $color_index = imagecolorat($im,$j-1,$i-1);
  65. $color_tran = imagecolorsforindex($im,$color_index);
  66. $back_text.=color_img($color_tran,false);
  67. }
  68. $back_text.="<br/>";
  69. }
  70. echo "<pre>";
  71. echo $back_text;
  72. echo "</pre>";
  73. //file_put_contents('1.txt',$back_text);

猜你在找的PHP相关文章