PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 17, 2022

[FIXED] How do I convert images from base 64 to their file types in PHP?

 July 17, 2022     bmp, gif, jpeg, php, png     No comments   

Issue

I have objects containing images as base 64 strings, the object also contains file names for the images, and file types (jpeg, png, gif & bmp) for the images. The base 64 strings have already had the tags (e.g. "data:image/png;base64" removed from the beginning.

The format for the objects ($myImg) are as follows:

  • $myImg->fileName contains the name that the converted image should be saved under.

  • $myImg->fileType describes the format that the file is supposed to be saved as - this is used to specify the path extension in the fopen() function.

  • $myImg->b64 contains the 64 bit binary string which represents the image.

The code for my function is as folows:

function toImg(ImageString $myImg){
    //Output file is in the same directory as the PHP script.
    //Uses the object's filetype attribute as the file extension.
    $outputFile = fopen($myImg->fileName . "." . $myImg->fileType, "w");
    $image = base64_decode($myImg->b64);
    fwrite($outputFile, $image);
    fclose($outputFile);
}

The function creates the image files, but I get errors when trying to view them in Xubuntu Image Viewer. The errors are as follows:

  • Error interpreting JPEG image file (Not a JPEG file: starts with 0x14 0x00)

  • Fatal error reading PNG image file: not a PNG file.

  • File does not appear to be a GIF file.

  • BMP image has bogus header data.

I've looked through and followed guides for base64 to image conversion, but none of them have encountered these errors.


Solution

Try to show the image inline in the browser, like this:

<img src="data:image/png;base64,the-base64-string" />

(change png to the correct image format)

If the image is still broken, then the image data is invalid.



Answered By - M. Eriksson
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing