2016-02-01 3 views
1

Я пытаюсь обрезать и изменять размер изображений. Когда изображения перемещаются в папку resized_images, все изображения становятся черными, но изображения изменяются (535 * 313). Вот мой код, который я пробовал до сих пор. Не могли бы вы предложить мне правильный способ сделать это? поблагодарить уОбрезать и изменить размер изображений в php

<form action="" method="POST" enctype="multipart/form-data"> 
 
<input id="input-6" name="slideshow_images[]" type="file" multiple class="file-loading"> 
 
<input type="submit" name="sub" > 
 
</form> 
 
<?php 
 
if(isset($_POST['sub'])) 
 
{ 
 
$pic = $_FILES["slideshow_images"]["name"]; \t 
 
foreach($pic as $pic_src) 
 
{ \t 
 
    
 
$image = imagecreatefromjpeg($pic_src); 
 
$filename = 'resized_images/'.$pic_src.'cropped_whatever.jpeg'; 
 

 
$thumb_width = 535; 
 

 
$thumb_height = 313; 
 

 
$width = imagesx($image); 
 
$height = imagesy($image); 
 
    \t 
 
$original_aspect = $width/$height; 
 
$thumb_aspect = $thumb_width/$thumb_height; 
 
    
 
if ($original_aspect >= $thumb_aspect) 
 
{ 
 
    // If image is wider than thumbnail (in aspect ratio sense) 
 
    $new_height = $thumb_height; 
 
    $new_width = $width/($height/$thumb_height); 
 
} 
 
else 
 
{ 
 
    // If the thumbnail is wider than the image 
 
    $new_width = $thumb_width; 
 
    \t 
 
    $new_height = $height/($width/$thumb_width); 
 

 
    
 
    
 
} 
 

 
$thumb = imagecreatetruecolor($thumb_width, $thumb_height); 
 

 
// Resize and crop 
 
imagecopyresampled($thumb, 
 
        $image, 
 
        0 - ($new_width - $thumb_width)/2, // Center the image horizontally 
 
        0 - ($new_height - $thumb_height)/2, // Center the image vertically 
 
        0, 0, 
 
        $new_width, $new_height, 
 
        $width, $height); 
 
imagejpeg($thumb, $filename, 80); 
 
} 
 

 
} 
 
    ?>

ответ

1

Я просто столкнулся с этой проблемой. Проблема в том, что цвет фона черный и полностью прозрачный. То, что вам нужно сделать, - просто выделить истинный цвет (например, белый) с альфой и сделать альфа полностью непрозрачным. Затем просто сделайте заполненный прямоугольник над новой областью сначала, и ваше изображение должно появиться. :-)

Ниже непосредственно из PHP документации о imagecopy:

// create new image with padding 
$img = imagecreatetruecolor($right-$left+$padding*2,$bottom-$top+$padding*2); 
// Allocate background color 
$white = imagecolorallocatealpha($img, 255, 255, 255, 0); 
// fill the background 
imagefill($img, 0, 0, $white); 
// or use 
imagefilledrectangle($img, 0,0,$width,$height, $white); 
// copy 
imagecopy($img, $image, $padding, $padding, $left, $top, $right-$left, $bottom-$top); 

Обратите внимание, что они делают imagefill с цветом фона перед копированием на самом деле новый образ. Это то же самое для imagecopyresample.

Ну, в отличие от предыдущих - на этот раз я не получил черное изображение. Поэтому проверьте, что вы делаете, против следующего: на самом деле загрузите следующее и запустите его (вместе с изображением test.jpg). Посмотрите, работает ли это для вас. Обратите внимание, что это прямо из веб-сайта документации PHP для imagecopyresample.

<?php 
// The file 
$filename = './test.jpg'; 
$percent = 0.5; 

// Content type 
header('Content-Type: image/jpeg'); 

// Get new dimensions 
list($width, $height) = getimagesize($filename); 
$new_width = $width * $percent; 
$new_height = $height * $percent; 

// Resample 
$image_p = imagecreatetruecolor($new_width, $new_height); 
$image = imagecreatefromjpeg($filename); 
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 

// Output 
imagejpeg($image_p, "new.jpg", 100); 
?> 

А вот изображение:

enter image description here

А вот выход: enter image description here

+0

Где следует Я выделяю true color.please ответ – silent

+0

Прежде чем вы выполните imagecopyresample и imagefill или imagefilledrectangle. В противном случае это не очень хорошо. :-) Модифицированный ответ. –

+0

Я не хочу, чтобы заполнить новый цвет, просто я хочу отображать те же изображения, что я загрузил. Возможно ли это? – silent

2

Измените код строки:

$pic = $_FILES["slideshow_images"]["tmp_name"]; 

$image = imagecreatefromstring(file_get_contents(($pic_src))); 

Поскольку [» имя "] всего 123.jpg, это не о ▪ Таблица.

Лучший способ будет что:

<form action="" method="POST" enctype="multipart/form-data"> 
<input id="input-6" name="slideshow_images[]" type="file" multiple class="file-loading"> 
<input type="submit" name="sub" > 
</form> 
<?php 
if(isset($_POST['sub'])){ 
    if(isset($_FILES['slideshow_images'])){ 
    foreach ($_FILES["slideshow_images"]["error"] as $key => $error) { 
     if ($error == UPLOAD_ERR_OK) { 
     $tmp_name = $_FILES["slideshow_images"]["tmp_name"][$key]; 
     $name = $_FILES["slideshow_images"]["name"][$key]; 
      $image = imagecreatefromstring(file_get_contents(($tmp_name))); 
      $filename = 'images/'.$name.'cropped_whatever.jpg'; 
      $thumb_width = 535; 

      $thumb_height = 313; 

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

      $original_aspect = $width/$height; 
      $thumb_aspect = $thumb_width/$thumb_height; 

      if ($original_aspect >= $thumb_aspect) 
      { 
      // If image is wider than thumbnail (in aspect ratio sense) 
      $new_height = $thumb_height; 
      $new_width = $width/($height/$thumb_height); 
      } 
      else 
      { 
      // If the thumbnail is wider than the image 
      $new_width = $thumb_width; 

      $new_height = $height/($width/$thumb_width); 



      } 

      $thumb = imagecreatetruecolor($thumb_width, $thumb_height); 

      // Resize and crop 
      imagecopyresampled($thumb, 
          $image, 
          0 - ($new_width - $thumb_width)/2, // Center the image horizontally 
          0 - ($new_height - $thumb_height)/2, // Center the image vertically 
          0, 0, 
          $new_width, $new_height, 
          $width, $height); 
      imagejpeg($thumb, $filename, 80); 
     } 
    } 
    } 
} 
    ?> 

Кроме того, если вы не хотите, чтобы добавить «.jpg» в имени файла, заменить $ имя_файла строку следующим образом:

$filename = 'images/'.preg_replace('/\.[^.]*$/', '', $name).'cropped_whatever.jpg'; 
+0

Я сделал вышеуказанные изменения, но изображения не перемещаются в папку – silent

+0

@Salman: Вы действительно имели в виду, что изображения НЕ перемещаются в папку? Кроме того, посмотрите http://www.w3schools.com/php/php_file_upload.asp. у него есть некоторые вещи, о которых вы могли бы подумать. :-) –

+0

, потому что теперь $ pic_src содержит путь к файлу, а не имя. Вы не можете использовать переменную $ pic_src в имени файла или просто проанализировать весь массив $ _FILES и после этого использовать ключи для выбора пути, имя_файла – AlexIL

Смежные вопросы