php - 在不知道尺寸的情况下按比例缩放图像

标签 php html css

我有一个脚本可以从各种 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/

相关文章:

php - 我想在 php 中将文件从本地主机上传到我的服务器

php - 使用正则表达式从文本中删除 URL(当前域除外)

php - 如何捕获PHP snmpwalk警告?

jquery - 将 IPAD 与 JQuery 一起使用时更改类

html - 无法在 Outlook 中正确显示 html 电子邮件签名

cookies - Cookie 仍设置在 HTTP 上,ini_set ('session.cookie_secure' ,1);

html - CSS :not selector has no effect

javascript - 减少文本和背景图像之间的填充

css - 纯CSS3动画: 2 parts animation,一个接一个

html - Flexbox 子项在 Safari 中呈现错误