【问题标题】:Generate thumbnail for text file为文本文件生成缩略图
【发布时间】:2013-03-24 05:32:13
【问题描述】:

假设用户上传了一个 .txt 或 .php 文件,我想为它生成一个 .png 缩略图。有没有一种简单的方法,不需要我打开文件并将其内容写入新的.png?我有 ImageMagick 和 FFmpeg 可用,一定有办法利用它,但我一直在寻找,但还没有运气。

提前致谢。

【问题讨论】:

  • 我看过很多关于如何将各种图像格式转换为缩略图的教程。但是我找不到任何关于转换 .txt 文件的内容,但我确信它可以完成。缩略图对于文本文件来说不会很有意义。
  • 是的,但它可以让您了解文本的长度和密度。

标签: php ffmpeg imagemagick thumbnails


【解决方案1】:

你可以使用ffmpeg:

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

但是,它有一些警告:

  • 默认情况下,它每帧渲染 6000 个字符,因此它可能不会绘制所有文本。您可以使用-chars_per_frame 和/或-framerate 输入选项更改此设置。默认帧率为 25。

  • 文本不会自动换行,因此您必须为文本添加换行符以适合您的输出视频大小。

【讨论】:

    【解决方案2】:

    你总是可以使用 php 的imagettftext 函数。

    它将为您提供文本文件中的内容的表示。

    http://php.net/manual/en/function.imagettftext.php

    【讨论】:

    • +1。我也会使用这种方法。似乎是最简单、最有效的做事方式。
    【解决方案3】:

    您可以使用 PHP 的类 imagick 将文件转换为图像。 它适用于 txt 文件。

    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");
    

    【讨论】:

      【解决方案4】:
      $image = new Imagick();
      $image->readImage("text:" . $filename . "[0]");
      $image->resizeImage($width, $height, Imagick::FILTER_LANCZOS, 1);
      $image->setImageFormat('png');
      $image->writeImage($linkImage);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-26
        • 1970-01-01
        • 2010-11-03
        • 2014-05-01
        • 2018-10-19
        相关资源
        最近更新 更多