3

I need to display images stored in my database, from users in my symfony 2 application.
I've searched and I found examples such as:

Php Display Image Blob from Mysql

The line:

echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';

It didn't worked for me. How to return an image file and display it in user's profile or a gallery page?

1 Answer 1

2

I created this action that searches the blob data in my table: Empleado.

    /**
     * @Route("/employee/photo/{id}", name="zk_time_employee_photo", requirements={"id" = "\d+"}, defaults={"id" = 1})
     */
    public function photoAction()
    {
        $request = $this->getRequest();
        $workerId = $request->get('id');
        if (empty($workerId))
           //throw exception

        $em = $this->getDoctrine()->getManager();
        $repository = $em->getRepository('ZkTimeBundle:Empleado');

        $photo = $repository->findPhoto($workerId);
        if (empty($photo))
            //throw exception

        $response = new StreamedResponse(function () use ($photo) {
            echo stream_get_contents($photo);
        });

        $response->headers->set('Content-Type', 'image/png');
        return $response;
    }

This part is essential (works for both formats, no matters the original format stored):

 $response->headers->set('Content-Type', 'image/png');<br>
 OR
 $response->headers->set('Content-Type', 'image/jpeg');<br>

In order to display it I chose:

<img src="{{ asset(path('zk_time_employee_photo', {'id': employee.Id})) }}"/>

The base is the same for multiple images (carousel) or a gallery.
I hope this helps, because the web has empty results about it or not focused in Symfony2. Mainly, pure PHP.

This guys were very helpful:

Answer #1: symfony2-how-to-display-download-a-blob-field
Answer #2: symfony2-path-to-image-in-twig-template

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.