기울이거나 늘리지 않고 고정된 크기의 축소판을 표시할 수 있도록 사용자 이미지를 자르거나 크기를 조정하려면 어떻게 해야 합니까?

StackOverflow https://stackoverflow.com/questions/991587

문제

나는 사용자들이 내 사이트에 프로필 사진을 업로드할 수 있도록 하기 위해 노력하고 있습니다.내가 피하려고 노력하는 전형적인 예는 다음과 같습니다. lotoffish.com 각 사용자 이미지가 왜곡되어 매우 보기 흉해 보입니다.

alt text

그렇다면 위에서 설명한 왜곡 없이 이미지의 표준 크기 버전을 프로그래밍 방식으로 자르거나 생성하려면 어떻게 해야 합니까?

도움이 되었습니까?

해결책

글쎄요, 최대 높이와 ​​너비가 있어야 합니다. 사용 가능한 이미지 크기가 100x100과 같은 정사각형이라고 가정해 보겠습니다.

사용자가 이미지를 업로드하면 이미지의 크기를 확인한 다음 높이와 너비 중 어느 것이 더 큰지 알아보세요.

그런 다음 최대 크기를 측정하고 해당 측정값과 목표 측정값의 비율을 얻은 다음 해당 비율을 사용하여 높이와 너비를 모두 조정합니다.

따라서 사용자가 높이 500, 너비 450인 사진을 업로드하는 경우 높이가 가장 크기 때문에 썸네일 크기를 100으로 500으로 나누게 됩니다.이는 비율로 .2를 제공합니다.즉, 너비가 90이 되어 100x90으로 줄어들고 왜곡이 발생하지 않습니다.

다른 팁

다음은 BlowDart가 제안한 방법과 유사한 크기 조정을 수행했던 코드 (C#)입니다. "300"을 케이스에서 한쪽의 최대 크기로 교체하십시오.

 private Bitmap ScaleImage(Image oldImage)
    {
        double resizeFactor = 1;

        if (oldImage.Width > 300 || oldImage.Height > 300)
        {
            double widthFactor = Convert.ToDouble(oldImage.Width) / 300;
            double heightFactor = Convert.ToDouble(oldImage.Height) / 300;
            resizeFactor = Math.Max(widthFactor, heightFactor);

        }
        int width = Convert.ToInt32(oldImage.Width / resizeFactor);
        int height = Convert.ToInt32(oldImage.Height / resizeFactor);
        Bitmap newImage = new Bitmap(width, height);
        Graphics g = Graphics.FromImage(newImage);
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        g.DrawImage(oldImage, 0, 0, newImage.Width, newImage.Height);
        return newImage;
    }

또는 : 여전히 고정 치수를 원한다면 BlowDart의 지침을 따르지만 대신 100px / 450px = .22 .. 대신 가장 큰 비율을 계산합니다.

  • 너비 : 100px
  • 높이 : 111.11..px-> 바닥에서 작물 ((111.11-100) / 2) 상단 및 100px 다운.

편집하다: 또는 사용자가 가장 큰 치수를 자르는 방법을 선택하도록하십시오.

사용 Imagemagick. 명령 줄 사용 :

convert -thumbnail geometry

나는 이것과 다른 시나리오에 적합한 PHP를 위해이 기능을 만들었습니다.

<?php

function Image($source, $crop = null, $resize = null)
{
    $source = ImageCreateFromString(file_get_contents($source));

    if (is_resource($source) === true)
    {
        $width = imagesx($source);
        $height = imagesy($source);

        if (isset($crop) === true)
        {
            $crop = array_filter(explode('/', $crop), 'is_numeric');

            if (count($crop) == 2)
            {
                if (($width / $height) > ($crop[0] / $crop[1]))
                {
                    $width = $height * ($crop[0] / $crop[1]);
                    $crop = array((imagesx($source) - $width) / 2, 0);
                }

                else if (($width / $height) < ($crop[0] / $crop[1]))
                {
                    $height = $width / ($crop[0] / $crop[1]);
                    $crop = array(0, (imagesy($source) - $height) / 2);
                }
            }

            else
            {
                $crop = array(0, 0);
            }
        }

        else
        {
            $crop = array(0, 0);
        }

        if (isset($resize) === true)
        {
            $resize = array_filter(explode('*', $resize), 'is_numeric');

            if (count($resize) >= 1)
            {
                if (empty($resize[0]) === true)
                {
                    $resize[0] = round($resize[1] * $width / $height);
                }

                else if (empty($resize[1]) === true)
                {
                    $resize[1] = round($resize[0] * $height / $width);
                }
            }

            else
            {
                $resize = array($width, $height);
            }
        }

        else
        {
            $resize = array($width, $height);
        }

        $result = ImageCreateTrueColor($resize[0], $resize[1]);

        if (is_resource($result) === true)
        {
            ImageCopyResampled($result, $source, 0, 0, $crop[0], $crop[1], $resize[0], $resize[1], $width, $height);
            ImageDestroy($source);

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

            ImageJPEG($result, null, 90);
            ImageDestroy($result);
        }
    }

    return false;
}

Image('/path/to/your/image.jpg', '1/1', '100*');
Image('/path/to/your/image.jpg', '1/1', '100*100');
Image('/path/to/your/image.jpg', '1/1', '100*500');

?>

Imagemagick의 Convert Tool을 사용하여 이것을 달성하기 위해 함께 던진 Bash 명령은 다음과 같습니다. 부모 디렉토리에 앉아있는 일련의 이미지, 일부 초상화, 일부 풍경은 현재 디렉토리의 이미지를 600x400으로 스케일링하고 중심에서 초상화 이미지를 자르고 간단히 조경 이미지를 스케일링하는 이미지를 만듭니다.

for f in ../*jpg; do
    echo $f; 
    size=`identify $f|cut -d' ' -f 3`; 
    w=`echo $size|cut -dx -f 1`; 
    h=`echo $size|cut -dx -f 2`; 
    if [ $w -gt $h ]; then 
        convert $f -thumbnail 600x400 `basename $f`; 
    else 
        convert $f -scale 600x -crop 600x400+0+`echo "((600*($h/$w))/2)" | bc | sed 's/\..*//'` `basename $f`; 
    fi;
done;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top