Generate thumbnail for text file

2019-09-16 19:14发布

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.

4条回答
男人必须洒脱
2楼-- · 2019-09-16 19:55

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");
查看更多
smile是对你的礼貌
3楼-- · 2019-09-16 19:55
$image = new Imagick();
$image->readImage("text:" . $filename . "[0]");
$image->resizeImage($width, $height, Imagick::FILTER_LANCZOS, 1);
$image->setImageFormat('png');
$image->writeImage($linkImage);
查看更多
乱世女痞
4楼-- · 2019-09-16 19:58

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

查看更多
虎瘦雄心在
5楼-- · 2019-09-16 20:00

You can use ffmpeg:

 ffmpeg -video_size 640x480 -chars_per_frame 60000 -i in.txt -frames:v 1 out.png

enter image description here

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.

查看更多
登录 后发表回答