2013-11-01 5 views
0

Я использую функцию для изменения размера изображений.Изменение размера изображения дано

Большинство изображений очень сильно изменено. , но кто-то, я не понимаю, почему они только черные. одинаковое изображение всегда дает черный результат. Может быть, это тот тип Jpeg, который дает это ... но как его изменить?

Спасибо!

function create_image($file) { 
    if(is_file($file)) { 
     $size = getimagesize($file); 
     // y =hauteur en pixel 
     $y = 800; 
     $x = $size[0]/$size[1]*$y; 
     //$y = 75; # Taille en pixel de l'image redimensionnée 
     if ($size) { 
      if ($size['mime']=='image/jpeg') { 
       $img_big = imagecreatefromjpeg($file); 
       $img_new = imagecreate($x, $y); 
       # création de la miniature 
       $img_mini = imagecreatetruecolor($x, $y) 
       or $img_mini = imagecreate($x, $y); 

       // copie de l'image, avec le redimensionnement. 
       imagecopyresized($img_mini,$img_big,0,0,0,0,$x,$y,$size[0],$size[1]); 

       imagejpeg($img_mini,$file); 

      } 
      elseif ($size['mime']=='image/png') { 
       $img_big = imagecreatefrompng($file); 
       $img_new = imagecreate($x, $y); 
       # création de la miniature 
       $img_mini = imagecreatetruecolor($x, $y) 
       or $img_mini = imagecreate($x, $y); 

       // copie de l'image, avec le redimensionnement. 
       imagecopyresized($img_mini,$img_big,0,0,0,0,$x,$y,$size[0],$size[1]); 

       imagepng($img_mini,$file); 

      } 
      elseif ($size['mime']=='image/gif') { 
       $img_big = imagecreatefromgif($file); 
       $img_new = imagecreate($x, $y); 
       # création de la miniature 
       $img_mini = imagecreatetruecolor($x, $y) 
       or $img_mini = imagecreate($x, $y); 

       // copie de l'image, avec le redimensionnement. 
       imagecopyresized($img_mini,$img_big,0,0,0,0,$x,$y,$size[0],$size[1]); 

       imagegif($img_mini,$file); 
      } 
      // move_uploaded_file($img_mini,$dir."test"); 
     } 
     return true; 
    } else { 
     return false; 
    } 
} 

EDIT: Спасибо!

Оптимизация хороша ...

Но результат тот же с изображениями, как: http://www.ericae.fr/test_images/Ripper.jpg изменении размеров отдавания: http://www.ericae.fr/test_images/resized.jpg Все черные :(

С другими изображениями результат хороший! !! Я тестировал около 25 изображений только 2 проблемы ... ПОЧЕМУ?

ответ

0
Я решил просмотреть ваш код. o это один раз? Также я рекомендую использовать imagecopyresampled вместо imagecopyresized, это даст вам лучший результат без черных экранов. Посмотрите на это, я заметил что-то, что я изменил для вас:

function create_image($file) 
{ 
    if(is_file($file)) 
    { 
     $size = getimagesize($file); 

     if ($size) 
     { 
      $y = 800; 
      $x = $size[0]/$size[1]*$y; 
      $mime = $size['mime']; 

      // Detect image format and create a GD resource 
      switch ($mime) 
      { 
       case 'image/jpeg' : $img_big = imagecreatefromjpeg($file); break; 
       case 'image/png' : $img_big = imagecreatefrompng($file); break; 
       case 'image/gif' : $img_big = imagecreatefromgif($file); break; 
       // Wrong type - exiting 
       default: return false; 
      } 

      // Create a new image for resizing 
      $img_mini = imagecreatetruecolor($x, $y); 

      // This function is better for image resizing than imagecopyresized 
      // Gives you better quality and no black screens 
      imagecopyresampled($img_mini,$img_big,0,0,0,0,$x,$y,$size[0],$size[1]); 

      // OK, now we ready to save your image! 
      // We will save it in the same format as original 
      switch ($mime) 
      { 
       case 'image/jpeg' : $img_big = imagejpeg($img_mini, $file); break; 
       case 'image/png' : $img_big = imagepng($img_mini, $file); break; 
       case 'image/gif' : $img_big = imagegif($img_mini, $file); break; 
       default: return false; 
      } 

      // Don't forget to free memory. 
      imagedestroy($img_big); imagedestroy($img_mini); 

      return true; 

      // Don't do this. It's wrong. 
      // move_uploaded_file($img_mini,$dir."test"); 
     } 
     // didn't get size 
     else 
      return false; 
    } // isn't a file 
    else 
     return false; 
} 

