Laravel 4.1, how to compare image height and width within a function

跟風遠走 提交于 2019-12-13 06:00:54

问题


I am trying to determine in which way an image has to be cropped to fit perfectly as a square user profile image.

I have discovered the Laravel package "intervention image" but as far as I can see this one does not offer a function to compare whether an image is horizontal or vertical.

http://intervention.olivervogel.net/

Is there any good way to determine whether the image is a square or horizontal or vertical before resizing and cropping it?

This is what I do at the moment:

$img->resize(400, null, true)->crop(400, 400);

It works perfectly for squares obviously and it works pretty good for vertical but it does not work very well for horizontal images.

Any help would be much appreciated.

Thanks!


回答1:


So, here's my take on it.

http://jsfiddle.net/SinisterSystems/PD4a2/1/

HTML:

<img id="img1" src="http://hdwallpaper2013.com/wp-content/uploads/2013/02/Download-Flower-Background-Images-HD-Wallpaper.jpg" />

<img id="img2" src="http://1.bp.blogspot.com/_74so2YIdYpM/TEd09Hqrm6I/AAAAAAAAApY/rwGCm5_Tawg/s1600/tall%2Bcopy.jpg" />

<img id="img3" src="http://upload.wikimedia.org/wikipedia/commons/8/89/Love_Heart_symbol_square.svg" />

CSS:

img {
    max-width:500px;
    max-height:500px;
    border:1px solid #000;
}

Javascript:

function findSize(x){
    var h = x.height();
    var w = x.width();
    if(h<w){
       alert("Image is wider than it is tall.");
    } else if(w<h){
       alert("Image is taller than it is tall.");
    } else {
       alert("Image is square.");
    }
}
findSize($('#img1'));
findSize($('#img2'));
findSize($('#img3'));

Gives you a definitive comparison of which values are either taller, wider, or square.

All you would have to do otherwise is include the add css code I provided in the previous question you posted for each conditional. I'd set a horizontal class, vertical class, and a square class. Like this Fiddle. You will have to define the classes in CSS

Obviously I just set a border color, but you could do whatever you wanted at this point.




回答2:


You can use getimagesize($link), which returns an array with the width and height of an image. Then just check horizontal or vertical or square using:

<?php
function WvsH ($link) {
    $size = getimagesize($link);
    if ($size[0] < $size[1]) {
        return 'vertical';
    }
    else if ($size[1] < $size[0]) {
        return 'horizontal';
    }
    else {
        return 'square';
    }
}
?>

Of course, that is assuming that the link exists.



来源:https://stackoverflow.com/questions/21176543/laravel-4-1-how-to-compare-image-height-and-width-within-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!