I have a database with a column filled with image binaries data. After I made some research I figuried out how to detect in which image format is the data. Lets say in of the records in my images column is in gif format, now I want to save it with php gd2 to jpeg format. Please, can someone tell me how can I do that?
问题:
回答1:
If you only want to convert the image data to JPEG then all you need is imagecreatefromstring
and imagejpeg
. Basically:
imagejpeg(imagecreatefromstring($gif_bindata), "temp.jpeg");
$jpeg_bindata = file_get_contents("temp.jpeg");
It's that simple because imagecreatefromstring
detects the file type automatically (the first few bytes contain enough magic bytes to make detection feasible). And obviously you might want to use a real temporary filename instead.
回答2:
I think you'll need to do the following for each image:
- Write out the BLOB image data to a file
- Open the image in gd with
imagecreatefromgif()
- Write the image back out to the disk with
imagejpeg()
- Read in the image data from file and write it back to the database
In general terms keeping image data in the database like this is bad practice. A nicer solution is to store the images on the webserver disk but to store the file location to the images in the database. If for example you'd done this it'd be a lot easier for you to fix the problem that your explaining!
回答3:
All you need is imagecreatefromstring() to read your data and imagejpeg() to output in jpeg format.