2010-07-26 60 views
7

我想要寫的函數小型化的圖像,以適應指定的邊界。例如,我想調整一個2000x2333圖像的大小,以適應1280x800。寬高比必須保持不變。我想出了以下算法:圖像調整大小算法

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; 
} 

而且它似乎工作。好吧......好像。但後來我嘗試將1280x1024的圖像調整到1280×800的邊界,它給了我1280×1024的結果(這顯然不適合在1280×800)。

任何人有任何想法,這algorighm應該如何工作?

回答

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

哦,我要補充爲1280×1024的例子投以1280×800的比例將是1和1.28,後調整大小這將是1000×800 – GWW 2010-07-26 04:49:54

+0

謝謝!我認爲它終於有效! – Marius 2010-07-26 04:58:51

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? – 2016-10-20 04:52:36

+0

@JonathanAquino我認爲這應該是'sourceRatio'。好的皮卡。 – 2016-10-20 09:32:51