2010-07-26 9 views
7

지정된 경계에 맞게 이미지의 크기를 줄이는 함수를 작성하고 싶습니다. 예를 들어, 1280x800에 맞도록 2000x2333 이미지의 크기를 조정하려고합니다. 종횡비는 유지되어야합니다. 나는 다음 알고리즘을 제안했다 :이미지 크기 조정 알고리즘

NSSize mysize = [self pixelSize]; // just to get the size of the original image 
int neww, newh = 0; 
float thumbratio = width/height; // width and height are maximum thumbnail's bounds 
float imgratio = mysize.width/mysize.height; 

if (imgratio > thumbratio) 
{ 
    float scale = mysize.width/width; 
    newh = round(mysize.height/scale); 
    neww = width; 
} 
else 
{ 
    float scale = mysize.height/height; 
    neww = round(mysize.width/scale); 
    newh = height; 
} 

그리고 그것은 보였다. 글쎄 ... 하지만 1280x800 크기의 이미지를 1280x800 크기로 조정하려고 시도한 결과 1280x1024 (1280x800에 맞지 않음)라는 결과가 나왔습니다.

누구나이 알고리즘이 어떻게 작동해야하는지 아이디어가 있습니까?

답변

26

일반적으로 이렇게하는 방법은 원래 너비와 새 너비의 비율과 원래 높이와 새 높이의 비율을 확인하는 것입니다.

그런 다음 이미지를 가장 큰 비율로 축소합니다. 예를 들어, 800x600 이미지를 400x400 이미지로 크기 조정하려는 경우 폭 비율은 2이고 높이 비율은 1.5입니다. 2의 비율로 이미지를 축소하면 400x300 이미지가됩니다.

당신은 이미지의 높이 또는 너비 중 하나가 경계 상자의 것과 동일 할 것이라는 점을 알고있다 :

NSSize mysize = [self pixelSize]; // just to get the size of the original image 
int neww, newh = 0; 
float rw = mysize.width/width; // width and height are maximum thumbnail's bounds 
float rh = mysize.height/height; 

if (rw > rh) 
{ 
    newh = round(mysize.height/rw); 
    neww = width; 
} 
else 
{ 
    neww = round(mysize.width/rh); 
    newh = height; 
} 
+0

아 난 후, 비율이 1, 1.28 것 화면 1280x800에 1280X1024의 귀하의 예제 캐스트에 대한 추가해야는 1000 X 800 – GWW

+0

감사합니다 것입니다 크기를 조정! 나는 마침내 그것이 일하는 것이라고 생각한다! – Marius

6

다음은 문제를 접근하는 방법입니다.

경계 상자의 크기와 동일한 치수를 결정했으면 이미지의 종횡비를 사용하여 다른 치수를 계산합니다.

double sourceRatio = sourceImage.Width/sourceImage.Height; 
double targetRatio = targetRect.Width/targetRect.Height; 

Size finalSize; 
if (sourceRatio > targetRatio) 
{ 
    finalSize = new Size(targetRect.Width, targetRect.Width/sourceRatio); 
} 
else 
{ 
    finalSize = new Size(targetRect.Height * sourceRatio, targetRect.Height); 
} 
+0

imageRatio 란 무엇입니까? –

+0

@JonathanAquino 나는 이것이'sourceRatio'라고 생각했다. 좋은 픽업. –