Scale Image Using PHP and Maintaining Aspect Ratio

2019-01-07 19:34发布

Basically I want to upload an image (which i've sorted) and scale it down to certain constraints such as max width and height but maintain the aspect ratio of the original image.

I don't have Imagick installed on the server - otherwise this would be easy.

Any help is appreciated as always. Thanks.

EDIT: I don't need the whole code or anything, just a push in the right direction would be fantastic.

标签: php image scale
9条回答
劳资没心,怎么记你
2楼-- · 2019-01-07 20:30

Formule is wrong for keeping aspect ratio. It should be: original height / original width x new width = new height

function createThumbnail($imageName,$newWidth,$newHeight,$uploadDir,$moveToDir)
{
    $path = $uploadDir . '/' . $imageName;

    $mime = getimagesize($path);

    if($mime['mime']=='image/png'){ $src_img = imagecreatefrompng($path); }
    if($mime['mime']=='image/jpg'){ $src_img = imagecreatefromjpeg($path); }
    if($mime['mime']=='image/jpeg'){ $src_img = imagecreatefromjpeg($path); }
    if($mime['mime']=='image/pjpeg'){ $src_img = imagecreatefromjpeg($path); }

    $old_x = imageSX($src_img);
    $old_y = imageSY($src_img);

    if($old_x > $old_y)
    {
        $thumb_w    =   $newWidth;
        $thumb_h    =   $old_y/$old_x*$newWidth;
    }

    if($old_x < $old_y)
    {
        $thumb_w    =   $old_x/$old_y*$newHeight;
        $thumb_h    =   $newHeight;
    }

    if($old_x == $old_y)
    {
        $thumb_w    =   $newWidth;
        $thumb_h    =   $newHeight;
    }

    $dst_img        =   ImageCreateTrueColor($thumb_w,$thumb_h);

    imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);


    // New save location
    $new_thumb_loc = $moveToDir . $imageName;

    if($mime['mime']=='image/png'){ $result = imagepng($dst_img,$new_thumb_loc,8); }
    if($mime['mime']=='image/jpg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }
    if($mime['mime']=='image/jpeg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }
    if($mime['mime']=='image/pjpeg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }

    imagedestroy($dst_img);
    imagedestroy($src_img);
    return $result;
}
查看更多
男人必须洒脱
3楼-- · 2019-01-07 20:33

works perfecly for me

    static function getThumpnail($file){

    $THUMBNAIL_IMAGE_MAX_WIDTH  = 150; # exmpl.
    $THUMBNAIL_IMAGE_MAX_HEIGHT = 150;

    $src_size = filesize($file);
    $filename = basename($file);

    list($src_width, $src_height, $src_type) = getimagesize($file);
    $src_im = false;
    switch ($src_type) {
        case IMAGETYPE_GIF  : $src_im = imageCreateFromGif($file);  break;
        case IMAGETYPE_JPEG : $src_im = imageCreateFromJpeg($file); break;
        case IMAGETYPE_PNG  : $src_im = imageCreateFromPng($file);  break;
        case IMAGETYPE_WBMP  : $src_im = imagecreatefromwbmp($file);  break;
    }   
    if ($src_im === false) { return false; }

    $src_aspect_ratio = $src_width / $src_height;
    $thu_aspect_ratio = $THUMBNAIL_IMAGE_MAX_WIDTH / $THUMBNAIL_IMAGE_MAX_HEIGHT;

    if ($src_width <= $THUMBNAIL_IMAGE_MAX_WIDTH && $src_height <= $THUMBNAIL_IMAGE_MAX_HEIGHT) {
        $thu_width  = $src_width;
        $thu_height = $src_height;
    } elseif ($thu_aspect_ratio > $src_aspect_ratio) {
        $thu_width  = (int) ($THUMBNAIL_IMAGE_MAX_HEIGHT * $src_aspect_ratio);
        $thu_height = $THUMBNAIL_IMAGE_MAX_HEIGHT;
    } else {
        $thu_width = $THUMBNAIL_IMAGE_MAX_WIDTH;
        $thu_height = (int) ($THUMBNAIL_IMAGE_MAX_WIDTH / $src_aspect_ratio);
    }

    $thu_im = imagecreatetruecolor($thu_width, $thu_height);
    imagecopyresampled($thu_im, $src_im, 0, 0, 0, 0, $thu_width, $thu_height, $src_width, $src_height);

    $dst_im    = imagecreatetruecolor($THUMBNAIL_IMAGE_MAX_WIDTH,$THUMBNAIL_IMAGE_MAX_WIDTH);
    $backcolor = imagecolorallocate($dst_im,192,192,192);
    imagefill($dst_im,0,0,$backcolor);
    imagecopy($dst_im, $thu_im, (imagesx($dst_im)/2)-(imagesx($thu_im)/2), (imagesy($dst_im)/2)-(imagesy($thu_im)/2), 0, 0, imagesx($thu_im), imagesy($thu_im));
    imagedestroy($src_im);
    imagedestroy($thu_im);
    }
查看更多
狗以群分
4楼-- · 2019-01-07 20:38

Here is a comprehensive application that I worked hard on it to include most common operations like scale up & scale down, thumbnail, preserve aspect ratio, convert file type, change quality/file size and more...

<?php
//##// Resize (and convert) image (Scale up & scale down, thumbnail, preserve aspect ratio) //##//
///////////////////////////////////////////////
///////////////// Begin.Setup /////////////////
// Source File:
$src_file = "/your/server/path/to/file.png";// png or jpg files only

// Resize Dimensions:
// leave blank for no size change (convert only)
// if you specify one dimension, the other dimension will be calculated according to the aspect ratio
// if you specify both dimensions system will take care of it depending on the actual image size 
// $newWidth = 2000;
// $newHeight = 1500;

// Destination Path: (optional, if none: download image)
$dst_path = "/your/server/path/new/";

// Destination File Name: (Leave blank for same file name)
// $dst_name = 'image_name_only_no_extension';

// Destination File Type: (Leave blank for same file extension)
// $dst_type = 'png';
$dst_type = 'jpg';

// Reduce to 8bit - 256 colors (Very low quality but very small file & transparent PNG. Only for thumbnails!)
// $palette_8bit = true;

///////////////// End.Setup /////////////////
///////////////////////////////////////////////
if (!$dst_name){$dst_name = strtolower(pathinfo($src_file, PATHINFO_FILENAME));}
if (!$dst_type){$dst_type = strtolower(pathinfo($src_file, PATHINFO_EXTENSION));}
if ($palette_8bit){$dst_type = 'png';}
if ($dst_path){$dst_file = $dst_path . $dst_name . '.' . $dst_type;}

$mime = getimagesize($src_file);// Get image dimensions and type

// Destination File Parameters:
if ($dst_type == 'png'){
    $dst_content = 'image/png';
    $quality = 9;// All same quality! 0 too big file // 0(no comp.)-9 (php default: 6)
} elseif ($dst_type == 'jpg'){
    $dst_content = 'image/jpg';
    $quality = 85;// 30 Min. 60 Mid. 85 Cool. 90 Max. (100 Full) // 0-100 (php default: 75)
} else {
    exit('Unknown Destination File Type');
}

// Source File Parameters:
if ($mime['mime']=='image/png'){$src_img = imagecreatefrompng($src_file);}
elseif ($mime['mime']=='image/jpg'){$src_img = imagecreatefromjpeg($src_file);}
elseif ($mime['mime']=='image/jpeg'){$src_img = imagecreatefromjpeg($src_file);}
elseif ($mime['mime']=='image/pjpeg'){$src_img = imagecreatefromjpeg($src_file);}
else {exit('Unknown Source File Type');}

// Define Dimensions:
$old_x = imageSX($src_img);
$old_y = imageSY($src_img);

if ($newWidth AND $newHeight){
    if($old_x > $old_y){
        $new_x    =   $newWidth;
        $new_y    =   $old_y / $old_x * $newWidth;
    } elseif($old_x < $old_y){
        $new_y    =   $newHeight;
        $new_x    =   $old_x / $old_y * $newHeight;
    } elseif($old_x == $old_y){
        $new_x    =   $newWidth;
        $new_y    =   $newHeight;
    }
} elseif ($newWidth){
    $new_x    =   $newWidth;
    $new_y    =   $old_y / $old_x * $newWidth;
} elseif ($newHeight){
    $new_y    =   $newHeight;
    $new_x    =   $old_x / $old_y * $newHeight;
} else {
    $new_x    =   $old_x;
    $new_y    =   $old_y;
}

$dst_img = ImageCreateTrueColor($new_x, $new_y);

if ($palette_8bit){//////// Reduce to 8bit - 256 colors ////////
    $transparent = imagecolorallocatealpha($dst_img, 255, 255, 255, 127); 
    imagecolortransparent($dst_img, $transparent);
    imagefill($dst_img, 0, 0, $transparent);
    imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_x,$new_y,$old_x,$old_y);// Great quality resize.
    imagetruecolortopalette($dst_img, false, 255);
    imagesavealpha($dst_img, true);
} else {
    // Check image and set transparent for png or white background for jpg
    if ($dst_type == 'png'){
        imagealphablending($dst_img, false);
        imagesavealpha($dst_img, true);
        $transparent = imagecolorallocatealpha($dst_img, 255, 255, 255, 127);
        imagefilledrectangle($dst_img, 0, 0, $new_x, $new_y, $transparent);
    } elseif ($dst_type == 'jpg'){
        $white = imagecolorallocate($dst_img, 255, 255, 255);
        imagefilledrectangle($dst_img, 0, 0, $new_x, $new_y, $white);
    }

    imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_x,$new_y,$old_x,$old_y);// Great quality resize.
}

// Skip the save to parameter using NULL, then set the quality; imagejpeg($dst_img);=> Default quality
if ($dst_file){
    if ($dst_type == 'png'){
        imagepng($dst_img, $dst_file, $quality);
    } elseif ($dst_type == 'jpg'){
        imagejpeg($dst_img, $dst_file, $quality);
    }
} else {
    header('Content-Disposition: Attachment;filename=' . $dst_name . '.' . $dst_type);// comment this line to show image in browser instead of download
    header('Content-type: ' . $dst_content);
    if ($dst_type == 'png'){
        imagepng($dst_img, NULL, $quality);
    } elseif ($dst_type == 'jpg'){
        imagejpeg($dst_img, NULL, $quality);
    }
}
imagedestroy($src_img);
imagedestroy($dst_img);
//##// END : Resize image (Scale Up & Down) (thumbnail, bigger image, preserve aspect ratio) END //##//
查看更多
登录 后发表回答