2010-04-21 2 views
3

У меня есть скрипт php, который в настоящее время используется, который создает миниатюры на основе максимальной ширины и высоты. Тем не менее, мне бы хотелось, чтобы он всегда создавал квадратные изображения и обрезал изображения при необходимости.Используйте PHP для создания эскизов. (Cropped to square)

Вот что я использую сейчас:

function makeThumb($filename, $type) { 
    global $max_width, $max_height; 
    if ($type == 'jpg') { 
    $src = imagecreatefromjpeg("blocks/img/gallery/" . $filename); 
    } else if ($type == 'png') { 
    $src = imagecreatefrompng("blocks/img/gallery/" . $filename); 
    } else if ($type == 'gif') { 
    $src = imagecreatefromgif("blocks/img/gallery/" . $filename); 
    } 
    if (($oldW = imagesx($src)) < ($oldH = imagesy($src))) { 
    $newW = $oldW * ($max_width/$oldH); 
    $newH = $max_height; 
    } else { 
    $newW = $max_width; 
    $newH = $oldH * ($max_height/$oldW); 
    } 
    $new = imagecreatetruecolor($newW, $newH); 
    imagecopyresampled($new, $src, 0, 0, 0, 0, $newW, $newH, $oldW, $oldH); 
    if ($type == 'jpg') { 
    imagejpeg($new, 'blocks/img/gallery/thumbs/'.$filename); 
    } else if ($type == 'png') { 
    imagepng($new, 'blocks/img/gallery/thumbs/'.$filename); 
    } else if ($type == 'gif') { 
    imagegif($new, 'blocks/img/gallery/thumbs/'.$filename); 
    } 
    imagedestroy($new); 
    imagedestroy($src); 
} 

Как бы я изменить это сделать то, что я хочу (квадратные пальцы)?

Заранее спасибо.

+2

Действительно запах как 'плз-отправить-мне-The-code' вопрос. – Strae

ответ

15
function makeThumb($filename , $thumbSize=100){ 
    global $max_width, $max_height; 
/* Set Filenames */ 
    $srcFile = 'blocks/img/gallery/'.$filename; 
    $thumbFile = 'blocks/img/gallery/thumbs/'.$filename; 
/* Determine the File Type */ 
    $type = substr($filename , strrpos($filename , '.')+1); 
/* Create the Source Image */ 
    switch($type){ 
    case 'jpg' : case 'jpeg' : 
     $src = imagecreatefromjpeg($srcFile); break; 
    case 'png' : 
     $src = imagecreatefrompng($srcFile); break; 
    case 'gif' : 
     $src = imagecreatefromgif($srcFile); break; 
    } 
/* Determine the Image Dimensions */ 
    $oldW = imagesx($src); 
    $oldH = imagesy($src); 
/* Calculate the New Image Dimensions */ 
    if($oldH > $oldW){ 
    /* Portrait */ 
    $newW = $thumbSize; 
    $newH = $oldH * ($thumbSize/$newW); 
    }else{ 
    /* Landscape */ 
    $newH = $thumbSize; 
    $newW = $oldW * ($thumbSize/$newH); 
    } 
/* Create the New Image */ 
    $new = imagecreatetruecolor($thumbSize , $thumbSize); 
/* Transcribe the Source Image into the New (Square) Image */ 
    imagecopyresampled($new , $src , 0 , 0 , ($newW-$thumbSize)/2 , ($newH-$thumbSize)/2 , $thumbSize , $thumbSize , $oldW , $oldH); 
    switch($type){ 
    case 'jpg' : case 'jpeg' : 
     $src = imagejpeg($new , $thumbFile); break; 
    case 'png' : 
     $src = imagepng($new , $thumbFile); break; 
    case 'gif' : 
     $src = imagegif($new , $thumbFile); break; 
    } 
    imagedestroy($new); 
    imagedestroy($src); 
} 
3

