0

I want to output an image that I've stored in MYSQL with file_get_contents("http://www.example.com/img.jpg") in an HTML page. I have the following code but I'm stuck as to how to make this work. Right now, it displays gibberish or if I use header, a broken image. I'm using codeigniter:

Model:

public function img_get() { $query = $this->db->query('SELECT * FROM imgtable'); if ($query->num_rows() > 0) { foreach ($query->result() as $row) { $data[] = $row; } } return $data; } 

Controller:

class Site extends CI_Controller { public function index() { $this->load->model('img_model'); $data['row'] = $this->img_model->img_get(); $this->load->view('home_view', $data); } 

View:

<html> <head> <title>Homepage</title> </head> <body> <h3>Insert the image url</h3> <br> <?php foreach ($row as $r) { echo $r->img . "<br />"; } ?> </body> </html> 
6
  • What about generating a temporary URL for that image, and put it into the HTML? Commented Jan 29, 2014 at 3:40
  • You need to use <img src="data:image/jpeg;base64,' . base64_encode( $r->img. Take a look at this duplicate question: stackoverflow.com/questions/5525830/… Commented Jan 29, 2014 at 3:41
  • Not being able to serve images directly is yet another reason why storing images in the database is probably a really bad idea. Commented Jan 29, 2014 at 4:09
  • @tadman What's a better way to do it? Commented Jan 29, 2014 at 17:42
  • The recommended practice is to save image files somewhere on your filesystem and store a reference to this in your database, that way your server can simply send the file to service the request, no database access needed and your database backups won't be cluttered with gigabytes of binary data. Even better is using an object-store like Amazon S3 where you don't have to serve the file at all, just provide a URL to the remote resource. Commented Jan 30, 2014 at 16:26

3 Answers 3

2

You are trying to display BLOB data:

displaying an image stored in a mysql blob

Show a BLOB image PHP MySQL along with other data

How to display an BLOB image stored in MySql database?

The trick is using:

<img src="data:image/jpeg;base64,' . base64_encode($r->img) . '"> 

Credit goes to all the other questions and answers on this site :)

Hope this helps!

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

Comments

1

you cannot do that as http need a header to know what is in the content.

<?php foreach($row as $r) { echo "<img src='yourcontroller?id=your_image_id'></br>"; } ?> 

Comments

1

You have to first upload that image in your system. So that you can access that image any time with your site's base url.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.