Home>Article>Backend Development> How to convert php image to string
How to convert php images into strings: 1. Install the php_imagick extension; 2. Convert the image into a string through the "function img2str($img_src,$width_index,$height_index){...}" method That’s it.
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
php How to convert an image into a string?
php converts image pictures into strings (GD library operation and imagick two implementation methods)
Study the imagick extension in php two days ago At that time, I came up with a small function that was quite interesting. I will record it here:
To convert an image into a string, first upload a rendering. (To run the code in the notes, you need to install php_imagick first. The extension tutorial can be found here: Imagick installation of PHP extension)
Original picture:
$pixels) { if($rows%$width == 1 || $width == 1){ echo "\n"; foreach ($pixels as $column => $pixel) { if($column%$height == 1 || $height == 1){ //灰度计算公式 某个像素点的灰度值 = 红色值*0.3 + 绿色值 * 0.59 + 蓝色值 * 0.11 $gray = $pixel->getColor()['r']*0.3 + $pixel->getColor()['g']*0.59 + $pixel->getColor()['b']*0.11; //由于 rgb 三原色的数值范围在 [0,255] 所以求出的灰度值的范围也是 [0,255],所以我们计算像素的 "饱和度" = 灰度值/255; $r = $gray/255; //根据像素的 "饱和度" 选择合适的字符 $offset=(int)ceil($r*(strlen($str)-1)); if($offset==(strlen($str)-1)){ echo " "; }else{ echo $str[$offset]; } } } $imageIterator->syncIterator(); } } } img2String('huawei.jpg',2,1);
Copy code
/** * 图片转为字符串 * @param string $img_src 图片地址 * @param int $width_index 横向缩放比例 * @param int $height_index 纵向缩放比例 * @return string 生成的字符串 **/ function img2str($img_src,$width_index,$height_index){ $resource = imagecreatefromjpeg($img_src); $width = imagesx($resource); $height = imagesy($resource); imagefilter($resource, IMG_FILTER_GRAYSCALE); for ($i=0; $i < $height; $i++) { if($i%$height_index==0){ for ($j=0; $j < $width; $j++) { if($j%$width_index==0){ $color_index = imagecolorat($resource, $j, $i); $rgb = imagecolorsforindex($resource,$color_index); $gray = $rgb['red']; $str='O80GCLft*+;:,. '; $r = $gray/255; $offset=(int)ceil($r*(strlen($str)-1)); echo $str[$offset]; } } echo "\n"; } } } img2str("./huawei.jpg",1,2);
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to convert php image to string. For more information, please follow other related articles on the PHP Chinese website!