【发布时间】: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