2015-04-16 4 views
1

Я использую класс plupload на моем сайте. Я загружаю работу. Однако, когда я загружаю один файл, я хочу создать несколько разрешений для этого файла. Я попытался с помощью javascript ниже: пытаясь сделать эту клиентскую сторону, а затем загружать изображения, ускоряет работу. Однако я открыт для изменения размера загруженных изображений на сервере.plupload multiple resize размер клиента

Моя попытка:

$(function() { 
    $('#html5_uploader_" . $a1 . "').pluploadQueue({ 
     // General settings 
     runtimes : 'html5', 
     url : 'http://domain.com.au/fileuploader', 

     filters : { 
      max_file_size : '1024mb', 
      mime_types: [ 
       {title : 'Image files', extensions : 'jpg,gif,png'} 
      ] 
     }, 

     // Resize images on clientside if we can 
     resize : {width : 800, height : 600, quality : 90} 
    }); 
}); 

ответ

0

Вот небольшой набор функций, которые позволяют обрабатывать и создавать эскизы легко в PHP. если изображение представляет собой прямоугольник, он срезается центром и обрезается соответствующим образом.

функция подписи

function square_thumbs(string $input_name,array $data_source, array $sizes,int $min_width,$int $min_height) 

Возвращаемое значение

возвращает массив имен файлов для создаваемых миниатюр в одном порядке, как $ размеры массивов

Пример использования

list($small,$medium,$large) = square_thumbs('image_file',$_FILES,[60,150,300],120,120); 

полный код

function square_thumbs($img_name,$files,$sizes = [60,220,800],$min_width=120,$min_height=120) 
{ 
    if(empty($files) || !isset($files[$img_name])){ 
     throw new \exception('You must select an image!'); 
    } 
    if($files[$img_name]['error']) 
    { 
     throw new exception(upload_errors($files[$img_name]['error'])); 
    } 
    $image_temp = $files[$img_name]['tmp_name']; 
    @$image_info = getimagesize($image_temp); 
    $exif = [IMAGETYPE_GIF,IMAGETYPE_JPEG,IMAGETYPE_PNG]; 
    $finfo = ['image/gif','image/png','image/jpeg','image/pjpeg']; 
    $etype = exif_imagetype($image_temp); 
    if(!function_exists('finfo_file')){ 
     throw new exception('Unable to determine image mime type.'); 
    } 
    $type = finfo_file(finfo_open(FILEINFO_MIME_TYPE),$image_temp); 
    if(!is_uploaded_file($files[$img_name]['tmp_name'])){ 
     throw new exception('bad file input'); 
    } 
    if(!in_array($etype,$exif) || !in_array($type,$finfo)){ 
     throw new exception('file type not allowed'); 
    } 
    switch($type){ 
     case 'image/gif': 
      $type2 = 'gif'; 
     break; 
     case 'image/png': 
      $type2 = 'png'; 
     break; 
     case 'image/jpeg': 
     case 'image/jpg': 
     case 'image/pjpeg': 
      $type2 = 'jpg'; 
     break; 
    } 
    if(!$image_info){ 
     throw new exception('invalid image size.'); 
    } 

    //get the image resource 
    $image = imagecreatefromstring(file_get_contents($image_temp)); 
    $width = $image_info[0]; 
    $height = $image_info[1]; 


    if($width < $min_width || $height < $min_height){ 
     throw new exception('Images must be atleast '.$min_width.' x '.$min_height.' in size.'); 
    } 

    //ill admit this code is smelly, but do you have a better idea? lol 
    if($width != $height){ 
     list($size,$image) = square_img($image,$width,$height); 
     $width = $height = $size; 
    } 
    $size = $width; 

    //now we have a square image and our image size is updated to reflect this change. 
    $res = []; 
    foreach($sizes as $z) 
    { 
     $t = imagecreatetruecolor($z,$z); 
     ob_start(); 
     switch($type){ 
      case 'image/gif': 
       imagecopyresampled($t,$image,0,0,0,0,$z,$z,$size,$size); 
       imagegif($t); 
      break; 
      case 'image/png': 
       imagesavealpha($t, true); 
       $trans_colour = imagecolorallocatealpha($t, 0, 0, 0, 127); 
       imagefill($t, 0, 0, $trans_colour); 
       imagecopyresampled($t,$image,0,0,0,0,$z,$z,$size,$size); 
       imagepng($t,NULL,2); //lossless compression minimal (default is 6) 
      break; 
      case 'image/jpeg': 
      case 'image/jpg': 
      case 'image/pjpeg': 
       imagecopyresampled($t,$image,0,0,0,0,$z,$z,$size,$size); 
       imagejpeg($t,NULL,100); //100% quality (default is 75%) 
      break; 
     } 
     $result_image = ob_get_clean(); //stores the image content as string. 
     $file_name = md5($result_image).'.'.$type2; //we can create a random distinct file name by md5ing the data and appending the file extension which is stored in $type2 variable. 
     $res[] = store_image($result_image,$file_name); //store name of the resultant file in result array 
    } 
    return $res; //after all the thumbs have been generated, return them all in an array. 
} 

//calculates the nearest square size of the image 
function square_img($image,$width,$height) 
{ 
    //horizontal rectangle 
    if ($width > $height) { 
     $square = $height;    // $square: square side length 
     $offsetX = ($width - $height)/2; // x offset based on the rectangle 
     $offsetY = 0;    // y offset based on the rectangle 
    } 
    // vertical rectangle 
    elseif ($height > $width) { 
     $square = $width; 
     $offsetX = 0; 
     $offsetY = ($height - $width)/2; 
    } 
    $t = imagecreatetruecolor($square,$square); 
    imagecopyresampled($t, $image, 0, 0, $offsetX, $offsetY, $square, $square, $square, $square); 
    return [$square,$t]; 
} 


//handle some common upload errors 
function upload_errors($err_code) { 
    switch ($err_code) { 
     case UPLOAD_ERR_INI_SIZE: 
      return 'The uploaded file exceeds the upload_max_filesize directive in php.ini'; 
     case UPLOAD_ERR_FORM_SIZE: 
      return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'; 
     case UPLOAD_ERR_PARTIAL: 
      return 'The uploaded file was only partially uploaded'; 
     case UPLOAD_ERR_NO_FILE: 
      return 'No file was uploaded'; 
     case UPLOAD_ERR_NO_TMP_DIR: 
      return 'Missing a temporary folder'; 
     case UPLOAD_ERR_CANT_WRITE: 
      return 'Failed to write file to disk'; 
     case UPLOAD_ERR_EXTENSION: 
      return 'File upload stopped by extension'; 
     default: 
      return 'Unknown upload error'; 
    } 
} 


//stores the resultant image. 
function store_image($image_data,$file_name,$path='') 
{ 
    //this is just a basic implementation of storing some data into a file. 
    $t = fopen($path.$file_name,'w+'); 
    fwrite($t,$image_data); 
    fclose($t); 
    return $file_name; 
}