【问题标题】:Wordpress function to convert from GIF to JPG and set it as the POST THUMBNAIL/FEATURE IMAGEWordpress 功能将 GIF 转换为 JPG 并将其设置为 POST THUMBNAIL/FEATURE IMAGE
【发布时间】:2013-12-03 04:57:31
【问题描述】:

所以我有一个带有一堆动画 GIF 的 WordPress 网站,我设法使用这个 PHP 脚本将我的图像从 GIF 转换为 JPG:

<?php

//This function gif2jpeg take three parameter as argument. two argument are optional
//first will take the gif file name. second for file name to save the converted file. third argument is an color array

//EXAMPLE:
$gifName = $_GET['gif_name']; //ABSOLUTE PATH OF THE IMAGE (according to its location)
$c['red']=255;
$c['green']=0;
$c['blue']=0;
echo gif2jpeg($gifName, '', $c);


function gif2jpeg($p_fl, $p_new_fl='', $bgcolor=false){
  list($wd, $ht, $tp, $at)=getimagesize($p_fl);
  $img_src=imagecreatefromgif($p_fl);
  $img_dst=imagecreatetruecolor($wd,$ht);
  $clr['red']=255;
  $clr['green']=255;
  $clr['blue']=255;
  if(is_array($bgcolor)) $clr=$bgcolor;
  $kek=imagecolorallocate($img_dst,
                  $clr['red'],$clr['green'],$clr['blue']);
  imagefill($img_dst,0,0,$kek);
  imagecopyresampled($img_dst, $img_src, 0, 0,
                  0, 0, $wd, $ht, $wd, $ht);
  $draw=true;
  if(strlen($p_new_fl)>0){
    if($hnd=fopen($p_new_fl,'w')){
      $draw=false;
      fclose($hnd);
    }
  }
  if(true==$draw){
    header("Content-type: image/jpeg");
    imagejpeg($img_dst);
  }else imagejpeg($img_dst, $p_new_fl);
  imagedestroy($img_dst);
  imagedestroy($img_src);
}

?>

如何使用?

Add the above code into a php file 'convertGifToJpeg.php'
Add an <img tag. <img src="http://mydomain.com/convertGifToJpeg.php?gif_name=/images/animated_image.gif" width="200" height="200" />

它的工作就像一个魅力!

现在我正在构建一个函数来从 GIF (动画图像) 中获取静态图像 (JPG),并在每次将 GIF 上传到 POST 时将其设置为 POST THUMBNAIL/FEATURE 图像:

function gif_to_jpg($post_id) {
// if attachment is a gif extension
if($attachments[$i]['mime'] == 'image/gif' ){
$gifurl = wp_get_attachment_url( $post_id ); // GET THE URL OF THE MEDIA IMAGE UPLOADED
// build the string
$gif_to_jpg = 'http://mydomain.com/convertGifToJpeg.php?gif_name=' . $gifurl . '';
  // next, download the URL of the JPG image
        media_sideload_image($gif_to_jpg, $post_id, 'Sample GIF TO JPG image.');

// find the most recent attachment for the given post
        $attachments = get_posts(
            array(
                'post_type' => 'attachment',
                'numberposts' => 1,
                'order' => 'ASC',
                'post_parent' => $post_id
            )
        );
        $attachment = $attachments[0];

        // and set it as the post thumbnail
        set_post_thumbnail( $post_id, $attachment->ID );} // end if
} // gif_to_jpg
add_action('save_post', 'gif_to_jpg'); 

但它根本不起作用......你们能帮帮我吗?

