我有一个脚本可以从各种 URL 检索远程图像。宽度和高度是未知变量。
我将它们显示在我的页面上,并将每个高度降低到 55 像素。但是,非常宽的图像(横幅等)以全宽显示。
我无法限制宽度和高度,因为我会扭曲图像。有谁知道有创意的解决方案可以按比例缩放这些图像,使它们不超过 55px(h) 和 75px(w)?
附注我已经在 php 中尝试过 getimagessize(),但是这些函数需要很长时间才能完成
谢谢!
最佳答案
我遇到了类似的问题,但我使用的是 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
}
希望对您有所帮助。
呸,我才意识到我脑子放屁了,图片大小未知。忽略整个事情
关于php - 在不知道尺寸的情况下按比例缩放图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8100621/