Suppose a user uploads a .txt or .php file, and I want to generate a .png thumbnail for it. Is there a simple way of doing it, that doesn't require me to open the file and write its contents into a new .png? I have ImageMagick and FFmpeg available, there must be a way to take advantage of that, but I've been looking a lot and no luck yet.
Thanks in advance.
You could always use php's imagettftext function.
It would give you a representation of what is in the text file.
http://php.net/manual/en/function.imagettftext.php
You can use ffmpeg
:
ffmpeg -video_size 640x480 -chars_per_frame 60000 -i in.txt -frames:v 1 out.png
However, it has some caveats:
By default it renders 6000 characters per frame, so it may not draw all of your text. You can change this with the -chars_per_frame
and/or -framerate
input options. Default frame rate is 25.
The text will not be automatically word wrapped so you will have to add line breaks for the text to fit your output video size.
You can use PHP's class imagick
to convert the file to image.
It will work for a txt file nicely.
try
{
$im = new imagick("inputfile.txt[0]");
if ($im)
{
$im->setImageAlphaChannel(imagick::ALPHACHANNEL_DEACTIVATE);
$im->setImageFormat('jpg');
$im->setImageCompressionQuality(85);
file_put_contents("outfile.jpg",$im->getImageBlob());
}
} catch(Exception $e)
{
echo "cannot process";
}
// When imagick is unable to read the file, it may wrongly
// set internal server error 500 status code.
// I do not understand why that happens, because the script
// continues normally. Anyway, lets overwrite it here for all cases.
header("HTTP/1.1 200 OK");
$image = new Imagick();
$image->readImage("text:" . $filename . "[0]");
$image->resizeImage($width, $height, Imagick::FILTER_LANCZOS, 1);
$image->setImageFormat('png');
$image->writeImage($linkImage);