2015-07-11 14 views
6

Ho un metodo per ritagliare un'immagine ma mantiene il rapporto e talvolta mi dà un'immagine oblunga. C'è un modo per fissare larghezza e altezza senza distorcere o distorcere l'immagine? es., 120px x 120px?PHP Image Crop Issue

Qualche idea su come modificare questo metodo per farlo?

Nota: maxSize è impostato su 120px. Inoltre, sto passando la larghezza e l'altezza dall'immagine originale.

protected function calculateSize($width, $height) { 
    if ($width <= $this->maxSize && $height <= $this->maxSize) { 
     $ratio = 1; 
    } elseif ($width > $height) { 
     $ratio = $this->maxSize/$width; 
    } else { 
     $ratio = $this->maxSize/$height; 
    } 

    $this->newWidth = round($width * $ratio); 
    $this->newHeight = round($height * $ratio); 
} 
+0

Ah ... Così si vuole avere un'immagine ritagliata che sia sia oblunga sia quadrata _at allo stesso tempo_? –

+0

@HoboSapiens No, questo metodo restituirà un'immagine oblunga se lo passo un'immagine di 320 x 200 o qualcosa del genere. Voglio che restituisca un'immagine ritagliata uniformemente ad una larghezza e altezza fissa come 120 x 120. –

+0

@HoboSapiens, ho aggiornato la mia domanda. So come avrebbe potuto creare confusione. –

risposta

1

supponendo che si desidera sempre dimensioni quadrate restituiti, e che upscaling non è un'opzione, qualcosa di simile a questo dovrebbe funzionare (a meno che non mi manca qualcosa):

protected function calculateSize($width, $height) { 
    if ($height <= $this->maxSize && $width <= $this->maxSize) { 
    $new_height = $new_width = min(array($height, $width)); 
    } 
    else { 
    if ($height > $width) { 
     $variable = 'width'; 
    } 
    else { 
     $variable = 'height'; 
    } 
    if ($$variable <= $this->maxSize) { 
     $new_height = $new_width = $$variable; 
    } 
    else { 
     $new_height = $new_width = min(array($this->maxSize, $$variable)); 
    } 
    } 
    $this->newWidth = $new_width; 
    $this->newHeight = $new_height; 
}