Mango D
Mango D

Reputation: 473

Load an image blob from MySQL into PDF with PDFlib (PHP)

I want to fetch my image blob from MySQL and paste it in a PDF with PDFlib. How can I transform the blob so that I can use it as a normal image for PDFlib?

This is the way I am trying to do it at the moment.

$img = imagecreatefromstring($qra['photo']); //$qra['photo'] is the mysql blob field

// Loading the image with PDFlib (this code is already tested with a normal image src like /images/example.jpg and works)
$image = $p->load_image("auto", $img, "");
$p->fit_image($image, 10, 10, "boxsize={50 50} position=center fitmethod=meet");

Somehow the image is not created properly with imagecreatefromstring because I get an error with that code.

How do I fetch the blob image properly so that I can use it (save it on the server as a tmp image would also work)?

Upvotes: 0

Views: 1084

Answers (2)

Rainer
Rainer

Reputation: 2185

this is more simple. I expect you have your image as a byte array stored in the database. So it should be simple, when you just retrieve the BLOB field as string and use PVF (PDFlib Virtual Filesystem). With this technique, you give your variable a name, which can be used afterwards for the load_image() call.

This is demonstrated in the starter_pvf.php sample, which is included in the PDFlib PHP packages as well in the PDFlib Coobkook: http://www.pdflib.com/pdflib-cookbook/general-programming/starter-pvf/php-starter-pvf/

The sample just read the image data from disc, but this should be similar to fetching it from the database

# We just read some image data from a file; to really benefit
# from using PVF read the data from a Web site or a database instead

$imagedata = read_file("../input/PDFlib-logo.tif");
$p->create_pvf("/pvf/image", $imagedata, "");

# Load the image from the PVF
$image = $p->load_image("auto", "/pvf/image", "");

Upvotes: 1

alistaircol
alistaircol

Reputation: 1453

I think something like this will work for you:

<?php

$img = imagecreatefromstring($qra['photo']); //$qra['photo'] is the mysql blob field

ob_start(); // capture the image from the blob
imagepng($img); //  Output a PNG image to either the browser or a file
$img = ob_get_clean(); // Get current buffer contents and delete current output buffer

// img should now be png resource

// Loading the image with PDFlib (this code is already tested with a normal image src like /images/example.jpg and works)
$image = $p->load_image("auto", $img, "");
$p->fit_image($image, 10, 10, "boxsize={50 50} position=center fitmethod=meet");

Upvotes: 1

Related Questions