具有目标文件大小的PHP GD Jpeg [英] PHP GD Jpeg with a target filesize

查看:66
本文介绍了具有目标文件大小的PHP GD Jpeg的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向PHP/GD提供图像资源和目标文件大小,并使其输出该目标大小的JPEG文件.说,我有一个500KB的PNG图片,需要为100KB.

I'd like to feed PHP/GD an image resource and a target file size and have it output a JPEG file of that target size. Say, I have a 500KB PNG image that needs to be 100KB.

示例.

function target_image_filesize($im,$target_size){
  //create gd image
  //return a new image resource of specified size
}

我知道我已经看到了用于此功能的函数,并且如果可能的话,我不想重新发明它.

I know I've seen a function for this floating around, and it's not something I'm looking to re-invent if possible.

推荐答案

如果其他人也遇到同样的问题,这应该有所帮助.

If anyone else has this same problem, this should help.

function make_jpeg_target_size($file,$saveDir,$targetKB){
    $imageInfo = getimagesize($file);
    $filename = array_shift(explode('.',basename($file)));
    switch($imageInfo['mime']){
        case 'image/jpeg':
            $src = imagecreatefromjpeg($file);
            break;
        case 'image/gif':
            $src = imagecreatefromgif($file);
            break;
        case 'image/png':
            $src = imagecreatefrompng($file);
            break;
    }
    $target = $targetKB*1024;
    $start_q = 1;
    $cur_q = 99;
    while($cur_q > $start_q){
        $temp_file = tempnam(sys_get_temp_dir(), 'checksizer');
        $out = imagejpeg($src, $temp_file, $cur_q);
        $size = filesize($temp_file);
        if($size <= $target){
            $s = $targetKB.'kb';
            $saveAs = str_replace("//","/",$saveDir.'/'.$filename.'-'.$s.'.jpg');
            copy($temp_file, $saveAs);
            unlink($temp_file);
            $cur_q=0;
        }
        $cur_q=$cur_q-1;
    }
    if($saveAs == ''){
        return false;
    }else{
        return $saveAs;
    }
}

这篇关于具有目标文件大小的PHP GD Jpeg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