This article mainly introduces the implementation of PHP to convert the image to ASCII code, interested in the friend's reference, I hope to be helpful to everyone.
PHP implemented to convert a picture to TXT
<?php/*2015 October 19 10:24:59*///Open an image $file_name= ' d:\ascii_dora.png '; $chars = "$@b%8&wm#* oahkbdpqwmzo0qlcjuyxzcvunxrjft/\| () 1{}[]?-_+~<>i!li;:,\ "^". "; function Getimgchars ($color _tran, $chars) {$length = strlen ($chars); $alpha = $color _tran[' alpha ']; $r = $color _tran[' red ']; $g = $color _tran[' green '); $b = $color _tran[' Blue '; $gray = Intval (0.2126 * $r + 0.7152 * $g + 0.0722 * $b); if ($gray ==0) {return '. '; } if ($gray <196) {$unit = (256.0 + 1)/$length; return $chars [Intval ($gray/$unit)]; } return "";} function color_img ($color _tran, $chars) {$length = strlen ($chars); $alpha = $color _tran[' alpha ']; $r = $color _tran[' red ']; $g = $color _tran[' green '); $b = $color _tran[' Blue '; $gray = Intval (0.2126 * $r + 0.7152 * $g + 0.0722 * $b); $rand =rand (0, $length-1); $color = "rgb (". $r. ",". $g. ",". $b. ")"; $char = $chars [$rand]; Return ' <span style= ' color: '. $color. ' > '. $char. ' </span> ";; }function resize_img ($file _name, $chars, $flage =true) {//header (' content-tYpe:image/jpeg '); List ($width, $height, $type) = getimagesize ($file _name); $fun = ' Imagecreatefrom '. Image_type_to_extension ($type, false); if ($type ==3) {$flage =false; } $fun ($file _name); $new _height = 100; $percent = $height/$new _height; $new _width= $width/$percent; $image _p = Imagecreatetruecolor ($new _width, $new _height); $image = $fun ($file _name); Imagecopyresampled ($image _p, $image, 0, 0, 0, 0, $new _width, $new _height, $width, $height); if ($flage) {return $image _p; }else{return $image; }} $im =resize_img ($file _name, $chars) $width =imagesx ($im); $height =imagesy ($im); $back _text= ""; for ($i =1; $i <=$ Height; $i + +) {for ($j =1; $j <= $width; $j + +) {$color _index = Imagecolorat ($im, $j-1, $i-1); $color _tran = Imagecolorsforindex ($im, $color _index); $back _text.=color_img ($color _tran, $chars, false); } $back _text.= "<br/>";} echo "<pre>", Echo $back _text;echo "</pre>";//file_put_contents (' 1.txt ', $back _text);
Summary: The above is the entire content of this article, I hope to be able to help you learn.