Изменение размера изображений с помощью PHP, поддержка PNG, JPG


Я использую этот класс:

class ImgResizer {

function ImgResizer($originalFile = '$newName') {
    $this -> originalFile = $originalFile;
}
function resize($newWidth, $targetFile) {
    if (empty($newWidth) || empty($targetFile)) {
        return false;
    }
    $src = imagecreatefromjpeg($this -> originalFile);
    list($width, $height) = getimagesize($this -> originalFile);
    $newHeight = ($height / $width) * $newWidth;
    $tmp = imagecreatetruecolor($newWidth, $newHeight);
    imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

    if (file_exists($targetFile)) {
        unlink($targetFile);
    }
    imagejpeg($tmp, $targetFile, 95);
}

}

Который отлично работает, но не работает с png, он создает черное изображение с измененным размером.

Есть ли способ настроить этот класс для поддержки изображений png?

Author: nickhar, 2012-11-28

6 answers

function resize($newWidth, $targetFile, $originalFile) {

    $info = getimagesize($originalFile);
    $mime = $info['mime'];

    switch ($mime) {
            case 'image/jpeg':
                    $image_create_func = 'imagecreatefromjpeg';
                    $image_save_func = 'imagejpeg';
                    $new_image_ext = 'jpg';
                    break;

            case 'image/png':
                    $image_create_func = 'imagecreatefrompng';
                    $image_save_func = 'imagepng';
                    $new_image_ext = 'png';
                    break;

            case 'image/gif':
                    $image_create_func = 'imagecreatefromgif';
                    $image_save_func = 'imagegif';
                    $new_image_ext = 'gif';
                    break;

            default: 
                    throw new Exception('Unknown image type.');
    }

    $img = $image_create_func($originalFile);
    list($width, $height) = getimagesize($originalFile);

    $newHeight = ($height / $width) * $newWidth;
    $tmp = imagecreatetruecolor($newWidth, $newHeight);
    imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

    if (file_exists($targetFile)) {
            unlink($targetFile);
    }
    $image_save_func($tmp, "$targetFile.$new_image_ext");
}
 35
Author: P. Galbraith, 2016-02-24 17:13:51

Я знаю, что опаздываю на шоу, но это может помочь другим, кто нуждается в том же самом:

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

    $magicianObj = new imageLib('racecar.jpg');
    $magicianObj -> resizeImage(100, 200);
    $magicianObj -> saveImage('racecar_convertd.png', 100);

Он поддерживает чтение и запись (включая преобразование) следующих форматов

  • jpg
  • png
  • gif
  • bmp

И может читать только

  • psd

Пример

    // Include PHP Image Magician library
    require_once('php_image_magician.php');

    // Open JPG image
    $magicianObj = new imageLib('racecar.jpg');

    // Resize to best fit then crop
    $magicianObj -> resizeImage(100, 200, 'crop');

    // Save resized image as a PNG
    $magicianObj -> saveImage('racecar_small.png');
 9
Author: Jarrod, 2018-02-16 19:05:42

Вы можете попробовать это. В настоящее время предполагается, что изображение всегда будет в формате jpeg. Это позволит вам загрузить jpeg, png или gif. Я еще не проверял, но это должно сработать.

function resize($newWidth, $targetFile) {
    if (empty($newWidth) || empty($targetFile)) {
        return false;
    }

    $fileHandle = @fopen($this->originalFile, 'r');

    //error loading file
    if(!$fileHandle) {
        return false;
    }

    $src = imagecreatefromstring(stream_get_contents($fileHandle));

    fclose($fileHandle);

    //error with loading file as image resource
    if(!$src) {
        return false;
    }

    //get image size from $src handle
    list($width, $height) = array(imagesx($src), imagesy($src));

    $newHeight = ($height / $width) * $newWidth;

    $tmp = imagecreatetruecolor($newWidth, $newHeight);

    imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

    //allow transparency for pngs
    imagealphablending($tmp, false);
    imagesavealpha($tmp, true);

    if (file_exists($targetFile)) {
        unlink($targetFile);
    }

    //handle different image types.
    //imagepng() uses quality 0-9
    switch(strtolower(pathinfo($this->originalFile, PATHINFO_EXTENSION))) {
        case 'jpg':
        case 'jpeg':
            imagejpeg($tmp, $targetFile, 95);
            break;
        case 'png':
            imagepng($tmp, $targetFile, 8.5);
            break;
        case 'gif':
            imagegif($tmp, $targetFile);
            break;
    }

    //destroy image resources
    imagedestroy($tmp);
    imagedestroy($src);
}
 5
Author: Austin Brunkhorst, 2014-02-27 13:47:05

Я взял версию П. Гэлбрейта, исправил ошибки и изменил ее размер по площади (ширина х высота). Для себя я хотел изменить размер изображений, которые слишком велики.

