rkbom9
rkbom9

Reputation: 913

Convert Image Data URI to Image PHP

I have a data uri variable in php

$imageURL  = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAyAAAAJYCAYAAACadoJwAAAgAElEQ…ACIiACIiAC5U1AAqS891erEwEREAEREAEREAEREIFAEfj/bfXX..."

I am trying to insert this into a pdf using fpdf for which I need to convert this into a image I guess. I tried doing something like

base64_decode($imageURL);

but this does not work. How I successfully insert this data uri into pdf.

Upvotes: 2

Views: 4548

Answers (2)

Vytaliy Makovyak
Vytaliy Makovyak

Reputation: 98

Usually we have something like

data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==

So, after first comma all data will be pure file source. Below we are removing first part "data:text/plain;base64" and after make a glue string again, as commas can be in the middle of string, for example. So, providing the code:

$file = explode(',', $file);
unset($file[0]);
$file = implode(',', $file);

Another variant is to find first comma by substr or like that and just cut this part of text, maybe it works faster than implode/explode.

With result, you can store the file:

file_put_contents('filename.ext', base64_decode(result));

Upvotes: 1

Prib
Prib

Reputation: 88

$image_content = base64_decode(str_replace("data:image/png;base64,","",$imageURL)); // remove "data:image/png;base64,"
$tempfile = tmpfile(); // create temporary file
fwrite($tempfile, $image_content); // fill data to temporary file
$metaDatas = stream_get_meta_data($tempfile);
$tmpFilename = $metaDatas['uri'];

Now you can use that image into fpdf like:

$pdf->Image($tmpFilename,null,null,0,0);

Or you can specify image type by adding image type parameter like this:

$pdf->Image($tmpFilename,null,null,0,0,'PNG');

Please check to http://www.fpdf.org/en/doc/image.htm

Upvotes: 2

Related Questions