php 如何将image图片转化为字符串(GD库操作及imagick两种实现方式)

效果

 

代码:

<?php
/**
* 图片转换为字符图
* @param string $imagePath 图片地址
* @param int $width x轴方向缩放比例
* @param int $height y轴方向缩放比例
* @return string 生成的字符串图
*/
function img2String($imagePath,$width=1,$height=1)
{
    //检查是否安装 php_imagick 扩展
    if(!extension_loaded("imagick")){
        exit("请先安装 imagick 模块");
    }
    $imagick = new \Imagick(realpath($imagePath));
    //将生成的imagick对象转化为一个像素迭代器,可以从该迭代器中获取没个像素的 rgb 的值。不知道什么是rgb的请问度娘
    $imageIterator = new \ImagickPixelIterator($imagick);
     $str='O80GCLft*+;:,. ';
    foreach ($imageIterator as $rows => $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);

GD:

/**
* 图片转为字符串
* @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);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值