How to restrict image width or height on upload

后端 未结 3 1067
一生所求
一生所求 2021-01-16 05:03

I would like manipulate/resize images in a similar way to Pinterest but I am not sure what is the best way to approach it. The goal is to allow a mix of both portrait and la

3条回答
  •  无人及你
    2021-01-16 05:58

    Check for a max size and then resize based on a ratio. Here's a pseudo code example:

    if($imageHeight > $maxHeight) {
        $newHeight = $maxHeight;
        $newWidth = $imageWidth * ($maxHeight / $imageHeight);
    }
    if($imageWidth > $maxWidth) {
        $newWidth = $maxWidth;
        $newHeight = $imageHeight * ($maxWidth / $imageWidth);
    }
    resize($image, $newWidth, $newHeight);
    

    It first checks the height and if the height is greater, it scales it down. Then it checks the width. If the width is too big, it scales it down again. The end result, both height and width will be with in your bounds. It uses the ratio to do the scaling.

    Note, this is pseudocodish. The actual resize function call will depend on your image manipulation library -- same goes for calls to obtain image size.

提交回复
热议问题