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...
Related
I am using iptcparse to fetch the IPTC data from images(jpg's) and it is also working for most of images but in some JPEGs it shows Incorrect APP1 Exif Identifier error code.
Here is the sample code:
$size = getimagesize('apple.jpg', $info);
if(isset($info['APP13']))
{
$iptc = iptcparse($info['APP13']);
echo '<pre>';
print_r($iptc);
}
I have checked metadata with Photoshop and metadata shows correctly. Can anyone share their thoughts?
public function addNewCategory($category_title, $strImage) {
// get the image from the base64 string.
$strImage = str_replace('data:image/png;base64,', '', $strImage);
$strImage = str_replace(' ', '+', $strImage);
$strImage = base64_decode($strImage);
// set the path name of where the image is to be stored.
$path = dirname(__FILE__).'/category_images/'.$category_title.".png";
// save the image in the path.
file_put_contents($path, $image);
// insert category and the image path into the MySQL database.
$result = mysqli_query($this->db->connect(), "INSERT INTO category(category_title, path, created_at) VALUES ('$category_title', '$path', NOW())");
if ($result) {
return mysqli_fetch_array($result);
} else {
return false;
}
}
After running this code I found out that the PNG file with the category title name is stored in the category_images directory. But it turns out that the size of the PNG file is zero, so I believe that there is a flaw in converting the base64 string into image.
Your tips for the correction will be very much appreciated.
Edited
The Base64 string here is encoded in Android with the following method.
public String getStringFromImage(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] imageBytes = stream.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
and here is the encoded string. I got this value using Log.i() method.
iVBORw0KGgoAAAANSUhEUgAAAlgAAAJYCAIAAAAxBA+LAAAAA3NCSVQICAjb4U/gAAAgAElEQVR4nOzd2XNcV5Im+M/dz11iwb5xkyiltlSq1VVZOVVdM9M2bdaP/TJ/7zyMWc/YzFj3dM1YV1eVVVZWKZVaKXEnloi49xx374cbACmJFEUQoCjAf0aDASAQcQMg44uzuB/Cx/8eIYQQwmXFP/cFhBBCCD+nCMIQQgiXWgRhCCGESy2CMIQQwqUWQRhCCOFSiyAMIYRwqUUQhhBCuNQiCEMIIVxqEYQhhBAutQjCEEIIl1oEYQghhEstgjCEEMKlFkEYQgjhUosgDCGEcKlFEIYQQrjUIghDCCFcahGEIYQQLrUIwhBCCJdaBGEIIYRLLYIwhBDCpRZBGEII4VKLIAwhhHCpRRCGEEK41NLPfQGvnPtTP5NYnvrl/IMvH/Tk37m1k3c4XluEEMIvyeULwhNET75TXF/s250ev0803AgR+Q+DNoQQwmvssgbhcQrS8Tue6Olf+axc02d8fQghhF+UyxeEx8E3ZKGfBJ2Wp3/9s4KQa+B4RvT4rTtAMTUaQgi/JJcwCAkA3Jd/jgmevkb4LGr2nY9jRjSEEH6ZLl8QPplYJ6EIwJ/+o/BnzYBaXt7CcCPDHhkiWCRiCCH8kly+IDxxkmFEANSqZ3zZs77/icD74d7REEIIv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U749k9YHBoniOBZncFDCCGc1vkHoRAzGQwpYW19vHetX90uWZLXUBjUoYAB5jCH1bW79+NmfOPG9XfeuHl
According to the encoded string, the data:image/png;base64, is not included in front of the string. I think now this is the reason the PNG file is not properly made. What can be done here to fix this issue?
That encoded data is the contents of the image file, and data:image/png;base64, is only used if you're cramming the image data into HTML.
Putting the data into your HTML source bloats the source, slows down your initial page load, robs the browser of the ability to download large resources like images in parallel, and makes the image un-cacheable between pages. Don't do it unless you literally have no other option.
To convert the image back to a file simply:
file_put_contents('foo.png', base64_decode($str));
Or make a PHP script pretend it's an image:
header('Content-Type: image/png');
echo base64_decode($str);
Or to do the thing I just told you not to do because seriously never do this there are so many ways to not do this, I'll be super disappointed with you if this is what you take away from this answer:
printf('<img src="data:image/png;base64,%s" />', $str);
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');
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
I'm trying to show all images within a specified directory.
The following code lists all allowed file names:
function getDirectoryList()
{
// create an array to hold directory list
$results = array();
// create a handler for the directory
$handler = opendir($this->currentDIR);
// open directory and walk through the filenames
while ($file = readdir($handler)) {
// Make sure we get allowed images types
if ($this->allowedFileType($file,$this->allowedImageTypes) )
{
$results[] = $file;
}
}
// tidy up: close the handler
closedir($handler);
// done!
return $results;
}
(...)
$images = getDirectoryList();
foreach($images as $img) {
echo "<li>".$img."</li>";
}
How can I get file size and MIME type?
I read that mime_content_typeis deprecated and I should use finfo_file istead. But I've not been very successfull with this.
Do I have to use /usr/share/misc/magic to get file information? Can't I use GD library?
I've looked at many examples, but they are old and don't work that well.
Any help appreciated.
to get the size and mime type of image its simple,
use function : getimagesize
uses like :
list($width, $height, $type, $attr) = getimagesize("img/myimg.jpg");
Returns an array with 7 elements.
Index 0 and 1 contains respectively the width and the height of the image.
Index 2 is one of the IMAGETYPE_XXX constants indicating the type of the image.
using filesize give the size in bytes
To expand on Haim Evgi's post, use getimagesize() to retrieve the dimensions and the image type in an array. Then, use image_type_to_mime_type() on the image type code to retrieve the MIME:
list ($fileWidth, $fileHeight, $fileType) = getimagesize($filename);
$fileMimeType = image_type_to_mime_type($fileType);