【问题讨论】:

  • 我不确定你期望在media_sideload_image 中发生什么,但它绝对不会通过将图像传递给该函数来将 gif 转换为 jpg。
  • 我不是专家...我们将不胜感激!
  • 您的代码开始出现问题。你在哪里设置$i?正如我所看到的, wp_get_attachment_url 将 $attachment_id 作为第一个参数。我说的是这两行:if($attachments[$i]['mime'] == 'image/gif' ){ $gifurl = wp_get_attachment_url( $post_id );
  • 我删除 $i 并更改 wp_get_attachment_url( $post_id );到 wp_get_attachment_url( $id );什么都没有发生......

标签: php jquery wordpress image


【解决方案1】:

您可以为此使用一个名为 GifExtractor 的类

这将从 gif 文件中提取帧,并允许您对资源做任何您想做的事情(使用 imagejpeg 保存它们或使用 imagepng 保存 png)。

不过,查看您的代码,您没有定义 $i,因此它基本上没有从您的帖子输入中获取任何内容,并且无法在此处真正处理任何内容。

在这种情况下,我会使用 wp_check_filetype()。它会在您为服务器端 gif 文件定义的数组中返回媒体的扩展名和 mime

$getMimeType = wp_check_filetype(get_post_thumbnail_id($post_id));
var_dump($getMimeType);

var_dumping 此数据(如果图像存在)应返回一个包含此部分所需数据的数组,其中包含 ['ext'] 和 ['mime']。

为了将 gif 转换为 JPG,我们首先要抓取帧(单帧或多帧):

function extractJPGFromGif( $imagePath ) {

        $frameImages = null;

        if ( \GifFrameExtractor\GifFrameExtractor::isAnimatedGif( $imagePath ) ) { // check this is an animated GIF

            $gfe = new \GifFrameExtractor\GifFrameExtractor();
            $gfe->extract( $imagePath );

            $frameImages = $gfe->getFrameImages();

        }

        return $frameImages;
    }

这只会返回帧。一个非常简单的函数,可以很容易地用维度等进行扩展。

然后我们抓取第一帧并在我们的 save_post 钩子中转换资源:

注意:在开始处理服务器端的文件/目录之前,您甚至可以确保您的目录是可写的,以 is_writable($directory_path) 开头。

function wpse_20343192_ryan( $post_id ) {
        /**
         * Get extension of media to see if it is a gif file
         */
        $fileExtension = wp_check_filetype( get_post_thumbnail_id( $post_id ) );
        if ( $fileExtension['ext'] == 'gif' ) {

            /**
             * Get server location of gif image file
             */
            $gifurl = get_attached_file( get_post_thumbnail_id( $post_id ) );

            /**
             * Extract frames from gif file
             */
            $gifFrames = extractJPGFromGif( $gifurl );

            /**
             * Takes 1st gif frame, converts it to the existing gif file and then sets output quality to 75
             * It then sets the post thumbnail if conversion was successful
             * Note: You can create multiple frames - i suggest looking into the GifExtractor codebase in github
             */
            if ( @imagejpeg( $gifFrames[0], $gifurl, 75 ) ) {

                /**
                 * Generate our arguments for new media attachment
                 */
                $jpgInsert = array(
                    'guid'           => $gifurl,
                    'post_mime_type' => 'image/jpg',
                    'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $gifurl ) ),
                    'post_content'   => '',
                    'post_status'    => 'inherit'
                );

                /**
                 * Insert new media attachment and contain new attachment ID into $thumbnail_id
                 */
                $thumbnail_id = wp_insert_attachment($jpgInsert, $post_id);

                /**
                 * Set post thumbnail with new converted thumbnail
                 */
                set_post_thumbnail( $post_id, $thumbnail_id );
            }
        }
    }
add_action( 'save_post', 'wpse_20343192_ryan' );

GifExtractor 类允许更多可能性,例如获取 gif 的持续时间、指定 gif 的时间段以及要获取的帧等……我强烈建议查看 Github 上的代码库并熟悉这些可能性。

您还可以在进行 imagejpg 转换时构建自己的自定义 jpg 文件位置。

注意:请记住,您需要将类库包含到您的 wordpress 环境中或使用作曲家环境并从 Packagist 获取它们

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-03
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 2010-10-31
    • 2012-01-22
    • 1970-01-01
    相关资源
    最近更新 更多