zoukankan      html  css  js  c++  java
  • js和php计算图片自适应宽高算法实现

    js Code:

    <script>
    $width = $(imgobj).width(); //图原始宽
    $newheight = $(imgobj).height(); //图原始高
    $w = 693; //最小宽度
    $h = 840; //最大宽度
    //计算图片比例高度
    $A=$w / $h;
    $A1=$width/$newheight;
    if($A1>$A){
        $width=$w;
        $newheight=$w/$A1;
    }else if($A1<$A){
        $height=$h;
        $width=$h*$A1;
    }else if($A1==$A){
        $width=$w;
        $newheight=$h;
    }
    $width = parseInt($width);//得到的自适应宽度
    $newheight = parseInt($newheight); //得到的自适应高度
    </script>

    说明:

    设容器宽为W,高为H,则宽高比例为W/H=A;
    设被加载图片宽为W',高为H',则被加载图片宽高为W'/H'=A';
    设修正后的被加载图片宽为W'',高为H''。

    结论:
    若被加载图片相对容器更宽,更矮:
    即当A' > A时,W'' = W, H'' = W / A';
    若被加载图片相对容器更高,更窄:
    即当A' < A时,H'' = H, W'' = H * A';
    若被加载图片宽高比与容器相当:
    即当A' = A时,W'' = W, H'' = H。

    php Code:

    // src:原图地址
    // w:需要显示的宽
    // h:需要显示的高
    public static function imageSize_tag($src,$w,$h){
        $src='img.jpg';
        $w = 693;
        $h = 840;
        $src = $_SERVER['DOCUMENT_ROOT'].$src;
        $img = getimagesize($src);
        $width = $img[0];
        $height = $img[1];
          
        $A=$w / $h;
        $A1=$width/$height;
        if($A1>$A){
            $width=$w;
            $height=$w/$A1;
            }
        else if($A1<$A){
            $height=$h;
            $width=$h*$A1;
        }
        else if($A1==$A){
            $width=$w;
            $height=$h;
        }
        return "<img src='$src' height='$height' width='$width' />";
    }
  • 相关阅读:
    mysql常用函数
    快看看你躺枪了吗?最全搞笑中式英语大集合
    浏览器 返回状态码汇总
    Eclipse 快捷键 篇
    Spring定时任务的几种实现
    mysql ---复制表结构---创建新表
    日志级别的选择:Debug、Info、Warn、Error还是Fatal
    关闭网页时如何弹出消息框 提醒用户:您确认关闭吗 ?
    处理session丢失的问题
    工作中存在的问题
  • 原文地址:https://www.cnblogs.com/guangxiaoluo/p/3336890.html
Copyright © 2011-2022 走看看