2011-11-11 39 views
0

我有一個腳本從各種URL中檢索遠程圖像。寬度和高度是未知變量。在不知道尺寸的情況下按比例縮放圖像

我把它們顯示在我的頁面上,我將高度降低到55px。但是,非常寬的圖像(橫幅等)以全寬顯示。

我無法約束寬度和高度,因爲我會扭曲圖像。有沒有人知道一個創造性的解決方案,將按比例縮放這些圖像,使其不超過55px(h)和75px(w)?

p.s.我已經嘗試了getimagessize()在PHP中,但功能需要太長時間才能完成

謝謝!

+0

我其實這樣的事情在PHP,但我用和getimagesize和類似下面的答案。你的意思是太長而無法完成?請更具體一些 - 該解決方案是否基於PHP或基於JavaScript(如下面的好答案)。
和另一個小東西:如果你確實使用php來調整大小,你可以在服務器端緩存重新調整大小的圖像,這樣該函數對每個圖片只運行一個(如果(!$ minipic)然後緩存else:return $ minipic) – alonisser

+0

太長,因爲它使用http請求,並且我從中拉出圖像的一些頁面有20多張圖像。有些請求需要超過30秒。無論如何,雖然有效,但速度太慢 –

回答

2

我有一個類似的問題,但我使用的是jQuery。但我認爲你可以在php中使用相同的邏輯來計算圖像大小。

var maxWidth = 75; // Max width for the image 
    var maxHeight = 77; // Max height for the image 
    var ratio = 0; // Used for aspect ratio 
    var width = $(this).width(); // Current image width 
    var height = $(this).height(); // Current image height 

    // Check if the current width is larger than the max 
    if(width > maxWidth){ 
     ratio = maxWidth/width; // get ratio for scaling image 
     $(this).css("width", maxWidth); // Set new width 
     $(this).css("height", height * ratio); // Scale height based on ratio 
     height = height * ratio; // Reset height to match scaled image 
     width = width * ratio; // Reset width to match scaled image 
    } 

    // Check if current height is larger than max 
    if(height > maxHeight){ 
     ratio = maxHeight/height; // get ratio for scaling image 
     $(this).css("height", maxHeight); // Set new height 
     $(this).css("width", width * ratio); // Scale width based on ratio 
     width = width * ratio; // Reset width to match scaled image 
    } 

希望這有任何幫助。

Bah我剛剛意識到我腦部放屁,圖像尺寸未知。無視整個事情

+0

! –

1

和嘿,你總是可以使用CSS來做到這一點!像這樣answer explains,但你將避免支持ie6和也許ie7這個功能(你可以使用條件註釋來調整javascript或serverside php腳本在這種情況下)

順便說一下上面的答案確實有效!但你應該程式設計加入IMG和獲取圖像的高度和距離這樣的目標直寬度,然後運行調整大小功能上面:

var rimg = new Image(); 
    rimg.src = "yourimageserverurl"; 
    var original_height = rimg.height; 
    var original_width = rimg.width; 
    start the resize function on rimg.. 
相關問題