PHPExcel more than one image in a cell - php

I need to create an excel document with only 2 col. The first one will contain multiple images 150px large and the seconde one will contain a web code. For some reason only one image is added and the file appears to be currupted. Not sure what i am doing wrong ...
<?php
include("../../init.php");
if (is_numeric($_GET[groupe])){
define( 'PCLZIP_TEMPORARY_DIR', $_CONFIG['upload']['root'].'/cache' );
// filename for download
$groupe = mysql_query("SELECT * FROM photographe_groupe WHERE id='$_GET[groupe]'");
$records = "Groupe - $groupe[nom].xlsx";
header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition:inline;filename='.$records);
$workbook = new PHPExcel;
$sheet = $workbook->getActiveSheet();
$i=0;
$select = mysql_query("SELECT * FROM photographe_images WHERE sid='$_GET[groupe]' group by `paire`");
while($photo = mysql_fetch_array($select)){
// Table header
if ($i=="1"){
$sheet->setCellValue("A1",'Photo(s)');
$sheet->setCellValue('B1','Code Web');
$i++;
}
// Set images in col 1
$select1 = mysql_query("SELECT * FROM photographe_images WHERE paire='$photo[paire]'");
while($photo1 = mysql_fetch_array($select1)){
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName($photo1[img]);
$objDrawing->setDescription($photo1[img]);
$objDrawing->setWorksheet($workbook->getActiveSheet());
$objDrawing->setPath($_CONFIG['upload']['root'].'/userfiles/photos/'.$photo1[img]);
$objDrawing->setWidth(150);
$objDrawing->setCoordinates('A'.$i);
}
// Set web code in col 2
$sheet->setCellValue("B$i",$photo[code_web]);
$i++;
}
}
$workbook->getActiveSheet()->getRowDimension(1)->setRowHeight(-1);
$writer = new PHPExcel_Writer_Excel2007($workbook);
PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);
$writer->save('php://output');
?>
You can download and output demo here

Just a few points to note before I try taking a look at your file:
The first point to note here is that Excel doesn't store images in cells, it "overlays" images, and doesn't particularly care where cell boundaries occur, so an image can be a fixed size irrespective of how many cells it overlays
When you specify a coordinate for a image, you're relating the top-left corner of that image to be placed at the top-left corner of that cell.... where the bottom and/or right corner of the image lies isn't determined by the cells at all. Setting the row height or column width to autosize will not be affected by the image in any way, because the image is overlaid, not a content of the cell
You can, offset the image from the top-left corner of the related cell by using the Drawing object's setOffsetX() and setOffsetY() methods.
You can link more than one image to be placed relative to the same cell's top-left corner using different offset values so they don't overlap, but you need to work out the offsets from the size of the images

Related

Auto sized the cell width with text width using FPDF

I am beginning to use the FPDF to export the pdf from the Mysql. Now that i can export the pdf. I have referenced this link and this link, but I still cannot change the cell width and text width.
Could anyone provide any suggestions? Thank you very much.
<?php
require('mysql_table.php');
class PDF extends PDF_MySQL_Table
{
function Header()
{
//Title
$this->SetFont('Arial','',18);
$this->Cell(0,6,'Test',0,1,'C');
$this->Ln(10);
//Ensure table header is output
parent::Header();
}
}
mysql_connect('localhost','root','');
mysql_select_db('test');
$query = "SELECT * FROM test";
$result = mysql_query($query) or die(mysql_error());
$rowCount = 2;
while($row = mysql_fetch_array($result)){
$thisid = $row['ID'];
$fileName =$row['name'];
$filepath = $row['path'];
$date = $row['date'];
$rowCount++;
}
$pdf=new PDF('P','mm',array(1000,1500));
$pdf->AddPage();
$pdf->Table('select * from test');
$pdf->AddPage();
$pdf->SetFont('Arial','',14);
$pdf->Cell('','',$thisid,1);
$pdf->Cell('','',$fileName,1);
$pdf->Cell('','','','','','',false,$filepath);
$pdf->Cell('','',$date);
$pdf->Output();
?>
Check the below answer to set cell width
Inserting an image with PHP and FPDF, failed to load big image
As per your question you may need to pass width and height like below to cell() function
$pdf->cell(1000,1000,'',$pdf->Image($image,10,10,235,$height*18/100),'PNG');
This is to resize the cell and load img into the same
you can use this code to solve this problem... here the concept is only if string size greater than your cell width then font size will reduce.
Note that you can not use this code for a multi-line string. for this, you have to use MultiCell()
$table_head1=array(25,46,40,20,60);
$table_head2=array(25,20,26,20,20,16,24,40);
// some code remove from here for show actual code.
$pdf->CellFit($table_head2[7],$table_height,$item['remark'],1,0,'C',0,'',1,0);
use this link
how to auto adjust cell width in fpdf using php and mysql

