Wordpress函数将从GIF转换为JPG并将其设置为POST THUMBNAIL / FEATURE IMAGE

时间:2013-12-03 04:57:31

标签: php jquery wordpress image

所以我有一个带有一堆动画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(ANIMATED IMAGE)获取静态图像(JPG),并在每次将GIF上传到POST时将其设置为POST THUMBNAIL / FEATURE IMAGE:

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

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

1 个答案:

答案 0 :(得分:0)

您可以使用此类称为GifExtractor

这将从gif文件中提取帧,并允许您使用资源执行您喜欢的操作(使用 imagejpeg 保存,或使用 imagepng 保存)。 / p>

看看你的代码,你没有 $ 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

中获取它们