Convert Image Data URI to Image PHP - 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.

$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

Related

How can Fopen read png files in php

I was working on something and I needed the data out of a png file and I can only use PHP. Don't ask why just give me the answer lol
Lets suppose below is your image.
You have to define its url in a variable using the below line
$image = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
after that you can use file_get_content function to get data/content of image.
$image_content = file_get_contents($image);
also, if you want to convert it into base64 string, you can use base64_encode function.
$image_base64Data = base64_encode($image_content);
Whole Code will be ......
<?php
$image = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
$image_content = file_get_contents($image);
$image_base64Data = base64_encode($image_content);
?>

Image from database into PDF using FPDF

I have an image that is sent from an iPad app to an SQL database. I can retrieve this image and display in a web page using the following php:
$img = base64_encode($row['photoData']);
echo "<img src=\"data:image/jpg;charset=utf8;base64, $img\"/>";
This displays fine. What I want to do now is put this image into a PDF document using FPDF however I am struggling to do this.
This:
$img = base64_encode($row['photoData']);
$pdf->Image($img);
give this error:
FPDF error: Image file has no extension and no type was specified:
So I tried this (although I realise I will then have to look at how to get the size of the image sorted):
$pdf->Image($img, 20, 20, 20, 20 'JPG');
which give me:
FPDF error: Missing or incorrect image file:
What is the correct way to do this?
Or would it be easier to temporarily save the image to the server and then place the saved image into the PDFdoc?
As mentioned in the comments above this is possible by using a stream ("data url") to hand over the image data to the fpdf library without writing physical files to disk:
<?php
// load the 'fpdf' extension
require('fpdf.php');
// just for demonstration purpose, the OP gets the content from a database instead
$h_img = fopen('img.jpg', "rb");
$img = fread($h_img, filesize('img.jpg'));
fclose($h_img);
// prepare a base64 encoded "data url"
$pic = 'data://text/plain;base64,' . base64_encode($img);
// extract dimensions from image
$info = getimagesize($pic);
// create a simple pdf document to prove this is very well possible:
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello Image!');
$pdf->Image($pic, 10, 30, $info[0], $info[1], 'jpg');
$pdf->Output();
If this is a good advice is another question, this is merely meant to prove that this is possible...
According to the Docs FPDF::Image accepts a filename as the first argument, not a binary blob.
If you want to use FPDF specifically, save the image to a temporary file first, and then pass that to FPDF::Image.
To do that, something like this should work:
$tmpFile = tempnam(sys_get_temp_dir(), 'fpdfimg');
if (file_put_contents($tmpFile, $row['photoData'])) {
$fpdf->Image($tmpFile);
// save/display image
unlink($tmpFile);
}
Alternatively, if you want to just serve the image as a PDF (with no other content) you could use Imagick:
$im = new \Imagick();
$im->readImageBlob($row['photoData']);
$im->setImageFormat('pdf');
header('Content-Type: application/pdf');
echo $im;
Since FPDF cannot use base64 data to produce images on the PDF, I would recommend saving the file to the disk permanently as opposed to writing a temp file for every PDF operation.
This will save you a lot of I/O overhead.
Assuming your table has unique photo_id or photo_name to accompany photoData then you can use something like this to create your images and use them in FPDF.
I will also assume you have a last_update and photo_extension column.
<?php
$path = '/path/to/fpdf/images/';
$filename = $row['photo_id'].'.'.$row['photo_extension'];
$filepath = $path.$filename;
// If a physical file is not available then create it
// If the DB data is fresher than the file then make a new file
if(!is_file($filepath) || strtotime($row['last_update']) > filemtime($filepath))
{
$result = file_put_contents($filepath, $row['photoData']);
if($result === FALSE)
{
die(__FILE__.'<br>Error - Line #'.__LINE__.': Could not create '.$filepath);
}
}
$pdf->Image($filepath);
If you plan on updating the photoData which is stored in your DB then you will have to make sure to also have a timestamp column and compare that timestamp against the filemtime($filepath) of the image on your disk.
Another solution for this ;)
Make a new php by copying and pasting this (piece of fpdf's code edited):
require('fpdf.php');
class DATAIMAGE extends FPDF
{
protected function _parsedata($file)
{
// Extract info from a JPEG file
$a = getimagesizefromstring($file);
if(!$a)
$this->Error('Missing or incorrect image file: '.$file);
if($a[2]!=2)
$this->Error('Not a JPEG file: '.$file);
if(!isset($a['channels']) || $a['channels']==3)
$colspace = 'DeviceRGB';
elseif($a['channels']==4)
$colspace = 'DeviceCMYK';
else
$colspace = 'DeviceGray';
$bpc = isset($a['bits']) ? $a['bits'] : 8;
return array('w'=>$a[0], 'h'=>$a[1], 'cs'=>$colspace, 'bpc'=>$bpc, 'f'=>'DCTDecode', 'data'=>$file);
}
}
Then call this php instead of fpdf.php in your main php.
You'll now be able to display an image simply by adding 'data' to the end of the function:
$pdf->Image($mysqlrow["blob"],0,0,40,0,'data');

how to add the logo into csv file using ECSVExport in yii?

Yii::import('application.extensions..ECSVExport');
$filename = 'filename.csv';
$csv = new ECSVExport($sheet_generation);
$csv->setOutputFile($outputFile);
$imageUrl = Yii::app()->request->baseUrl.'/themes/optisol/images/resign-icon.png';
$num = cal_days_in_month(CAL_GREGORIAN, $month,$year);
$heading="Attendance for 01"."-".$month."-".$year." To ".$num."-".$month."-".$year." ";
$content=$heading;
$content = $content.$csv->toCSV();
Yii::app()->getRequest()->sendFile($filename, $content, "text/csv", false);
It cannot be done. Not in the way you asked, actually.
A CSV is a text file, and therefore cannot have embedded images like a word processor document can.
If we want the image in the file, you will have to put the file name in the document. Then, the person reading the document can decide what to do with the file name.
A file will look this:
id, name, image, email
1,'Tom', 'image1.png', 'user1#domain.com'
1,'Jones', 'image2.png', 'user2#domain.com'

file upload error using codeigniter

I am tryin to upload file in mysql database using php with codeigniter framework.
Following my code. Its just saving first name of file in database but actual file in not storing at the given path.
My code is -
move_uploaded_file($_FILES["userfile"]["tmp_name"] , "uploads/diagnosis_report/".$_FILES["userfile"]["name"]);
$data['file_name'] = $_POST["userfile"]["name"];
I believe:
$data['file_name'] = $_POST["userfile"]["name"];
Should be:
$data['file_name'] = $_FILES["userfile"]["name"];
// ---------------------^
$upload_path$_POST["userfile"]["name"] is just the file name. If you want to save it with the path you need to do something like this:
// For relative path
$data['file_name'] = "uploads/diagnosis_report/".$_FILES["userfile"]["name"];
// For absolute path
$data['file_name'] = dirname(__FILE__)."/uploads/diagnosis_report/".$_FILES["userfile"]["name"];
Honestly what I would do is set an upload path variable first like so:
$upload_path = dirname(__FILE__)."/uploads/diagnosis_report/";
Then you can use it over and over again like so:
move_uploaded_file($_FILES["userfile"]["tmp_name"] , $upload_path.$_FILES["userfile"]["name"]);
$data['file_name'] = $upload_path.$_FILES["userfile"]["name"];
Hope this helps.

Embedding IPTC image data with PHP GD

I'm trying to embed a IPTC data onto a JPEG image using iptcembed() but am having a bit of trouble.
I have verified it is in the end product:
// Embed the IPTC data
$content = iptcembed($data, $path);
// Verify IPTC data is in the end image
$iptc = iptcparse($content);
var_dump($iptc);
Which returns the tags entered.
However when I save and reload the image the tags are non existant:
// Save the edited image
$im = imagecreatefromstring($content);
imagejpeg($im, 'phplogo-edited.jpg');
imagedestroy($im);
// Get data from the saved image
$image = getimagesize('./phplogo-edited.jpg');
// If APP13/IPTC data exists output it
if(isset($image['APP13']))
{
$iptc = iptcparse($image['APP13']);
print_r($iptc);
}
else
{
// Otherwise tell us what the image *does* contain
// SO: This is what's happening
print_r($image);
}
So why aren't the tags in the saved image?
The PHP source is avaliable here, and the respective outputs are:
Image output
Data output
getimagesize has an optional second parameter Imageinfo which contains the info you need.
From the manual:
This optional parameter allows you to extract some extended information from the image file. Currently, this will return the different JPG APP markers as an associative array. Some programs use these APP markers to embed text information in images. A very common one is to embed » IPTC information in the APP13 marker. You can use the iptcparse() function to parse the binary APP13 marker into something readable.
so you could use it like this:
<?php
$size = getimagesize('./phplogo-edited.jpg', $info);
if(isset($info['APP13']))
{
$iptc = iptcparse($info['APP13']);
var_dump($iptc);
}
?>
Hope this helps...

Categories