Use PHP to create embossing effect: add white border to bottom edges and black border to other edges, rest of image should be 5% black

I would like to know if it is possible to use PHP to create an embossing effect on a user uploaded logo.
The effect (according to the Photoshop department) could be achieved by transforming the contents of the logo to all black (so it will be one color), and make that 'layer' 5% filled (so basically it becomes 95% transparent). After that they would add a black border to the top/left/right edges of the logo, and a white border to the bottom edge of the logo. And just the edges, not the outside of the image itself; the edges of the content of the logo needs to be traced.
As I am not well known in image processing, I was wondering if some PHP expert could help me out/point me in the right direction on how to do this?
So to sum it up, what I need is 4 things:
Convert contents of image to all black (but keep transparency)
Make the image 95% transparent
Add a black border to the top/left/right edges of contents of image
Add a white border to the bottom edges of contents of image
If this could be achieved in CSS for browsers from IE10 and up, it would be a good solution as well. Thanks in advance!
EDIT
Here is an example of a logo created by the artists, on top of an image/background/pattern: http://picpaste.com/embos-example-ngxfSAj5.png - they did it in a bit different way as they first told me they would do :) in Photoshop they added a inner shadow in black from the top to down, and a drop shadow in white from bottom to top
It seems I was not asking the right questions.. When translating the effect from Dutch (Preeg) to English, I thought I was in need of an embossing effect.. But I found that the PHP function shadeImage was what I wanted. In order to help other people, I'll post what I did to achieve this.
To use shadeImage, you have to supply a black/white image. That is where I went wrong when first trying out that function. So I first made a function to translate an image to black/grey/white, based on the alpha channel of each pixel. After that I used shadeImage. The resulting image did have a background, that had to be removed. I tried using things like paintTransparentImage, but that did not work in all my tests, so I made a custom function, by looping over each pixel once again. And finally I set all pixels to an alpha channel value of 0.35, to make the image a bit 'softer' and usable on a background. Here is the complete function:
public function createEmbossedLogo($imagePath, $embossedFilePath) {
// initialize Imagick and load the image
$imagick = new \Imagick(realpath($imagePath));
// make sure we are using PNG, so we can use the alpha channel
$imagick->setImageFormat('png');
// resize the logo, so we do not have to process too many pixels
$imagick->resizeImage(200, null,\Imagick::FILTER_CATROM,1);
// if the image does not have any margin around the content,
// the shade would be cut off at the sides,
// so we add an invisible border of 5 pixels, to add some margin
$imagick->borderImage('rgba(255,0,0,0)',5, 5);
// now we have to convert the image to a black/white image, using only the alpha channel
// and use the alpha channel value as the R/G/B channel values
// load the pixels of the image
$imageIterator = $imagick->getPixelIterator();
foreach ($imageIterator as $row => $pixels) { /* Loop through pixel rows */
foreach ($pixels as $column => $pixel) { /* Loop through the pixels in the row (columns) */
/** #var $pixel \ImagickPixel */
$nor_color = $pixel->getColor(true); //normalized color
// the alpha channel will be 0 if it is completely invisible and 1 if visibile
// but can be any value in between 0-1
// by using the alpha channel as the white/grey/black value, we create an alpha map
$alpha = $nor_color['a'];
$rgbValue = $alpha*255;
$pixel->setColor('rgba('.$rgbValue.','.$rgbValue.','.$rgbValue.',1');
}
$imageIterator->syncIterator(); /* Sync the iterator, this is important to do on each iteration */
}
// add the shading, the first parameter makes sure that all the 'to be removed' pixels
// are the same color, so we can find them in the next loop through all pixels
// they would otherwise be black, one of the colors we do need to keep in the result
$imagick->shadeImage(true,270,45);
// the shadeImage function will make all the pixels grey that should be transparent
// so we loop over all the pixels in the image once again to remove them
$imageIterator = $imagick->getPixelIterator();
$colorFound = false;
$colorRange = 10;
foreach ($imageIterator as $row => $pixels) { /* Loop through pixel rows */
foreach ($pixels as $column => $pixel) { /* Loop through the pixels in the row (columns) */
/** #var $pixel \ImagickPixel */
$color = $pixel->getColor(); //normalized color
if (!$colorFound) {
// since added some margin around the image, we can take the first pixel
// of the top left corner, and use it as the color to make transparent
// and since the image is in black/white, we only need one 'color' channel
$colorFound = array();
$colorFound['r'] = $color['r'];
}
// the default alpha for pixels to keep is 1
$alpha = 1;
// see if the color of this pixel is close to that of the 'color to be deleted'
// if so, we will not totally delete it, but change the alpha channel accordingly
$diff = abs($color['r']-$colorFound['r']);
if ($diff<=$colorRange) {
// set alpha value for this pixel, based on the difference from the removed color
$alpha = $diff / $colorRange;
}
// the entire opacity of the image has to brought down, to make the image a bit 'softer'
$alpha *= 0.35;
// this pixel matches the 'to be removed' color, so we set it to a new value with alpha 0
$pixel->setColor('rgba('.$color['r'].','.$color['g'].','.$color['b'].','.$alpha.')');
}
$imageIterator->syncIterator(); /* Sync the iterator, this is important to do on each iteration */
}
// remove any excess margins that are not needed
$imagick->trimImage(0);
// store the image
$imagick->writeImage($embossedFilePath);
}

