在CodeIgniter PHP中上传之前调整图像大小

时间:2012-10-31 09:27:21

标签: php codeigniter image-resizing

我的函数中有以下代码块:

$target_path = "uploads/";

        $target_path = $target_path . basename( $_FILES['image']['name']);

        if(move_uploaded_file($_FILES['image']['tmp_name'], $target_path))
       {
             echo  "The file ".  basename( $_FILES['image']['name'])." has been uploaded";           
       }      
       else   
       {
            echo "There was an error uploading the file, please try again!";
       }

现在我想在上传之前调整图片大小。我正在使用CodeIgniter框架。我有这段代码:

$config['upload_path'] = "uploads/";


 $path=$config['upload_path'];

        $config['overwrite'] = FALSE;
        $config['remove_spaces'] = TRUE;
        $config['allowed_types'] = 'gif|jpg|jpeg|png|JPEG|JPG|PNG';
        $config['max_size'] = '1024';
        $config['maintain_ratio'] = TRUE;
        $config['max_width'] = '1000';
        $config['max_height'] = '1000';
        $this->load->library('upload',$config);

但这不能正常运作。我正在寻找一个很好的解决方案,其中图像按我指定的高度和宽度上传。

2 个答案:

答案 0 :(得分:4)

这是我使用的功能,允许我们的员工上传产品图片,上传完整尺寸的图片和两张较小的图片(我只在这里包含了tn_版本的代码)。它需要它所做的值,因为它在我的控制器中,可以从多个地方调用。 $ control是你正在使用的fileUpload控件的名称,$ path是保存路径,$ imageName是来自控件的尺寸,而size只允许我指定要制作的版本,在我的情况下它接收所有版本,med和tn作为选项。您可以根据需要制作尽可能多的产品。正如VDP所提到的,如果你不改变任何设置,你只能限制在2mb以下,但这对我来说没什么问题,所以我只是回复一个错误。

我没有在所有btw上使用CI图片上传库。它只是通过正常的文件上传和ajax发送到控制器。它在主视图上使用iframe来显示错误或成功。

我的控制器上传功能:

function doUpload($control, $path, $imageName, $sizes)
{
    if( ! isset($_FILES[$control]) || ! is_uploaded_file($_FILES[$control]['tmp_name']))
    {
        print('No file was chosen');
        return FALSE;
    } 
    if($_FILES[$control]['size']>2048000)
    {
        print('File is too large ('.round(($_FILES[$control]["size"]/1000)).'kb), please choose a file under 2,048kb');
        return FALSE;
    }
    if($_FILES[$control]['error'] !== UPLOAD_ERR_OK)
    {
        print('Upload failed. Error code: '.$_FILES[$control]['error']);
        Return FALSE;
    }
    switch(strtolower($_FILES[$control]['type']))
    {
    case 'image/jpeg':
            $image = imagecreatefromjpeg($_FILES[$control]['tmp_name']);
            move_uploaded_file($_FILES[$control]["tmp_name"],$path.$imageName);
            break;
    case 'image/png':
            $image = imagecreatefrompng($_FILES[$control]['tmp_name']);
            move_uploaded_file($_FILES[$control]["tmp_name"],$path.$imageName);
            break;
    case 'image/gif':
            $image = imagecreatefromgif($_FILES[$control]['tmp_name']);
            move_uploaded_file($_FILES[$control]["tmp_name"],$path.$imageName);
            break;
    default:
           print('This file type is not allowed');
           return false;
    }
    @unlink($_FILES[$control]['tmp_name']);
    $old_width      = imagesx($image);
    $old_height     = imagesy($image);


    //Create tn version
    if($sizes=='tn' || $sizes=='all')
    {
    $max_width = 100;
    $max_height = 100;
    $scale          = min($max_width/$old_width, $max_height/$old_height);
    if ($old_width > 100 || $old_height > 100)
    {
    $new_width      = ceil($scale*$old_width);
    $new_height     = ceil($scale*$old_height);
    } else {
        $new_width = $old_width;
        $new_height = $old_height;
    }
    $new = imagecreatetruecolor($new_width, $new_height);
    imagecopyresampled($new, $image,0, 0, 0, 0,$new_width, $new_height, $old_width, $old_height);
    switch(strtolower($_FILES[$control]['type']))
    {
    case 'image/jpeg':
            imagejpeg($new, $path.'tn_'.$imageName, 90);
            break;
    case 'image/png':
            imagealphablending($new, false);
            imagecopyresampled($new, $image,0, 0, 0, 0,$new_width, $new_height, $old_width, $old_height);
            imagesavealpha($new, true); 
            imagepng($new, $path.'tn_'.$imageName, 0);
            break;
    case 'image/gif':
            imagegif($new, $path.'tn_'.$imageName);
            break;
    default:
    }
    }

    imagedestroy($image);
    imagedestroy($new);
    print '<div style="font-family:arial;"><b>'.$imageName.'</b> Uploaded successfully. Size: '.round($_FILES[$control]['size']/1000).'kb</div>';
}

查看HTML:

echo '<input type="file" name="manuLogoUpload" id="manuLogoUpload" onchange="return ajaxFileUpload2(this);"/>';

查看ajax电话:

        function ajaxFileUpload2(upload_field)
        {
            var re_text = /\.jpg|\.gif|\.jpeg|\.png/i;
            var filename = upload_field.value;
            var imagename = filename.replace("C:\\fakepath\\","");
            if (filename.search(re_text) == -1) 
            {
                alert("File must be an image");
                upload_field.form.reset();
                return false;
            }
            upload_field.form.action = "addManufacturerLogo";
            upload_field.form.target = "upload_iframe";
            upload_field.form.submit();
            upload_field.form.action = "";
            upload_field.form.target = "";
            document.getElementById("logoFileName").value = imagename;
            document.getElementById("logoFileName1").value = imagename;
            document.getElementById("manuLogoText").style.display="block";
            document.getElementById("logoLink").style.display="none";
            $.prettyPhoto.close();
            return true;        
        }

常规控制器功能:

function addManufacturerLogo()
{
    $control = 'manuLogoUpload';
    $image = $_FILES[$control]['name'];
    if($imageName = $this->doUpload($control,LOGO_PATH,$image,'all'))
    {

    } else {

    }
}

config / constants.php&lt;&lt;为LOGO_PATH。更改这些(和名称)以适合您的目的。理由是如果我改变了我想要保存图像的位置,我会在常量中更改它,而不是在整个应用程序中的10个位置。

define('LOGO_PATH',APPPATH.'assets/images/manulogos/');
define('PROD_IMAGE_PATH',APPPATH.'../assets/images/prod_images/');

答案 1 :(得分:3)

最好是使用客户端工具在本地调整图像大小,然后上传。您也可以在服务器端调整大小(使用php gd),但php会将文件复制到内存中,默认情况下,它只能调整大小+/- 2MB的图像。您可以使用php限制上传大小和调整大小,也可以使用Flash,Silverlight或JavaApplets。

以下是another question关于客户端使用flash调整大小

的信息

<强>更新

使用CI的Image Manipulation lib调整服务器端大小的示例

$config['image_library'] = 'gd2';
$config['source_image'] = $_FILES['image']['tmp_name'];
$config['new_image'] = $target_path
$config['maintain_ratio'] = TRUE;
$config['width']    = 250;
$config['height']   = 400;

$this->load->library('image_lib', $config); 

if (!$this->image_lib->resize()) {
    echo $this->image_lib->display_errors();
}

有关the resizing lib

的更多信息