O
O
oneonepro2016-03-20 01:48:04
PHP
oneonepro, 2016-03-20 01:48:04

How to load image in php ajax iframe with size reduction?

<?php	// work.php
header("Content-Type:text/html;charset=UTF-8"); // Кодирока

if ($_SERVER['REQUEST_METHOD'] == 'POST'){
  if ($_FILES['picture']){
      
      $path = 'images/';
      $tmp_path = 'tmp/';		
      $types = array('image/gif', 'image/png', 'image/jpeg');			
      $size = 6024000;
      $timedate = time().rand(100,999); 

      function resize($file, $type = 2, $rotate = null, $quality = null)
      {
        global $tmp_path;
        
        // Ограничение по ширине в пикселях
        $max_width_size = 800;
        $max_height_size = 650;		
      
        // Качество изображения по умолчанию
        if ($quality == null)
          $quality = 100;

        // Cоздаём исходное изображение на основе исходного файла
        if ($file['type'] == 'image/jpeg')
          $source = imagecreatefromjpeg($file['tmp_name']);
        elseif ($file['type'] == 'image/png')
          $source = imagecreatefrompng($file['tmp_name']);
        elseif ($file['type'] == 'image/gif')
          $source = imagecreatefromgif($file['tmp_name']);
        else
          return false;
          
        // Поворачиваем изображение
        if ($rotate != null)
          $src = imagerotate($source, $rotate, 0);
        else
          $src = $source;

        // Определяем ширину и высоту изображения
        $w_src = imagesx($src); 
        $h_src = imagesy($src);

        //  Если большое изображение устанавливаем ограничение по ширине.
        if ($type == 2)
          $w = $max_width_size;
                      
            // Если большое изображение устанавливаем ограничение по высоте.
        if ($type == 2)
          $h = $max_height_size;
          

        // Если ширина больше заданной
        if ($h_src > $h)
        {
          // Вычисление пропорций
          $ratio = $h_src/$h;
          $w_dest = @round($w_src/$ratio);
          $h_dest = @round($h_src/$ratio);

          // Создаём пустую картинку
          $dest = @imagecreatetruecolor($w_dest, $h_dest);
          
          // Копируем старое изображение в новое с изменением параметров
          @imagecopyresampled($dest, $src, 0, 0, 0, 0, $w_dest, $h_dest, $w_src, $h_src);

          // Вывод картинки и очистка памяти
          @imagejpeg($dest, $tmp_path . $file['name'], $quality);
          
          @imagedestroy($dest);
          @imagedestroy($src);

          return $file['name'];
          
        } else {
          // Вывод картинки и очистка памяти
          @imagejpeg($src, $tmp_path . $file['name'], $quality);
          @imagedestroy($src);

          return $file['name'];
        }
      }
        
      $name = resize($_FILES['picture'], $_POST['file_type'], $_POST['file_rotate']);

      // Загрузка файла и вывод сообщения
      if ([email protected]($tmp_path . $name, $path . $name)){
        echo '';
      } else {						
        echo '<script> window.top.work("' . $path . $_FILES['picture']['name'] . '"); </script>';
        }
        
      unlink($tmp_path . $name);
  }
}
?>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
seriogja, 2016-03-21
@seriogja

I think few people will be interested in understanding your "sheet". Moreover, you didn't even bother to describe the essence of your problem normally... In general, ajax is what ajax is for, so that you can do everything without iframes.

O
oneonepro, 2016-03-21
@oneonepro

The point is that ajax does not allow uploading images to the server. There is a way through iframe. The method is working and suits me. The image is uploaded to the server, but I would also like to add a reduction in the size of the uploaded image. For example: if the image is more than 1000px wide, then it is proportionally reduced to 900px wide for example. below is the form code and jquery code.

<div id="fullsize">
  <form method="post" enctype="multipart/form-data" action="work.php" target="imgframe" id="upload">
     <input style="display: none;" type="file" id="picture" 
     required="required" accept="image" name="picture" onchange="document.getElementById('upload').submit()">
     <div id="trigger">выбрать</div>
  </form>
  <img id="image" src="" />
  <iframe style="visibility: hidden; display: none;" id="imgframe" name="imgframe">
  </iframe>	
</div>

function work(obj) {
    $("#image").attr("src", obj);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question