PHP Merge images (white color = transparency)

How to merge images if in image color white get transparency status white color?
I have this situation:
I need this result:
This is not a best result, since I didn't know better method to achieve this. Here is my result:
Here is the PHP:
<?php
/** Set source image location **/
$baseImageSource = 'http://q/stock-photos/tux.png';
$overlayImageSource = 'http://q/stock-photos/firefox-logo-small.jpg';
/** Overlay image configuration **/
// Set this value between 0 and 100. 10 will doing great
$fuzz = 10;
// Set position of overlay image, from top and left;
$overlayTop = 240;
$overlayLeft = 200;
/** Core program **/
// Create Imagick object for source image
$overlayImage = new Imagick( $overlayImageSource );
$finalImage = new Imagick( $baseImageSource );
// Remove overlay image background
$overlayImage->paintTransparentImage(
$overlayImage->getImagePixelColor( 0, 0 ),
0, round( $fuzz * 655.35 )
);
// Set image overlay format
$overlayImage->setImageFormat('png');
// Put overlay image to base image
$finalImage->compositeImage(
$overlayImage, Imagick::COMPOSITE_DEFAULT,
$overlayLeft,
$overlayTop
);
// Set output image format
$finalImage->setImageFormat('png');
// Prepare image and publish!
header('Content-type: image/png');
echo $finalImage;
Basically this is just a modification of this answer (to achieve image merger) and this answer (to achieve background removal). The method used to remove background is Imagick::paintTransparentImage(), with Imagick::getImagePixelColor() is used to detect background color. Then we just need to merge both image with Imagick::compositeImage().
But still, this result is far from perfect, especially if you compare it with image processing app like GIMP or Photoshop. But you should give it a try. Hope it helps :)
You need to use a program like Gimp, add a transparency layer, delete the white from the firefox image, and save as PNG.

Mpdf Barcode size is too big. want to fix height and width

