1

I am trying to display images for each blog post. I have them set up so that it is displaying the blog name, excerpt and published date, but I am struggling to get the images which I have stored as Blobs. I have attached my code, which is in 3 parts: the entity, which has set and get variables; the index.html.twig file, which is the front end (how I am displaying the image); and the post.orm.yml file, which is to set the type of item the image is, i.e., BLOB.

Post entity

/**
 * Set image
 *
 * @param /post/blob $image
 *
 * @return Post
 */
public function setimage($image)
{
    $this->image = $image;

    return $this;
}

/**
 * Get image
 *
 * @return post/blob
 */
public function getimage()
{
    return $this->image;
}

index.html.twig

{{post.image}}

post.orm.yml

Shannon\BlogBundle\Entity\Post:
    type: entity
    table: null
    repositoryClass: Shannon\BlogBundle\Repository\PostRepository
    id:
        id:
            type: integer
            id: true
            generator:
                strategy: AUTO
    fields:
        title:
            type: string
            length: '255'
        body:
            type: text
        publishedAt:
            type: datetime
            column: published_at
        image:
            type:image
    lifecycleCallbacks: {  }

postcontroller.php

public function imageAction($id) { $image = $this->getDoctrine()->getRepository('ShannonBlogBundle:Image')->findOneBy(array('id'=> $id));
return $this->render('index.html.twig', array('image' => $image)); } } public function imageAction($id) { $image = $this->getDoctrine()->getRepository('ShannonBlogBundle:Image')->findOneBy(array('id'=> $id));
return $this->render('index.html.twig', array('image' => $image)``); }

1

1 Answer 1

1

You need to encode your image in base64 and simply embed it in the HTML:

<img  src="data:image/png;base64,{{ imageBase64 }}" />
Sign up to request clarification or add additional context in comments.

7 Comments

hi i have tried <img src="data:image/jpg;base64,{{ post.image }}" /> in index.html.twig and it shows resourse #419
Try in controller $imageBase64 = base64_encode(stream_get_contents($post.getImage()); and pass it to twig
i keep receiving a parse error when i tried that i have no idea whats going it is able to retrive the rest of the blog information
Parse error: syntax error, unexpected '$imageBase64' (T_VARIABLE), expecting ';' or '{'
That's not parse error, it is syntax error as it said.
|

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.