I am able to successfully resize (to the proper resized dimensions) an image that I have created from one page of a pdf document. However, I do not understand why the result is a dark resized image with a patch of white. Please, can someone advise?
PHP code:
// Create image from first page of pdf document
$im = new imagick('1Mpublic.pdf[0]');
$im->setImageFormat('jpg');
$imageHeight = $im -> getImageHeight();
$imageWidth = $im -> getImageWidth();
$desiredImgWidth = 200;
$desiredImgHeight = resizedImageHeight($imageWidth, $imageHeight,
$desiredImgWidth);
$im -> resizeImage($desiredImgWidth, $desiredImgHeight,
imagick::STYLE_NORMAL, 1);
// Save image
$page = '1';
$saveToFolder = 'thumbnailFolder';
$fileName = 'thanhThumbNail_'.$page.'.jpg';
$saveImgToPath = $saveToFolder.'/'.$fileName;
$result = file_put_contents($saveImgToPath, $im);
function resizedImageHeight($imgWidth, $imgHeight, $desiredImgWidth){
$quoient = $imgWidth/$imgHeight;
$height = $desiredImgWidth/$quoient;
return $height;
}
Resulting thumbnail image:
Link to original PDF can be found here:
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4905263/pdf/ksgt-06-04-1091539.pdf
Your PDF has transparency. JPG does not support transparency and shows black where the PDF was transparent. Just turn the transparency off. In Imagemagick command line:
convert -density 300 ksgt-06-04-1091539.pdf[0] -alpha off result.jpg
See setImageAlphaChannel at http://us3.php.net/manual/en/imagick.setimagealphachannel.php
Looks like the background color is not defined. You need to set the background color before reading the PDF document.
// Create image from first page of pdf document
$im = new imagick();
$im->setBackgroundColor('WHITE');
$im->readImage('1Mpublic.pdf[0]');
$im->setImageFormat('jpg');
Related
<?php
// Set the font file and font size for the text
$font_file = '/path/to/font.ttf';
$font_size = 12;
// Create an array of image filenames
$images = array('image1.png', 'image2.png', 'image3.png', 'image4.png', 'image5.png');
// Select a random image filename from the array
$random_image = $images[array_rand($images)];
// Load the image using the GD library
$image = imagecreatefrompng($random_image);
// Get the width and height of the image
$width = imagesx($image);
$height = imagesy($image);
// Send the appropriate HTTP headers and output the image
header('Content-Type: image/png');
imagepng($image);
// Free up memory
imagedestroy($image);
?>
*The code works fine, don't get any errors but when I load the code I get this small white square and nothing else. GD is enabled, but don't know how to solve this solution. *
I followed this example to embed text in image while uploading it but it's not working.
This is my code:
header('Content-type: image/jpeg');
$img = $_FILES['mainImage']['name'];
list($txt, $ext) = explode(".", $img);
$imgName = "ac_".time().".".$ext;
$tmp = $_FILES['mainImage']['tmp_name'];
$textToImage = imagecreatefromjpeg($tmp);
// Allocate A Color For The Text
$white = imagecolorallocate($textToImage, 255, 255, 255);
// Set Path to Font File
$font_path = '../assets/fonts/font.ttf';
// Set Text to Be Printed On Image
$text = "Test text";
// Print Text On Image
imagettftext($textToImage, 25, 0, 75, 300, $white, $font_path, $text);
$imageUploaded = move_uploaded_file($tmp, 'images_path/'.$imgName);
if(!$imageUploaded){
die('Error upload image!');
}
The image is uploaded but wihout text in it !
For this we are working with GD library.
"PHP is not limited to creating just HTML output. It can also be used
to create and manipulate image files in a variety of different image
formats, including GIF, PNG, JPEG, WBMP, and XPM. Even more
convenient, PHP can output image streams directly to a browser. You
will need to compile PHP with the GD library of image functions for
this to work. GD and PHP may also require other libraries, depending
on which image formats you want to work with."
You can use the image functions in PHP to get the size of JPEG, GIF, PNG, SWF, TIFF and JPEG2000 images.
The following code sample demonstrates the use of GD library to watermark images on the fly. The method demonstrated here to watermark an uploaded image is to overlay the original image with another image, preferably a transparent PNG image.
PHP provides a rich set of functions to create and alter images on the fly. These functions require the GD library, which is bundled with PHP since version 4.3.
The HTML form needs a file upload element: <input type="file">. You must also specify the correct encoding type: enctype="multipart/form-data" for the form.
/ link to the font file no the server
$fontname = 'font/Capriola-Regular.ttf';
// controls the spacing between text
$i=30;
//JPG image quality 0-100
$quality = 85;
function create_image($user){
global $fontname;
global $quality;
$file = "covers/".md5($user[0]['name'].$user[1]['name'].$user[2]['name']).".jpg";
// if the file already exists dont create it again just serve up the original
if (!file_exists($file)) {
// define the base image that we lay our text on
$im = imagecreatefromjpeg("pass.jpg");
// setup the text colours
$color['grey'] = imagecolorallocate($im, 54, 56, 60);
$color['green'] = imagecolorallocate($im, 55, 189, 102);
// this defines the starting height for the text block
$y = imagesy($im) - $height - 365;
// loop through the array and write the text
foreach ($user as $value){
// center the text in our image - returns the x value
$x = center_text($value['name'], $value['font-size']);
imagettftext($im, $value['font-size'], 0, $x, $y+$i, $color[$value['color']], $fontname,$value['name']);
// add 32px to the line height for the next text block
$i = $i+32;
}
// create the image
imagejpeg($im, $file, $quality);
}
return $file;
}
function center_text($string, $font_size){
global $fontname;
$image_width = 800;
$dimensions = imagettfbbox($font_size, 0, $fontname, $string);
return ceil(($image_width - $dimensions[4]) / 2);
}
$user = array(
array(
'name'=> 'Slimen Tunis',
'font-size'=>'25',
'color'=>'black'),
array(
'name'=> 'Web developer',
'font-size'=>'16',
'color'=>'grey'),
array(
'name'=> 'SlimenTunis#webdeveloper.com',
'font-size'=>'13',
'color'=>'green'
)
);
// run the script to create the image
$filename = create_image($user);
here we have two functions to make it as simple as possible. To run the code simply pass the $user array data to the function and it’ll save the new image in the folder ‘covers’ on your server. The function returns the file url so you just need to echo it into an image tag as shown below. Check out the demo where you can create your own.
$filename = create_image($user);
<img src="<?=$filename;?>" width="800" height="600"/>
You can try using the Intervention library. I use it for doing what you're asking about. It is quite simple to understand and the documentation is is well-written.
Having a few teething problems watermarking a photo. It all works fine apart from the watermarked photo's colors become duller than they should be - very noticeable in-fact.
I'm using imagecopyresized to do my watermarking, as this specifically allows me to use PNG-24 watermarks, the others do not. I know the colors are usually OK, as I have just used readfile($url) as a test, and the photos are perfect.
Here is my script:
<?php
// get parent and watermark images & sizes
$image = imagecreatefromjpeg($url);
$imageSize = getimagesize($url);
$watermark = imagecreatefrompng('watermark.png');
$watermark_o_width = imagesx($watermark);
$watermark_o_height = imagesy($watermark);
// calculate new watermark width and position
if ($imageSize[0] > $imageSize[1] || $imageSize[0] == $imageSize[1]) {
$leftPercent = 23;
} else {
$leftPercent = 7;
}
$leftPixels = ($imageSize[0]/100)*$leftPercent;
$newWatermarkWidth = $imageSize[0]-$leftPixels;
$newWatermarkHeight = $watermark_o_height * ($newWatermarkWidth / $watermark_o_width);
// place watermark on parent image, centered and scaled
imagecopyresized(
$image,
$watermark,
$imageSize[0]/2 - $newWatermarkWidth/2,
$imageSize[1]/2 - $newWatermarkHeight/2,
0,
0,
$newWatermarkWidth,
$newWatermarkHeight,
imagesx($watermark),
imagesy($watermark)
);
// print
imagejpeg($image);
// destroy
imagedestroy($image);
imagedestroy($watermark);
?>
How can I stop this from happening? I'm reading about imagecreatetruecolor, does that solve the issue? I'm Googling "imagecreatetruecolor color loss photos" and variations but nobody really talks about this issue. If I do need this function, where would I add that to this script?
This has totally thrown a spanner in the works for me and would love for somebody to tell me where to stick it (not literally).
Here is an example of the color loss. The preview image should be exactly the same colors as the thumbnail. The thumbnails are created using readfile() whereas the previews are created using imagecreatefromjpeg and imagecopresized.
This example code works fine, by using the same characteristics as your images:
Original JPG: dark background; beautiful girl; red dress.
Watermark PNG: transparent background; text; gray color.
<?php
// Path the the requested file (clean up the value if needed)
$path = $url;
// Load image
$image = imagecreatefromjpeg($path);
$w = imagesx($image);
$h = imagesy($image);
// Load watermark
$watermark = imagecreatefrompng('watermark.png');
$ww = imagesx($watermark);
$wh = imagesy($watermark);
// Merge watermark upon the original image (center center)
imagecopy($image, $watermark, (($w/2)-($ww/2)), (($h/2)-($wh/2)), 0, 0, $ww, $wh);
// Output the image to the browser
header('Content-type: image/jpeg');
imagejpeg($image);
// destroy both images
imagedestroy($image);
imagedestroy($watermark);
// kill script
exit();
?>
Left: Output Image | Right: Original Image
Note:
The output image was compressed several times until: Original -> PHP Output -> GIMP -> Here.
After much testing, I came to the conclusion that PHP's GD Image does not support color profiles on the images that are being watermarked. I am now using Imagick and the colors are perfect.
I have a PHP script to re size image file as below;
$file = "test.bmp";
$ext = pathinfo($file, PATHINFO_EXTENSION);
$info = pathinfo($file);
$file_name = basename($file,'.'.$info['extension']);
$thumbname = "thumb/".$file_name.".".$ext;
$maxh = 200;
$maxw = 200;
$quality = 100;
list($width,$height)=getimagesize($file);
$src = imagecreatefromwbmp($file);
$tmp = imagecreatetruecolor($maxw,$maxh);
imagecopyresampled($tmp,$src,0,0,0,0,200,200,$width,$height);
imagejpeg($tmp,$thumbname,$quality);
imagedestroy($tmp);
The script is suppose to resize a Windows bitmap image to 200x200 thumbnail. But instead, I am getting a black 200x200 image. I am using PHP with Apache in Windows PC. How can I fix this?
.bmp and wbmp are VERY, VERY different file types.
Note the content-type headers:
Content-Type: image/x-xbitmap
Content-Type: image/vnd.wap.wbmp
Calling imagecreatefromwbmp($file) where $file is a .bmp will fail every time.
See this thread for info on how to load a .bmp file. It's not pretty.
As pointed out in PHP imagecopyresampled() docs:
Note:
There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by imagecreatetruecolor().
To see if it's the case you can use imageistruecolor() and copy the contents to a new truecolor image before "copyresampling" it:
if( !imageistruecolor($src) ){
$newim = imagecreatetruecolor( $width, $height );
imagecopy( $newim, $src, 0, 0, 0, 0, $width, $height );
imagedestroy($src);
$src = $newim;
}
There is a new opensource project on Github that allows reading and saving of BMP files (and other file formats) in PHP.
The project is called PHP Image Magician.
<?php
//Create New 'Thumbnail' Image
$newImageWidth = 200;
$newImageHeight = 200;
$newImage = imagecreatetruecolor($newImageWidth, $newImageHeight);
$newImageFile = 'output.jpg';
$newImageQuality = 100;
//Load old Image(bmp, jpg, gif, png, etc)
$oldImageFile = "test.jpg";
//Specific function
$oldImage = imagecreatefromjpeg($oldImageFile);
//Non-Specific function
//$oldImageContent = file_get_contents($oldImageFile);
//$oldImage = imagecreatefromstring($oldImageContent);
//Get old Image's details
$oldImageWidth = imagesx($oldImage);
$oldImageHeight = imagesy($oldImage);
//Copy to new Image
imagecopyresampled($newImage, $oldImage, 0, 0, 0, 0, $newImageWidth, $newImageHeight, $oldImageWidth, $oldImageHeight);
//Output to file
imagejpeg($newImage, $newImageFile, $newImageQuality);
I'm working on an image resizer, to create thumbnails for my page. The resizer works on principle of include a DIRECT link to the image. But what I want to do is put in the PHP Variable in the URL string, so that it points to that file and resizes it accordingly.
My code is as follows :
<img src="thumbnail.php?image=<?php echo $row_select_property['image_url']; ?>
Image Resize :
<?php
// Resize Image To A Thumbnail
// The file you are resizing
$image = '$_GET[image_url]';
//This will set our output to 45% of the original size
$size = 0.45;
// This sets it to a .jpg, but you can change this to png or gif
header('Content-type: image/jpeg');
// Setting the resize parameters
list($width, $height) = getimagesize($image);
$modwidth = $width * $size;
$modheight = $height * $size;
// Creating the Canvas
$tn= imagecreatetruecolor($modwidth, $modheight);
$source = imagecreatefromjpeg($image);
// Resizing our image to fit the canvas
imagecopyresized($tn, $source, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);
// Outputs a jpg image, you could change this to gif or png if needed
imagejpeg($tn);
?>
What I am trying to do is pass on the variable "image=" to the Thumbnail script. At the moment I am passing it through the URL string, but it doesnt seem to load the graphic.
I'll try expand on this more, should you have questions as I am finding it a little difficult to explain.
Thanks in advance.
I suspect at least part of the problem is that your existing...
$image = '$_GET[image_url]';
...line is creating a text string, rather than getting the contents of the 'image_url' query string. Additionally, your passing in the image name as "?image=" in the query string, so you should simply use "image", not "image_url".
As such, changing this to...
$image = $_GET['image'];
...should at least move things along.
Change it
$image = '$_GET[image_url]';
to
$image = $_GET['image'];
$image = '$_GET[image_url]';
should be
$image = $_GET['image'];