本文介绍了图像调整大小,然后在CodeIgniter PHP上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am having the following block of code in my function:

$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框架。我有这个代码:

Now I want to resize the image before uploading. I am using the CodeIgniter framework. I have this code:

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

但这不能正常工作。

推荐答案

这是我使用的函数允许我们的工作人员上传产品图片,它上传的全尺寸图像和两个较小的图像(我只包括一个在这里的tn_版本的代码)。它需要它的值,因为它在我的控制器,可以从多个地方调用。 $ control是您正在使用的fileUpload控件的名称,$ path是保存路径,$ imageName是从控件和大小只允许我指定要生成的版本,在我的情况下,它接收所有,med和tn作为选项。你可以做出多少或尽可能少的你需要。因为VDP提到你限制在2mb以下,如果你不改变任何设置,但对我很好,所以我只是返回一个错误,如果超过了。

This is the function I use to allow our staff to upload product images, it uploads the full size image and two smaller images (I only included the code for one here the tn_ version). It takes the values it does because it's in my controller and can be called from multiple places. $control is the name of the fileUpload control you're using, $path is the save path, $imageName is the from the control and sizes just allows me to specify which versions to make, in my case it receives all, med and tn as options. You could make as many or as few as you need. As VDP mentioned you're limited to under 2mb if you don't change any settings but that's fine for me so I just return an error if it's over that.

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

I don't use the CI image upload library at all btw. It's just sent to the controller via a normal file upload and ajax. It uses an iframe on the main view to display errors or success.

我的控制器上传功能:

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<用于LOGO_PATH。更改这些(和名称)以适合您的目的。推理是,如果我改变了我想保存图像,我在常量而不是在我的应用程序中的10个地方更改它。

config/constants.php << for the LOGO_PATH. Change these (and the name) to suit your purposes. The reasoning is if I ever change where I want to save images I change it in the constants rather than in 10 places throughout my application.

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

这篇关于图像调整大小,然后在CodeIgniter PHP上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 04:37