yii2php-imagine

Yii2 render image in browser without image tag using yii2-imagine


I'm using yii2-imagine

$imagine = yii\imagine\Image::getImagine();
Imagine->open('path/watermark.jpg')->show('jpg');

My problem is it not show the image, it show that:

����JFIF��>CREATOR: gd-jpeg v1.0 (using IJG JPEG v90), default quality ��C    $.' ",#(7),01444'9=82<.342��C  2!!22222222222222222222222222222222222222222222222222����"�� ���}!1AQa"q2���#B��R��$3br� %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������� ���w!1AQaq"2�B���� #3R�br� $4�%�

Any idea?


Solution

  • You need to use the getImagine() function first to invoke the GD or Imagick which ever available instance then call ->open() and ->show() on the object. Moreover, you need to provide the $options for the image to display too. You can copy paste the following code inside an action in your controller and can see the result image. I just tested on my local system, and it is in working, just remember to provide valid path to the $source variable

    use yii\imagine\Image;    
    
    $source="/path/to/your/image.jpg";        
    $imagine = new Image();
    
    $options = array(
                'resolution-units' => \Imagine\Image\ImageInterface::RESOLUTION_PIXELSPERINCH,
                'resolution-x' => 300,
                'resolution-y' => 300,
                'jpeg_quality' => 100,
            );
    
    echo $imagine->getImagine()->open($source)->show('jpg',$options);
    

    Apart from the above solution that displays the image in the browser if you want to display the image inside the img tag you can base64_encode the raw image data returned from the open() method and provide into the tag like below.

    echo '<img src="data:image/jpeg;base64,'.base64_encode($imagine->getImagine()->open($source)).'" >';
    

    Hope it helps