Вы хотите выработать смещение, а не новую ширину/высоту, чтобы новый образец находился пропорционально, затем используйте смещение при создании нового изображения и придайте ему фиксированную ширину/высоту, чтобы он обрезал на квадрат. Быстрый пример, что бы сделать 100x100 палец (примечание: непроверенные),

// Get dimensions of the src image. 
list($oldW, $oldH) = getimagesize($filename); 

// Work out what offset to use 
if ($oldH < $oldW) 
{ 
    $offH = 0; 
    $offW = ($oldW-$oldH)/2; 
    $oldW = $oldH; 
} 
elseif ($oldH > $oldW) 
{ 
    $offW = 0; 
    $offH = ($oldH-$oldW)/2; 
    $oldH = $oldW; 
} 
else 
{ 
    $offW = 0; 
    $offH = 0; 
}     

// Resample the image into the new dimensions. 
$new = imagecreatetruecolor(100, 100); 
imagecopyresampled($new, $src, 0, 0, $offW, $offH, 100, 100, $oldW, $oldH); 
+0

Спасибо, Rich! Я очень близко. Большие пальцы теперь квадратные, но все черные. Я думаю, что он почему-то генерирует их за пределами области изображения. – markf

10
/* Calculate the New Image Dimensions */ 
    $limiting_dim = 0; 
    if($oldH > $oldW){ 
    /* Portrait */ 
     $limiting_dim = $oldW; 
    }else{ 
    /* Landscape */ 
     $limiting_dim = $oldH; 
    } 
    /* Create the New Image */ 
    $new = imagecreatetruecolor($thumbSize , $thumbSize); 
    /* Transcribe the Source Image into the New (Square) Image */ 
    imagecopyresampled($new , $src , 0 , 0 , ($oldW-$limiting_dim)/2 , ($oldH-$limiting_dim)/2 , $thumbSize , $thumbSize , $limiting_dim , $limiting_dim); 

не хватает кармы прокомментировать принятый ответ (Lucanos'), но я обнаружил, что ответ выше дал черные полосы на стороне эскиза.

Этот фрагмент кода (в сочетании с принятым ответом) должен скопировать соответствующие разделы изображения src, не выходя из границ и создавая черные полосы. Эскиз по-прежнему квадратный в соответствии с исходным вопросом.

+2

работает для меня. Спасибо! –

+1

Принятый ответ имеет половину изображения черного цвета, но это работает как шарм. – AFgone

0

Эта модифицированная функция работала отлично подходит для меня

public function igImagePrepare($img,$name){ 
    $dir = 'my-images/'; 
    $img_name = $name.'-'.uniqid().'.jpg'; 

    //Your Image 
    $imgSrc = $img; 

    //getting the image dimensions 
    list($width, $height) = getimagesize($imgSrc); 

    //saving the image into memory (for manipulation with GD Library) 
    $myImage = imagecreatefromjpeg($imgSrc); 

    $square_size = 400; 

    $width = imagesx($myImage); 
    $height = imagesy($myImage); 


       //set dimensions 
       if($width> $height) { 
         $width_t=$square_size; 
         //respect the ratio 
         $height_t=round($height/$width*$square_size); 
         //set the offset 
         $off_y=ceil(($width_t-$height_t)/2); 
         $off_x=0; 
       } elseif($height> $width) { 
         $height_t=$square_size; 
         $width_t=round($width/$height*$square_size); 
         $off_x=ceil(($height_t-$width_t)/2); 
         $off_y=0; 
       } 
       else { 
         $width_t=$height_t=$square_size; 
         $off_x=$off_y=0; 
       } 


    /* Create the New Image */ 
    $new = imagecreatetruecolor($square_size , $square_size); 
    /* Transcribe the Source Image into the New (Square) Image */ 
    $bg = imagecolorallocate ($new, 255, 255, 255); 
    imagefill ($new, 0, 0, $bg); 
    imagecopyresampled($new , $myImage , $off_x, $off_y, 0, 0, $width_t, $height_t, $width, $height); 

    //final output 
    imagejpeg($new, $dir.$img_name); 

    return $dir.$img_name; 
    } 
Смежные вопросы