本文操作环境:windows7系统、PHP7.1版、DELL G3电脑php 图像怎么转换成字符串?php将image图片转化为字符串(GD库操作及imagick两种实现方式)前两天研究php中的 imagick 扩展的时候,突发奇想实现的
本文操作环境:windows7系统、PHP7.1版、DELL G3电脑
php 图像怎么转换成字符串?
php将image图片转化为字符串(GD库操作及imagick两种实现方式)
前两天研究php中的 imagick 扩展的时候,突发奇想实现的一个小功能感觉挺有意思,在这里记录一下:
将一张image图片转化为字符串的形式,先上一张效果图。(运行笔记中的代码需要先安装 php_imagick 扩展 教程可以看这里:PHP扩展之 Imagick安装)
原图:
<?php
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);
复制代码
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);
--结束END--
本文标题: php 图像怎么转换成字符串
本文链接: https://www.lsjlt.com/news/295.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2023-05-25
2023-05-25
2023-05-25
2023-05-25
2023-05-25
2023-05-25
2023-05-25
2023-05-25
2023-05-25
2023-05-25
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0