function resizeByArea($originalFile,$targetFile){

    $newArea = 375000; //a little more than 720 x 480

    list($width,$height,$type) = getimagesize($originalFile);
    $area = $width * $height;

if($area > $newArea){

    if($width > $height){ $big = $width; $small = $height; }
    if($width < $height){ $big = $height; $small = $width; }

    $ratio = $big / $small;

    $newSmall = sqrt(($newArea*$small)/$big);
    $newBig = $ratio*$newSmall;

    if($width > $height){ $newWidth = round($newBig, 0); $newHeight = round($newSmall, 0); }
    if($width < $height){ $newWidth = round($newSmall, 0); $newHeight = round($newBig, 0); }

    }

switch ($type) {
    case '2':
            $image_create_func = 'imagecreatefromjpeg';
            $image_save_func = 'imagejpeg';
            $new_image_ext = '.jpg';
            break;

    case '3':
            $image_create_func = 'imagecreatefrompng';
         // $image_save_func = 'imagepng';
         // The quality is too high with "imagepng"
         // but you need it if you want to allow transparency
            $image_save_func = 'imagejpeg';
            $new_image_ext = '.png';
            break;

    case '1':
            $image_create_func = 'imagecreatefromgif';
            $image_save_func = 'imagegif';
            $new_image_ext = '.gif';
            break;

    default: 
            throw Exception('Unknown image type.');
}

    $img = $image_create_func($originalFile);
    $tmp = imagecreatetruecolor($newWidth,$newHeight);
    imagecopyresampled( $tmp, $img, 0, 0, 0, 0,$newWidth,$newHeight, $width, $height );

    ob_start();
    $image_save_func($tmp);
    $i = ob_get_clean();

    // if file exists, create a new one with "1" at the end
    if (file_exists($targetFile.$new_image_ext)){
      $targetFile = $targetFile."1".$new_image_ext;
    }
    else{
      $targetFile = $targetFile.$new_image_ext;
    }

    $fp = fopen ($targetFile,'w');
    fwrite ($fp, $i);
    fclose ($fp);

    unlink($originalFile);
}

Если вы хотите включить прозрачность, проверьте это: http://www.akemapa.com/2008/07/10/php-gd-resize-transparent-image-png-gif/

Я протестировал функцию, она отлично работает!

 1
Author: pmrotule, 2013-03-01 18:13:55

Попробуйте это, и с помощью этого вы также можете сохранить свое изображение по определенному пути.

function resize($file, $imgpath, $width, $height){
    /* Get original image x y*/
    list($w, $h) = getimagesize($file['tmp_name']);
    /* calculate new image size with ratio */
    $ratio = max($width/$w, $height/$h);
    $h = ceil($height / $ratio);
    $x = ($w - $width / $ratio) / 2;
    $w = ceil($width / $ratio);

    /* new file name */
    $path = $imgpath;
    /* read binary data from image file */
    $imgString = file_get_contents($file['tmp_name']);
    /* create image from string */
    $image = imagecreatefromstring($imgString);
    $tmp = imagecreatetruecolor($width, $height);
    imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h);
    /* Save image */
    switch ($file['type']) {
       case 'image/jpeg':
          imagejpeg($tmp, $path, 100);
          break;
       case 'image/png':
          imagepng($tmp, $path, 0);
          break;
       case 'image/gif':
          imagegif($tmp, $path);
          break;
          default:
          //exit;
          break;
        }
     return $path;

     /* cleanup memory */
     imagedestroy($image);
     imagedestroy($tmp);
}

Теперь вам нужно вызвать эту функцию при сохранении изображения как...

<?php

    //$imgpath = "Where you want to save your image";
    resize($_FILES["image"], $imgpath, 340, 340);

?>
 0
Author: Hardik, 2015-02-11 15:02:44

Принятый ответ содержит много ошибок, здесь он исправлен

<?php 




function resize($newWidth, $targetFile, $originalFile) {

    $info = getimagesize($originalFile);
    $mime = $info['mime'];

    switch ($mime) {
            case 'image/jpeg':
                    $image_create_func = 'imagecreatefromjpeg';
                    $image_save_func = 'imagejpeg';
                    $new_image_ext = 'jpg';
                    break;

            case 'image/png':
                    $image_create_func = 'imagecreatefrompng';
                    $image_save_func = 'imagepng';
                    $new_image_ext = 'png';
                    break;

            case 'image/gif':
                    $image_create_func = 'imagecreatefromgif';
                    $image_save_func = 'imagegif';
                    $new_image_ext = 'gif';
                    break;

            default: 
                    throw Exception('Unknown image type.');
    }

    $img = $image_create_func($originalFile);
    list($width, $height) = getimagesize($originalFile);
    $newHeight = ($height / $width) * $newWidth;
    $tmp = imagecreatetruecolor($newWidth, $newHeight);
    imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

    if (file_exists($targetFile)) {
            unlink($targetFile);
    }
    $image_save_func($tmp, "$targetFile.$new_image_ext");
}



$img=$_REQUEST['img'];
$id=$_REQUEST['id'];

  //  echo $img
resize(120, $_SERVER['DOCUMENT_ROOT'] ."/images/$id",$_SERVER['DOCUMENT_ROOT'] ."/images/$img") ;


?>
 -1
Author: bdaz, 2013-12-25 07:00:34