I am trying to create barcode using mpdf. while creating, its automatically changing height and width. Please give me solution to fix height and width even though characters are different.
<barcode code="abcdefghijklmnopqrstuvwxyz1234" type="C39E+"
class="barcode" size="3" height="3" />
want to generate 5 barcodes on a page with equal space.
page size 50*100mm.
According to mpdf documentation and examples provided when you download the scripts from their website: http://www.mpdf1.com/mpdf/index.php?page=Download
If you have a look at their barcode example example37_barcodes.php (examples/example37_barcodes.php), if you want to modify the size for the C39E+ barcode type you will have to do this:
These barcodes are all of variable length depending on the code entered. There is no recommended maximum size for any of these specs, but all recommend a minimum X-dimension (width of narrowest bar) as 7.5mil (=0.19mm). The default used here is twice the minimum i.e. X-dim = 0.38mm.
The specifications give a minimum height of 15% of the barcode length (which can be variable). The bar height in mPDF is set to a default value of 10mm. 'size' will scale the barcode in both dimensions. mPDF will accept any number, but bear in mind that size="0.5" will set the bar width to the minimum. The 'height' attribute further allows scaling - this factor is applied to already scaled barcode. Thus size="2" height="0.5" will give a barcode twice the default width (X-dim=0.76mm) and at the default height set in mPDF i.e. 10mm.
The results may vary according to the value passed to the barcode class, so I think if you want a fixed width and height you should try an external library that creates an barcode image file with the desired size or forcing the barcode to adjust to a fixed row or div in a table.
I had the same problem and tried the following using an external library passing values to a function:
$codigoBarras = "<img src='barcode/script/html/image.php?code=code128&o=1&t=12&r=1&text=$productoID&f1=Arial.ttf&f2=0&a1=A&a2=' width='110' height='25'>";
image.php file:
<?php
if(isset($_GET['code']) && isset($_GET['t']) && isset($_GET['r']) && isset($_GET['text']) && isset($_GET['f1']) && isset($_GET['f2']) && isset($_GET['o']) && isset($_GET['a1']) && isset($_GET['a2'])){
define('IN_CB',true);
require('config.php');
require($class_dir.'/index.php');
require($class_dir.'/FColor.php');
require($class_dir.'/BarCode.php');
require($class_dir.'/FDrawing.php');
require($class_dir.'/Font.php');
if(include($class_dir.'/'.$_GET['code'].'.barcode.php')){
if($_GET['f1'] !== '0' && intval($_GET['f2']) >= 1){
$font = new Font($class_dir.'/font/'.$_GET['f1'], intval($_GET['f2']));
} else {
$font = 0;
}
$color_black = new FColor(0,0,0);
$color_white = new FColor(255,255,255);
if(!empty($_GET['a2']))
$code_generated =& new $_GET['code']($_GET['t'],$color_black,$color_white,$_GET['r'],$_GET['text'],$font,$_GET['a1'],$_GET['a2']);
elseif(!empty($_GET['a1']))
$code_generated =& new $_GET['code']($_GET['t'],$color_black,$color_white,$_GET['r'],$_GET['text'],$font,$_GET['a1']);
else
$code_generated =& new $_GET['code']($_GET['t'],$color_black,$color_white,$_GET['r'],$_GET['text'],$font);
$drawing =& new FDrawing('',$color_white);
$drawing->add_barcode($code_generated);
$drawing->draw_all();
$drawing->finish(intval($_GET['o']));
}
else{
header('Content: image/png');
readfile('error.png');
}
}
else{
header('Content: image/png');
readfile('error.png');
}
?>
<barcode type="EAN13" code="978-0-9542246-0" text="0" class="barcode" size="1" height="0.5"/>
always size ='1'

display image thumbnail by reading path from table and retrieving the image from folder

I would be grateful if anybody could help me out with this.
I have a table which stores the filepath of a set of images, e.g col filepath stores values like: ./phpimages/image3.jpg. Note that my images are stored in folder 'phpimages'
Now i want to loop through all the rows in my table and display thumbnails of the images.
Here is my code:
/
*************************Display all records from images table***************/
//create an instance is Image
$objImage = new Image;
$result = $objImage -> listImage();
$num_rows = mysql_num_rows($result);
//echo $num_rows."records in database";
while($row = mysql_fetch_assoc($result)){
$imagepath="'".$row["filepath"]."'"; // note that if i put $imagepath= "dog.jpg", it displays the image just once!
//set mime type content
header('Content-Type: image/jpeg');
//create original image
$image = imagecreatefromjpeg($imagepath);
//get image dimension
$dim=getimagesize($imagepath);
//Set thumb dimension
$thumbw = 100;
$thumbh = 130;
//create empty image
$thumb_image=imagecreatetruecolor($thumbw, $thumbh);
//Resize original image and copy it to thumb image
imagecopyresampled($thumb_image, $image, 0, 0, 0, 0,
$thumbw, $thumbh, $dim[0], $dim[1]);
//display thumb image
imagejpeg($thumb_image);
}
?>
Please can anyone tell me where my error lies? Many thanks for any help provided
Why not just use <img src="">
You can output only one imagejpeg($thumb_image); using this method. If you want to display all thumbnails in a combined image, you should merge your images to one PHP/GD image, and then output that one.
If you would like to output thumbnail images, then I advise you to use the following tool:
http://phpthumb.sourceforge.net/
So when you iterate through your images, you should output an <img src="" /> for each thumbnail.

Categories