当前位置:首页 > PHP教程 > php图像处理 > 列表

PHP 实现的将图片转换为TXT

发布:smiling 来源: PHP粉丝网  添加日期:2021-06-20 17:14:11 浏览: 评论:0 

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

PHP 实现的将图片转换为TXT

  1. <?php 
  2. /* 
  3. 2015年10月19日10:24:59 
  4.  
  5. */ 
  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.  
  18.   if($gray==0){ 
  19.     return '.'; 
  20.   } 
  21.  
  22.   if($gray<196){ 
  23.      $unit = (256.0 + 1)/$length; 
  24.     return $chars[intval($gray/$unit)]; 
  25.   } 
  26.  
  27.   return " "; 
  28.  
  29. } 
  30.  
  31. function color_img($color_tran,$chars){ 
  32.   $length = strlen($chars); 
  33.   $alpha=$color_tran['alpha']; 
  34.  
  35.   $r=$color_tran['red']; 
  36.   $g=$color_tran['green']; 
  37.   $b=$color_tran['blue']; 
  38.   $gray = intval(0.2126 * $r + 0.7152 * $g + 0.0722 * $b); 
  39.   $rand=rand (0, $length-1); 
  40.   $color="rgb(".$r.",".$g.",".$b.")"; 
  41.   $char=$chars[$rand]; 
  42.   return '<span style="color:'.$color.'" >'.$char."</span>";; 
  43.     
  44. } 
  45.  
  46. function resize_img($file_name,$chars,$flage=true){ 
  47.   //header('Content-Type: image/jpeg'); 
  48.   list($width, $height,$type) = getimagesize($file_name); 
  49.   $fun='imagecreatefrom' . image_type_to_extension($type, false); 
  50.   if($type==3){ 
  51.     $flage=false; 
  52.   } 
  53.   $fun($file_name); 
  54.   $new_height =100; 
  55.   $percent=$height/$new_height; 
  56.   $new_width=$width/$percent; 
  57.   $image_p = imagecreatetruecolor($new_width, $new_height); 
  58.   $image = $fun($file_name); 
  59.   imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 
  60.   if($flage){ 
  61.     return $image_p; 
  62.   }else{ 
  63.     return $image; 
  64.   } 
  65.  
  66. } 
  67.  
  68. $im=resize_img($file_name,$chars); 
  69.  
  70. $width=imagesx($im); 
  71. $height=imagesy($im); 
  72.  
  73. $back_text=""; 
  74.  
  75. for($i=1;$i<=$height;$i++){ 
  76.   for($j=1;$j<=$width;$j++){ 
  77.     $color_index = imagecolorat($im, $j-1, $i-1); 
  78.     $color_tran = imagecolorsforindex($im, $color_index); 
  79.     $back_text.=color_img($color_tran,$chars,false); 
  80.   } 
  81.   $back_text.="<br/>"; 
  82. } 
  83.    
  84. echo "<pre>"; 
  85. echo $back_text; 
  86. echo "</pre>"; 
  87. //file_put_contents('1.txt',$back_text);

Tags: PHP图片转换TXT

分享到: