php – Tell me a script for cropping an image automatically (on page load)?

Question:

Example – there is a 1000×1000 image in the image directory, you need to crop it to 800×400 and place it in the image_crop folder.

Trimming should go through the system – reduce the width to 800 (becomes 800×800) and then cut 200 from the bottom and top to make 800×400

Help with example code or links to ready-made solutions.

Answer:

Something like this (not tested):

<?php

/**
 * имя запрошенного файла в GET-параметре image:
 * script.php?image=apple.jpg
 */

define( 'IMG_SRC_PATH', '/var/www/mysite/image');
define( 'IMG_CROPPED_PATH', '/var/www/mysite/image_crop');

$filename = $_GET['image']; // TODO: проверить на существование, непустоту, очистить от "../.." и спецсимволов

$srcFile = IMG_SRC_PATH . '/' . $filename;
$dstFile = IMG_CROPPED_PATH . '/' . $filename;

if( file_exists( $dstFile)) {
    // уже есть переделанная картинка, отдаём её
    header('Content-type: image/jpeg');
    readfile( $dstFile);
    exit();
}

if(!file_exists( $srcFile)) {
    header('Not found', true, 404);
    echo "File not found: " . htmlspecialchars( $srcFile);
    exit();
}

list( $width, $height, $type, $attr) = getimagesize( $srcFile);


switch( $type) {
    case IMAGETYPE_GIF:
        $imagedata = imagecreatefromgif( $srcFile);
        break;
    case IMAGETYPE_JPEG:
    case IMAGETYPE_JPEG2000:
        $imagedata = imagecreatefromjpeg( $srcFile);
        break;
    case IMAGETYPE_PNG:
        $imagedata = imagecreatefrompng( $srcFile);
        break;
    default:
        $imagedata = false;
}

if( false === $imagedata) {
    header('Bad image type', true, 500);
    echo "Image type not supported: " . $type;
    exit();
}

// Resize the image
$thumbW = 800;
$thumbH = 400;
$proportion = $thumbW / $thumbH;
$k = $width / $height;

$thumbdata = imagecreatetruecolor( $thumbW, $thumbH);
imagefill( $thumbdata, 0, 0, 0xFFFFFF);

if( $k > $proportion) {
    // fit height, crop on left/right sides
    $scale = $thumbH / $height;

    $srcW = $height * $proportion;
    $srcH = $height;

    $srcX = ( $width - $thumbW / $scale) / 2;
    $srcY = 0;
} else {
    // fit width, crop on top/bottom
    $scale = $thumbW / $width;

    $srcW = $width;
    $srcH = $height / $proportion;

    $srcX = 0;
    $srcY = ( $height - $thumbH / $scale) / 2;
}

imagecopyresampled( $thumbdata, $imagedata, 0, 0, $srcX, $srcY, $thumbW, $thumbH, $srcW, $srcH);

imagejpeg( $thumbdata, $dstFile);

header('Content-type: image/jpeg');
readfile( $dstFile);
Scroll to Top