Wordpress function to convert from GIF to JPG and

2019-08-18 03:03发布

问题:

So i have a WordPress site with a bunch of animated GIFs and i manage to convert my images from GIF to JPG using this PHP script:

<?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);
}

?>

HOW TO USE?

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" />

and its working like a charm!

Now I'm building a function to get an static image (JPG) from a GIF ( ANIMATED IMAGE ) and set it as the POST THUMBNAIL/FEATURE IMAGE every time a GIF is uploaded to a POST by doing this:

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

But its not working at all... Can you guys help me out?

回答1:

You can utilize a class for this called GifExtractor

This will extract frames from a gif file and allow you to do what you'd like with the resources (save them with imagejpeg or png with imagepng).

Looking at your code though, you have no definition of $i so it's essentially grabbing nothing from your post input and doing not able to really process anything here.

I would use wp_check_filetype() in this case.. It will return the extension and mime of your media in an array you define of your serverside gif file

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

var_dumping this data (if the image exists) should return an array with ['ext'] and ['mime'] containing the data needed for this portion.

For converting a gif to JPG we would first grab the frames (singular or multiple):

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;
    }

This will simply return the frames. A very simplistic function as well that can be easily expanded on with dimensions, etc.

We then grab the 1st frame and convert the resource inside our save_post hook:

Note: You can make sure your directory is even writable to begin with is_writable($directory_path) before you begin working with files / directories on the server side.

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 class allows many more possibilities such as getting durations of gifs, specifying time period of gif and what frames to get , etc ... I highly suggest looking into the code base on Github and familiarize yourself with the possibilities.

You can also build out your own custom jpg file location for when you do a imagejpg conversion.

Note: Keep in mind you will need to include the class libraries into your wordpress environment or utilize a composer environment and grab them from Packagist