Я надеюсь, что это было полезно для вас: 3

+0

Спасибо много для оптимизации! но это то же самое для «черного изображения» –

+0

@FlorentPichon Возможно, эти изображения повреждены? Или ваш GD не поддерживает их? Попробуйте создать новый ресурс с этими изображениями и просто сохраните их как JPEG, например: '$ img = imagecreatefromjpeg ('Ripper.jpg'); imagejpeg ($ img, './test.jpg'); '. Будет ли черный экран? Если да, ваш GD не поддерживает это изображение. Если нет - попробуйте проверить массив '$ size', сделал ли PHP правильные данные из изображения? – namikiri

+0

Я тестировал этот код на своем сервере, и он отлично работал с вашим изображением: http://test.nyanserver.com/ripper/Ripper.jpg Итак, я думаю, вам нужно посмотреть на свой комплект GD. – namikiri

0

использовать этот файл повторно размер изображения

один замечание - оно может не поддерживать gif. Включить библиотеку GD.

использование

<img src="resizeImage.php?w=x&h=z&img=path/to/image" border="0'> 

Это изображение размер файла: resizeImage.php

<?php 
header ("Content-type: image/jpeg"); 
/* 
JPEG/PNG Image Resizer 
Parameters (passed via URL): 

img = path/url of jpeg or png image file 

percent = if this is defined, image is resized by it's 
      value in percent (i.e. 50 to divide by 50 percent) 

w = image width 

h = image height 

constrain = if this is parameter is passed and w and h are set 
      to a size value then the size of the resulting image 
      is constrained by whichever dimension is smaller 

Requires the PHP GD Extension 

Outputs the resulting image in JPEG Format 

*/ 

$img = $_GET['img']; 
$percent = $_GET['percent']; 
$constrain = $_GET['constrain']; 
$w = $_GET['w']; 
$h = $_GET['h']; 

// get image size of img 
$x = @getimagesize($img); 
// image width 
$sw = $x[0]; 
// image height 
$sh = $x[1]; 

if ($percent > 0) { 
    // calculate resized height and width if percent is defined 
    $percent = $percent * 0.01; 
    $w = $sw * $percent; 
    $h = $sh * $percent; 
} else { 
    if (isset ($w) AND !isset ($h)) { 
     // autocompute height if only width is set 
     $h = (100/($sw/$w)) * .01; 
     $h = @round ($sh * $h); 
    } elseif (isset ($h) AND !isset ($w)) { 
     // autocompute width if only height is set 
     $w = (100/($sh/$h)) * .01; 
     $w = @round ($sw * $w); 
    } elseif (isset ($h) AND isset ($w) AND isset ($constrain)) { 
     // get the smaller resulting image dimension if both height 
     // and width are set and $constrain is also set 
     $hx = (100/($sw/$w)) * .01; 
     $hx = @round ($sh * $hx); 

     $wx = (100/($sh/$h)) * .01; 
     $wx = @round ($sw * $wx); 

     if ($hx < $h) { 
      $h = (100/($sw/$w)) * .01; 
      $h = @round ($sh * $h); 
     } else { 
      $w = (100/($sh/$h)) * .01; 
      $w = @round ($sw * $w); 
     } 
    } 
} 

$im = @ImageCreateFromJPEG ($img) or // Read JPEG Image 
$im = @ImageCreateFromPNG ($img) or // or PNG Image 
$im = @ImageCreateFromGIF ($img) or // or GIF Image 
$im = false; // If image is not JPEG, PNG, or GIF 

if (!$im) { 
    // We get errors from PHP's ImageCreate functions... 
    // So let's echo back the contents of the actual image. 
    readfile ($img); 
} else { 
    // Create the resized image destination 
    $thumb = @ImageCreateTrueColor ($w, $h); 
    // Copy from image source, resize it, and paste to image destination 
    @ImageCopyResampled ($thumb, $im, 0, 0, 0, 0, $w, $h, $sw, $sh); 
    // Output resized image 
    @ImageJPEG ($thumb); 
} 
?> 
Смежные вопросы