开发者

best way to display image in php

开发者 https://www.devze.com 2023-01-02 01:27 出处:网络
I am storing images in mysql 开发者_如何学JAVADb directly. what is the best way to display the image in good quality (thumbnail and original size images) using php.So, you are storing the binary conte

I am storing images in mysql 开发者_如何学JAVADb directly. what is the best way to display the image in good quality (thumbnail and original size images) using php.


So, you are storing the binary content of a image files in your database (probably a BLOB field), right?

Displaying the original size image is not a big deal, I hope you have stored the file name / file extension (or at least mime type) of the original image along with the binary data.

If you table images e. g. contains two, content which holds the binary data and file_name which holds the file name and file extension of the stored image, you can think of code like this:

$res = mysql_query("select * from images");

while($row = mysql_fetch_assoc($res)) {
    $pathname = 'some/path/' . $row['file_name'];
    file_put_contents($pathname, $row['content']);
}

What this does is selecting all entries from the images table and writes the binary content from the database to an outfile named after the orignal image. Consider setting the [chmod][1] after writing the outfile, depending on your server setup.

If you dont have the file name property available, then you must generate some random name (maybe using md5($row['content'])? Could be very slow though.). But you need the original file extension or the mime type of the stored image, otherwise its not easy to find out if the image is abc.JPG or abc.PNG or abc.GIF etc.

Now you can access your created image (e. g. XYZ.jpg) using http://www.domain.com/some/path/XYZ.jpg if some/path/ is within your document root folder.

With the original image stored on disk it is easy to create a thumbnail. I heartly recommend Imagemagick (check if installed on your server), but you can also roll your own thumbnail script using PHPs GDLib which is bundled with PHP and most likely available. There already a ton of prebuilt thumbnail scripts for PHP which rely on Imagemagick and/or GDLib. I haven´t tried yet but heard good things about phpThumb().

One last word: you probably noticed it yourself, storing images as binary in a database is not really a good idea. Of course, if the application is already built and you have to work with things the way they are, you dont have a choice on this. But performance-wise it is way better to store just the image pathname in the database along with some meta data (like filesize, width, height etc.), keeps your db size down and the select/php code for processing the resultset fast.


The best way to display the image in good quality (thumbnail and original size images) using php is storing both original image and thumbnail in the filesystem and then generate an <img> tag to display it.

0

精彩评论

暂无评论...
验证码 换一张
取 消