Display blob image in symfony 2

喜夏-厌秋 提交于 2019-12-14 03:53:04

问题


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:


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



来源:https://stackoverflow.com/questions/24022909/display-blob-image-in-symfony-2

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