Создать эскиз для отображения ИЛИ Загрузить 50% изображения и создать предварительный просмотр изображения

0

Я загружаю несколько файлов с одним вводом и обработкой, используя приведенный ниже код, как я могу создать изображения с большими формами изображений или загрузить изображение на 50% и создать изображение с низким качеством

    <?php

$newname = md5(rand() * time());
$file1 = isset($_FILES['files']['name'][0]) ? $_FILES['files']['name'][0] : null;
$file2 = isset($_FILES['files']['name'][1]) ? $_FILES['files']['name'][1] : null;
$file3 = isset($_FILES['files']['name'][2]) ? $_FILES['files']['name'][2] : null;
$file4 = isset($_FILES['files']['name'][3]) ? $_FILES['files']['name'][3] : null;
$file5 = isset($_FILES['files']['name'][4]) ? $_FILES['files']['name'][4] : null;
if (isset($_FILES['files'])) {
    $errors = array();
    foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
        $file_name = $key . $_FILES['files']['name'][$key];
        $file_size = $_FILES['files']['size'][$key];
        $file_tmp = $_FILES['files']['tmp_name'][$key];
        $file_type = $_FILES['files']['type'][$key];
        if ($file_size > 2097152) {
            $errors[] = 'File size must be less than 2 MB';
        }
        $desired_dir = "user_data";
        if (empty($errors) == true) {
            if (is_dir($desired_dir) == false) {
                mkdir("$desired_dir", 0700);        // Create directory if it does not exist
            }
            if (is_dir("$desired_dir/" . $file_name) == false) {
                move_uploaded_file($file_tmp, "$desired_dir/" . $newname . $file_name);
            } else {                                  // rename the file if another one exist
                $new_dir = "$desired_dir/" . $newname . $file_name;
                rename($file_tmp, $new_dir);
            }
        } else {
            print_r($errors);
        }
    }
    if (empty($error)) {
        echo "FILE : $file1<br>";
        echo "FILE : $file2<br>";
        echo "FILE : $file3<br>";
        echo "FILE : $file4<br>";
        echo "FILE : $file5<br>";
    }
}
?>

Если изображение загружено с 512 Кб, изображение предварительного просмотра должно загружать меньше, чем размер оригинального файла для предварительного просмотра

Теги:
image
thumbnails

1 ответ

0
Лучший ответ

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

    $orig_directory = "$desired_dir";    //Full image folder
    $thumb_directory = "thumb/";    //Thumbnail folder

    /* Opening the thumbnail directory and looping through all the thumbs: */
    $dir_handle = @opendir($orig_directory); //Open Full image dirrectory
    if ($dir_handle > 1) { //Check to make sure the folder opened
        $allowed_types = array('jpg', 'jpeg', 'gif', 'png');
        $file_type = array();
        $ext = '';
        $title = '';
        $i = 0;

        while ($file_name = @readdir($dir_handle)) {
            /* Skipping the system files: */
            if ($file_name == '.' || $file_name == '..')
                continue;

            $file_type = explode('.', $file_name);    //This gets the file name of the images
            $ext = strtolower(array_pop($file_type));

            /* Using the file name (withouth the extension) as a image title: */
            $title = implode('.', $file_type);
            $title = htmlspecialchars($title);

            /* If the file extension is allowed: */
            if (in_array($ext, $allowed_types)) {

                /* If you would like to inpute images into a database, do your mysql query here */

                /* The code past here is the code at the start of the tutorial */
                /* Outputting each image: */

                $nw = 100;
                $nh = 100;
                $source = "$desired_dir{$file_name}";
                $stype = explode(".", $source);
                $stype = $stype[count($stype) - 1];
                $dest = "thumb/{$file_name}";

                $size = getimagesize($source);
                $w = $size[0];
                $h = $size[1];

                switch ($stype) {
                    case 'gif':
                        $simg = imagecreatefromgif($source);
                        break;
                    case 'jpg':
                        $simg = imagecreatefromjpeg($source);
                        break;
                    case 'png':
                        $simg = imagecreatefrompng($source);
                        break;
                }

                $dimg = resizePreservingAspectRatio($simg, $nw, $nh);
                imagepng($dimg, $dest);
            }
        }

        /* Closing the directory */
        @closedir($dir_handle);
    }
}

function resizePreservingAspectRatio($img, $targetWidth, $targetHeight) {
    $srcWidth = imagesx($img);
    $srcHeight = imagesy($img);

    // Determine new width / height preserving aspect ratio
    $srcRatio = $srcWidth / $srcHeight;
    $targetRatio = $targetWidth / $targetHeight;
    if (($srcWidth <= $targetWidth) && ($srcHeight <= $targetHeight)) {
        $imgTargetWidth = $srcWidth;
        $imgTargetHeight = $srcHeight;
    } else if ($targetRatio > $srcRatio) {
        $imgTargetWidth = (int) ($targetHeight * $srcRatio);
        $imgTargetHeight = $targetHeight;
    } else {
        $imgTargetWidth = $targetWidth;
        $imgTargetHeight = (int) ($targetWidth / $srcRatio);
    }

    // Creating new image with desired size
    $targetImg = imagecreatetruecolor($targetWidth, $targetHeight);

    // Add transparency if your reduced image does not fit with the new size
    $targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
    imagefill($targetImg, 0, 0, $targetTransparent);
    imagecolortransparent($targetImg, $targetTransparent);

    // Copies image, centered to the new one (if it does not fit to it)
    imagecopyresampled($targetImg, $img, 0, 0, 0, 0, $targetWidth, $targetHeight, $srcWidth, $srcHeight);

    return $targetImg;
}

?>
  • 0
    но этот код такой же, как мой код
  • 0
    спасибо это работает

Ещё вопросы

Сообщество Overcoder
Наверх
Меню