Search code examples
phpimagebase64binary-databinary-image

Get image type from binary data image & convert it to actual image in PHP


frankly speaking, I'm not sure if this is duplication of another question since the context should be different.

I currently working with some API that returns status & contents(binary data image) which I will base64 encode at first. The question is how to initially get the image type on it's binary data form, & after that convert it to actual image with its type extension. In this scenario, I'm using PHP since it involves with backend task. Thanks.

updates: for this case, I get the image in binary form from external site api. I use file_get_contents but it returns empty or null. When i use base64_encode then it will shows up the image as an encoded data. the issue is I need to convert it as normal image. I try getimagesize as encoded & decoded & try to print the output & it returns empty. is there any steps I am still missing?


Solution

  • About your 2 questions:

    how to convert it back to normal image.

    If the image is simply encode with base64, then of course decode it with base64_decode got the original image data.

    $original_image = base64_decode($encoded_base64_string);
    

    I guess no since what I need is its original image type

    Don't be confused by it's name, getimagesize also tells you the image type and the mime type.