How to Save Images into Database

Storing images in a database versus a filesystem

If the images are user data, rather than part of your application's code or theme, then storing the images in the database is a good idea, because…

  • Backups are easier to manage if all you have to back up is the database. On the other hand, if you store some application data in the database and some in the filesystem, then you'll have to coordinate the backup schedules of your database and your filesystem to ensure that the two are consistent.

    If you have a database administrator at your disposal, then great! Your backups should already be taken care of. If not, then database backups may be slightly tricky to set up, but once you do have a backup system, it can be better than filesystem backups. For example, many database systems have support for streaming replication.

  • If your application is load-balanced and served by a pool of multiple webservers, then you'll either have to replicate the data to all of the machines, or share them among your servers using a network filesystem.

Of course, having the images on a filesystem also has its advantages, namely in performance and simplicity, since most webservers are built to serve static files. A hybrid approach could give you the best of both worlds:

  • The images stored in the database would be the authoritative data.
  • Your application can have a feature to extract them as files in their local filesystem as a kind of cache. That cache can be rebuilt at any time, since it is not authoritative.
  • The webserver can then serve the files directly from the filesystem.

How to save images into Database

You should use BLOB in your database:

Check this tutorial...

But I think you should download and store image in HashMap, which will make it simpler.

Code:

Stroring

var imageMap = new HashMap<String, byte[]>();

var imageUrl = "http://i.stack.imgur.com/TLjuP.jpg";

var imagedata = GetImage(imageUrl);

imageMap.put("img",imagedata);


Retrieving

var imageData = imageMap.get("img");

var imageStream = new ByteArrayInputStream(imageData);

var image = BitmapFactory.decodeStream(imageStream);


GetImage

private byte[] GetImage(String url)
{
try
{
var imageUrl = new URL(url);
var urlConnection = imageUrl.openConnection();

var inputStream = urlConnection.getInputStream();
var bufferedInputStream = new BufferedInputStream(inputStream);

var byteArrayBuffer = new ByteArrayBuffer(500);

int current = 0;
while ((current = bis.read()) != -1)
{
byteArrayBuffer.append((byte)current);
}

return byteArrayBuffer.toByteArray();
}
catch (Exception e)
{
Log.d("ImageManager", "Error: " + e.toString());
return null;
}
}

Hope it helps you.

Can I store images in MySQL

Yes, you can store images in the database, but it's not advisable in my opinion, and it's not general practice.

A general practice is to store images in directories on the file system and store references to the images in the database. e.g. path to the image,the image name, etc.. Or alternatively, you may even store images on a content delivery network (CDN) or numerous hosts across some great expanse of physical territory, and store references to access those resources in the database.

Images can get quite large, greater than 1MB. And so storing images in a database can potentially put unnecessary load on your database and the network between your database and your web server if they're on different hosts.

I've worked at startups, mid-size companies and large technology companies with 400K+ employees. In my 13 years of professional experience, I've never seen anyone store images in a database. I say this to support the statement it is an uncommon practice.

How can I store and retrieve images from a MySQL database using PHP?

First you create a MySQL table to store images, like for example:

create table testblob (
image_id tinyint(3) not null default '0',
image_type varchar(25) not null default '',
image blob not null,
image_size varchar(25) not null default '',
image_ctgy varchar(25) not null default '',
image_name varchar(50) not null default ''
);

Then you can write an image to the database like:

/***
* All of the below MySQL_ commands can be easily
* translated to MySQLi_ with the additions as commented
***/
$imgData = file_get_contents($filename);
$size = getimagesize($filename);
mysql_connect("localhost", "$username", "$password");
mysql_select_db ("$dbname");
// mysqli
// $link = mysqli_connect("localhost", $username, $password,$dbname);
$sql = sprintf("INSERT INTO testblob
(image_type, image, image_size, image_name)
VALUES
('%s', '%s', '%d', '%s')",
/***
* For all mysqli_ functions below, the syntax is:
* mysqli_whartever($link, $functionContents);
***/
mysql_real_escape_string($size['mime']),
mysql_real_escape_string($imgData),
$size[3],
mysql_real_escape_string($_FILES['userfile']['name'])
);
mysql_query($sql);

You can display an image from the database in a web page with:

$link = mysql_connect("localhost", "username", "password");
mysql_select_db("testblob");
$sql = "SELECT image FROM testblob WHERE image_id=0";
$result = mysql_query("$sql");
header("Content-type: image/jpeg");
echo mysql_result($result, 0);
mysql_close($link);

Saving images to MySQL Database? Yes? Or not?

A few comments:

You seem to be using date('d.m.Y') I guess to get the current date. You're using it as a PHP function, but it's inside an SQL statement. I suggest you use CURDATE() if you put it inside the SQL statement. If you use the PHP function, do it outside the SQL statement and bind the result as a parameter.

Your code stores both the img content and the path to the tmpfile for the upload. I don't see the need for this. Pick one or the other. An uploaded tmpfile is removed at the end of the PHP request, so I don't know why you would store that path.

Don't use addslashes() for content you're binding to a query parameter. This will store the literal slashes in your content. Since your image file is not text, it will add slashes before binary bytes that happen to be the same as ASCII character \ (0x5C). You don't need slashes anyway when using bound parameters, even if it's for text.

See https://www.php.net/manual/en/mysqli-stmt.send-long-data.php for the right way to store larger data content via bound parameter. This allows files that are larger than MySQL's max_allowed_packet buffer, because it sends the content in chunks.

$query = "INSERT INTO `produkt` (`id`, `date`, `img`)
VALUES('', CURDATE(), ?)";

// prepare query
$stmt = $conn->prepare($query);

// bind params
$null = NULL;
$stmt->bind_param("b", $null);
$fp = fopen($_FILES['img']['tmp_name'], "r");
while (!feof($fp)) {
$stmt->send_long_data(0, fread($fp, 8192));
}
fclose($fp);

// execution of the prepared statement
$stmt->execute();

Are you asking whether it's better to store the image or the path? There is no universal rule about this. Many developers would say, "never store big images and other files in the database" because it makes the database larger.

But there are good reasons to do that sometimes, such as:

  • If you delete a row, it will atomically delete the image stored on that row. Whereas if you store it outside the database, then you need to remember to delete any orphaned images when you delete a row in the database.

  • Data in the database obeys transaction semantics. If you insert/update/delete a row that references an image, the change is isolated until you commit. You may also choose to rollback the transaction. You can't do that with files on the filesystem.

  • A database backup will collect all the image data along with row data, and this will be atomic. If you keep image files outside the database, a data backup must be done in two steps, and you always worry if you got the images that are true for that database snapshot.

Saving images: files or blobs?

I usually go with storing them as files, and store the path in the database. To me, it's a much easier and more natural approach than pushing them into the database as blobs.

One argument for storing them in the database: much easier to do full backups, but that depends on your needs. If you need to be able to easily take full snapshots of your database (including the images), then storing them as blobs in the database is probably the way to go. Otherwise you have to pair your database backup with a file backup, and somehow try to associate the two, so that if you have to do a restore, you know which pair to restore.

how to insert an image file into database table

2 possibilites:

1 Save to file server(prefered):

Save the image on your file server and save the path where you saved it in the database. This allows you to directly access this file and helps you to better output it to the user than with the second method. I'd prefer this.

Explanation: upload file with php and save path to sql

2 Save to database:

You can save the content of images to a BLOB (Binary large object).

Explanation: Insert Blobs in MySql databases with php



Related Topics



Leave a reply



Submit