PHP 实现的将图片转换为TXT

今天在用PHP写一个小插件的时候,遇到了一个小小的问题,就是需要将图片转换为TXT文本的内容,简单的说就是将图片转换为ASCII码,下面把代码分享给大家。

PHP 实现的将图片转换为TXT

  1. <?php
  2. /*
  3. 2015年10月19日10:24:59
  4. */
  5. // 打开一幅图像
  6. $file_name='d:\ascii_dora.png';
  7. $chars = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ";
  8. function getimgchars($color_tran,$chars){
  9. $length = strlen($chars);
  10. $alpha=$color_tran['alpha'];
  11. $r=$color_tran['red'];
  12. $g=$color_tran['green'];
  13. $b=$color_tran['blue'];
  14. $gray = intval(0.2126 * $r + 0.7152 * $g + 0.0722 * $b);
  15. if($gray==0){
  16. return '.';
  17. }
  18. if($gray<196){
  19. $unit = (256.0 + 1)/$length;
  20. return $chars[intval($gray/$unit)];
  21. }
  22. return " ";
  23. }
  24. function color_img($color_tran,$chars){
  25. $length = strlen($chars);
  26. $alpha=$color_tran['alpha'];
  27. $r=$color_tran['red'];
  28. $g=$color_tran['green'];
  29. $b=$color_tran['blue'];
  30. $gray = intval(0.2126 * $r + 0.7152 * $g + 0.0722 * $b);
  31. $rand=rand (0, $length-1);
  32. $color="rgb(".$r.",".$g.",".$b.")";
  33. $char=$chars[$rand];
  34. return '<span .$color.'" >'.$char."</span>";;
  35. }
  36. function resize_img($file_name,$chars,$flage=true){
  37. //header('Content-Type: image/jpeg');
  38. list($width, $height,$type) = getimagesize($file_name);
  39. $fun='imagecreatefrom' . image_type_to_extension($type, false);
  40. if($type==3){
  41. $flage=false;
  42. }
  43. $fun($file_name);
  44. $new_height =100;
  45. $percent=$height/$new_height;
  46. $new_width=$width/$percent;
  47. $image_p = imagecreatetruecolor($new_width, $new_height);
  48. $image = $fun($file_name);
  49. imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
  50. if($flage){
  51. return $image_p;
  52. }else{
  53. return $image;
  54. }
  55. }
  56. $im=resize_img($file_name,$chars);
  57. $width=imagesx($im);
  58. $height=imagesy($im);
  59. $back_text="";
  60. for($i=1;$i<=$height;$i++){
  61. for($j=1;$j<=$width;$j++){
  62. $color_index = imagecolorat($im, $j-1, $i-1);
  63. $color_tran = imagecolorsforindex($im, $color_index);
  64. $back_text.=color_img($color_tran,$chars,false);
  65. }
  66. $back_text.="<br/>";
  67. }
  68. echo "<pre>";
  69. echo $back_text;
  70. echo "</pre>";
  71. //file_put_contents('1.txt',$back_text);