在所选像素上创建一个词云

Aka*_*mar 9 php

我正在努力创造一个人脸的文字云.与类似

为了达到这个目的,我得到了一个人的黑白图像,并将最暗的像素变为黑色,最亮的像素变为白色.这是我的结果

在此输入图像描述

现在我有了一个我想放置文字云的区域.现在我无法弄清楚如何在面部内放置单词以保持单词之间的边距/角度.

这是我到目前为止所做的代码

<?php
set_time_limit(0);
$src = 'person.jpeg';

$im = imagecreatefromjpeg($src);
$size = getimagesize($src);
$width = $size[0];
$height = $size[1];

$image_p = imagecreatetruecolor($width, $height);
imagecopyresampled($image_p, $im, 0, 0, 0, 0, $width, $height, $width, $height);

$white_color = imagecolorallocate($im, 255, 255, 255);
$black_color = imagecolorallocate($im, 0, 0, 0);

$font = __DIR__ . "/testfont.ttf";
$font_size = 16;
$text = "Test text";

$skip = true;
for ($x = 0; $x < $width; $x++) {
    for ($y = 0; $y < $height; $y++) {
        $rgb = imagecolorat($im, $x, $y);
        $r = ($rgb >> 16) & 0xFF;
        $g = ($rgb >> 8) & 0xFF;
        $b = $rgb & 0xFF;


        if ($r >= 126) {
            imagesetpixel($image_p, $x, $y, $white_color);
        } else {
            imagesetpixel($image_p, $x, $y, $black_color);

            if ($x % 20 == 1) {
                imagestring($image_p, 5, $x, $y, 'T', $black_color);
                //imagettftext($image_p, 16, 0, $x, $y, $black_color, $font, $text);
            }
        }
        //var_dump($r, $g, $b);
        //echo "<br/>";
    }
}
imagestring($image_p, 5, 0, 0, 'Hello world!', $black_color);

header('Content-Type: image/jpeg');
imagejpeg($image_p, null, 100);
Run Code Online (Sandbox Code Playgroud)

我试过用imagestring&imagettftext

if ($x % 20 == 1) {
                imagestring($image_p, 5, $x, $y, 'T', $black_color);
                //imagettftext($image_p, 16, 0, $x, $y, $black_color, $font, $text);
            }
Run Code Online (Sandbox Code Playgroud)

并得到奇怪的输出.随着imagettftext时间过长渲染,并与imagestring这就是我得到了什么

在此输入图像描述

小智 0

使用这些函数之一而不是同时使用它们: imagesetpixel 或 imagestring 如果您有黑白照片,请忘记 $black_color 和 $white_color 或将它们添加到此代码中以自定义更多内容。并在最后添加您的自定义标头。

list($w, $h, $type) = getimagesize('person.jpeg');
$resource = imagecreatefromstring(file_get_contents('person.jpeg'));
$img = imagecreatetruecolor($w, $h);
for($y=0; $y<$h; $y+=20)
    for($x=0; $x<$w; $x+=20)
        imagestring($img, 5, $x, $y, 'Hello world!', imagecolorat($resource, $x, $y));
Run Code Online (Sandbox Code Playgroud)