How can I use getimagesize using Laravel 4's blade template?
I have the following foreach loop:
@foreach($category as $inventory)
{{ HTML::image('small/' . $inventory->image . '', '' . $inventory->name . '', array('class' => 'scale-with-grid', 'height' => '280', 'width' => 'auto')); }}
@endforeach
I want the getimagesize
function to display the height and width for that specific image in the height
and width
image attributes. Every time I attempted to do it myself but could not get it working correctly.
EDIT
This is what I have tried so far. I think my biggest problem is I am not sure how to access the small folder inside my public directory. I tried using public_path but it's returning a array to string conversion error. However, it seems like when I dump public_path it shows the correct path.
{{ $image = getimagesize(public_path('small/' . $inventory->image . '')) }}
{{ var_dump($image); die; }}
I am using wamp and when I dump public_path this is the first source I get.
string 'C:\wamp\www\product\public/small/image.jpg' (length=71)
I am not sure if that's the issue. When I copy and paste that into my browser it will load the image with no problem
Try this
list($width, $height) = getimagesize("Full path of the image");
Now you can use $width and $height.
I was able to solve it by not using blade brackets and inserting
<?php list($width, $height) = getimagesize(asset('small/' . $inventory->image . '')); ?>
{{ HTML::image('small/' . $inventory->image . '', '' . $inventory->name . '', array('class' => 'scale-with-grid', 'height' => 280, 'width' => $width)); }}
I would suggest against writing such a code in controller. If you need to repeat this somewhere else (which is the case most of the time) then writing it in controller is a bad idea. Keep you controllers simple. I would probably solve this in my repository or something like that... but if its small project that i suggest defining HTML::macro
HTML::macro('imageWithSize', function($url, $alt = null, $attributes = array(), $secure = null)
{
// original - HTMl::image($url, $alt = null, $attributes = array(), $secure = null);
// get image path - change this to whatever suits you
$image_path = public_path($url);
// get image size
list($width, $height) = getimagesize($image_path);
// add those to attributes array
$attributes['width'] = $width;
$attributes['height'] = $height;
return HTML::image($url, $alt, $attributes, $secure );
});
You can see the original implementatio of HTML::image here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.