문제

PHP에서 이미지를 자르고 파일을 저장하고 싶습니다. 나는 당신이 GD 라이브러리를 사용해야한다는 것을 알고 있지만 어떻게 확실하지 않습니다. 어떤 아이디어?

감사

도움이 되었습니까?

해결책

당신은 사용할 수 있습니다 imagecopy 이미지의 필요한 부분을 자르기 위해. 명령은 다음과 같습니다.

imagecopy  ( 
    resource $dst_im - the image object ,
    resource $src_im - destination image ,
    int $dst_x - x coordinate in the destination image (use 0) , 
    int $dst_y - y coordinate in the destination image (use 0) , 
    int $src_x - x coordinate in the source image you want to crop , 
    int $src_y - y coordinate in the source image you want to crop , 
    int $src_w - crop width ,
    int $src_h - crop height 
)

코드 php.net - 80x40 px 이미지가 소스 이미지에서 자릅니다.

<?php
// Create image instances
$src = imagecreatefromgif('php.gif');
$dest = imagecreatetruecolor(80, 40);

// Copy
imagecopy($dest, $src, 0, 0, 20, 13, 80, 40);

// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);

imagedestroy($dest);
imagedestroy($src);
?>

다른 팁

이 기능은 이미지를 유지하는 이미지를 유지합니다.

 function resize_image_crop($image, $width, $height)
     {

        $w = @imagesx($image); //current width

        $h = @imagesy($image); //current height
        if ((!$w) || (!$h)) { $GLOBALS['errors'][] = 'Image couldn\'t be resized because it wasn\'t a valid image.'; return false; }
        if (($w == $width) && ($h == $height)) { return $image; }  //no resizing needed
        $ratio = $width / $w;       //try max width first...
        $new_w = $width;
        $new_h = $h * $ratio;    
        if ($new_h < $height) {  //if that created an image smaller than what we wanted, try the other way
            $ratio = $height / $h;
            $new_h = $height;
            $new_w = $w * $ratio;
        }
        $image2 = imagecreatetruecolor ($new_w, $new_h);
        imagecopyresampled($image2,$image, 0, 0, 0, 0, $new_w, $new_h, $w, $h);    
        if (($new_h != $height) || ($new_w != $width)) {    //check to see if cropping needs to happen
            $image3 = imagecreatetruecolor ($width, $height);
            if ($new_h > $height) { //crop vertically
                $extra = $new_h - $height;
                $x = 0; //source x
                $y = round($extra / 2); //source y
                imagecopyresampled($image3,$image2, 0, 0, $x, $y, $width, $height, $width, $height);
            } else {
                $extra = $new_w - $width;
                $x = round($extra / 2); //source x
                $y = 0; //source y
                imagecopyresampled($image3,$image2, 0, 0, $x, $y, $width, $height, $width, $height);
            }
            imagedestroy($image2);
            return $image3;
        } else {
            return $image2;
        }
    }

GD를 사용하여 이미지를 자르려면 GD 메소드 조합을 사용해야하며 PHP의 문서에서 "예제 #1"을 보는 경우 imagecopyresampled 메소드, 이미지를 자르고 출력하는 방법을 보여 주면 파일에 출력을 캡처하고 작성하려면 코드를 추가하면됩니다.

http://us2.php.net/manual/en/function.imagecopyresampled.php

다른 옵션도 있습니다 이미지 magick 서버에 설치 한 경우 PHP를 사용하여 직접 액세스 할 수 있습니다. exec 방법 (또는 유사) 또는 PHP를 설치할 수 있습니다. imagick 더 높은 품질의 이미지를 생성하고 제 생각에, 내 의견으로는, 좀 더 직관적이고 유연하게 작업 할 수 있습니다.

마지막으로 오픈 소스를 사용했습니다 phpthumb 매우 간단한 인터페이스를 가지고 있으며 Imagemagick 및 GD를 포함하여 서버의 내용에 따라 여러 옵션으로 작동 할 수있는 클래스 라이브러리.

일부 프로젝트 에서이 스크립트를 사용하고 사용하기가 매우 쉽습니다.http://shiftingpixel.com/2008/03/03/smart-image-resizer/

스크립트에는 PHP 5.1.0 (2005-11-24 이후 이후이 버전에서는 업그레이드 할 시간)과 GD (좋은 웹 호스트에서 거의 누락되지 않음)가 필요합니다.

다음은 HTML에서 사용하는 예입니다.

<img src="/image.php/coffee-bean.jpg?width=200&amp;height=200&amp;image=/wp-content/uploads/2008/03/coffee-bean.jpg" alt="Coffee Bean" />

방금이 기능을 만들었고 내 필요에 맞게 작동하여 중앙 및 자른 썸네일 이미지를 만듭니다. 간소화되어 있으며 WebGautam의 답변에 표시된 것처럼 여러 개의 ImageCopy 호출이 필요하지 않습니다.

이미지 경로, 최종 너비 및 높이 및 선택적으로 이미지의 품질을 제공하십시오. 썸네일을 만들기 위해 이것을 만들었으므로 모든 이미지가 JPG로 저장되므로 필요한 경우 다른 이미지 유형을 수용하도록 편집 할 수 있습니다. 여기서 요점은 impecopyresAmped를 사용하여 썸네일을 생성하는 수학 및 방법입니다. 이미지는 동일한 이름과 이미지 크기를 사용하여 저장됩니다.

function resize_crop_image($image_path, $end_width, $end_height, $quality = '') {
 if ($end_width < 1) $end_width = 100;
 if ($end_height < 1) $end_height = 100;
 if ($quality < 1 || $quality > 100) $quality = 60;

 $image = false;
 $dot = strrpos($image_path,'.');
 $file = substr($image_path,0,$dot).'-'.$end_width.'x'.$end_height.'.jpg';
 $ext = substr($image_path,$dot+1);

 if ($ext == 'jpg' || $ext == 'jpeg') $image = @imagecreatefromjpeg($image_path);
 elseif($ext == 'gif') $image = @imagecreatefromgif($image_path);
 elseif($ext == 'png') $image = @imagecreatefrompng($image_path);

 if ($image) {
  $width = imagesx($image);
  $height = imagesy($image);
  $scale = max($end_width/$width, $end_height/$height);
  $new_width = floor($scale*$width);
  $new_height = floor($scale*$height);
  $x = ($new_width != $end_width ? ($width - $end_width) / 2 : 0);
  $y = ($new_height != $end_height ? ($height - $end_height) / 2 : 0);
  $new_image = @imagecreatetruecolor($new_width, $new_height);

  imagecopyresampled($new_image,$image,0,0,$x,$y,$new_width,$new_height,$width - $x,$height - $y);
  imagedestroy($image);
  imagejpeg($new_image,$file,$quality);
  imagedestroy($new_image);

  return $file;
 }
 return false;
}

아래 방법을 사용하여 이미지를 자르고

/*parameters are 
    $image =source image name
    $width = target width
    $height = height of image
    $scale = scale of image*/
    function resizeImage($image,$width,$height,$scale) {
        //generate new image height and width of source image
        $newImageWidth = ceil($width * $scale);
        $newImageHeight = ceil($height * $scale);
        //Create a new true color image
        $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
        //Create a new image from file 
        $source = imagecreatefromjpeg($image);
        //Copy and resize part of an image with resampling
        imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
        //Output image to file
        imagejpeg($newImage,$image,90);
        //set rights on image file
        chmod($image, 0777);
        //return crop image
        return $image;
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top