调整图像大小时,它不保持比例?

时间:2015-01-13 13:04:25

标签: php html css

当我在我的网站上传图像时,它会将最大值调整为100,最大值为100.唯一的问题是不能保持其比例...例如:原始图像为200 x 400,在调整其100之后100即使它应该是50乘100。

脚本:

<script>
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#imgprev')
                    .attr('src', e.target.result)
                    .width(100)
                    .height(100);
            };

            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

CALL:

            <div class="simplr-field ">
                <label class="left" for="small_image">
                    <strong>Huidige kleine afbeelding: </strong><br> (Hieronder vindt u de huidige kleine afbeelding.)
                    <br>
                    <img id="imgprev" src="<?=$post['small_image_url'];?>" alt="Afbeelding preview" style="width: 100px;">
            </div>
                <div class="simplr-field ">
                    <label class="left" for="small_image">
                        <strong>Wijzigen kleine afbeelding: </strong><br> (de gekozen afbeelding wordt automatisch geschaald naar een maximaal formaat van 100*100 pixels.
                        De bestaandsgrootte is 200kB maximaal. Alleen JPG, JPEG en PNG toegestaan.)
                    <br>
                        <input type="file" name="file" id="file" onchange="readURL(this)">
                </div>

2 个答案:

答案 0 :(得分:1)

当你重新调整图像大小时,你必须通过设置高度的属性值或宽度 自动<给它一个喘息空间/强>

<强> HTML

<div id="image-container">
<!-- Image Goes here -->
</div><!-- End Image Container -->

<强> CSS

#image-container {
    width: 100px; /* Adjust as needed */
    height: 100px; /* Adjust as needed */
    overflow: hidden; /* Cuts off whatever goes beyond the given dimension */
}


 #image-container img {
        width: 100px;
        height: auto; /* Gives the image the breathing space as it adjusts */
    }

答案 1 :(得分:1)

指定宽度,并将高度设置为自动。这将保留纵横比。

reader.onload = function (e) {
                $('#imgprev')
                    .attr('src', e.target.result)
                    .css({
                      width: '100px',
                      height: 'auto'
                    });
            };