1

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?

bozhidarc
  • 834
  • 1
  • 11
  • 25

3 Answers3

4

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.

mario
  • 144,265
  • 20
  • 237
  • 291
  • It does? Very nice, didn't know that. +1 – Pekka May 08 '11 at 19:10
  • I tray that, but when I tray to open it I recieved the following error from my image viewer (Eye of GNOME 2.30.0) "Error interpreting JPEG image file (Not a JPEG file: starts with 0x89 0x50)" and from PHP: '/var/www/myImage.jpeg' is not a valid JPEG file in ... – bozhidarc May 08 '11 at 19:49
  • @bozhidarc You are certainly having another issue. The `imagejpeg()` function always stores a JPEG file. You are likely not saving it back correctly into your database or are sending the wrong binary string to your browser. --- Update your question with the surrounding code and how you utilize it. – mario May 08 '11 at 20:38
  • Sorry for my late answer, you are completely right, the problem was in my code :) – bozhidarc May 16 '11 at 08:37
0

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!

James C
  • 14,047
  • 1
  • 34
  • 43
  • It's not bad practice to save images in the database. It makes backing up, security, and moving things around much easier. For example, moving files from the development server to the production server is as easy as copying over the database. The only problem is when you have limited database storage and not file storage – Chad K Nov 30 '18 at 21:49
0

All you need is imagecreatefromstring() to read your data and imagejpeg() to output in jpeg format.

Mel
  • 6,077
  • 1
  • 15
  • 12