php thumbnail image problem (some images flipped or rotated) - php

i use php to create thumbnail of image on upload. But i have some issues. Sometimes thumbnail is fliped vertically or horizontally or 90º rotated ... and i dont know why... some images are correct some not.
Don´t you know, where could be problem?
UPDATE:
imagecreatefromjpeg load image wrong rotated...
I´m using this code...
class ThumbImage
{
private $source;
public function __construct($sourceImagePath)
{
$this->source = $sourceImagePath;
}
public function createThumb($destImagePath, $thumbWidth=100)
{
$sourceImage = imagecreatefromjpeg($this->source);
$orgWidth = imagesx($sourceImage);
$orgHeight = imagesy($sourceImage);
$thumbHeight = floor($orgHeight * ($thumbWidth / $orgWidth));
$destImage = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($destImage, $sourceImage, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $orgWidth, $orgHeight);
imagejpeg($destImage, $destImagePath,100);
imagedestroy($sourceImage);
imagedestroy($destImage);
}
}
and call it with:
$objThumbImage = new ThumbImage($uploadFilePath);
$objThumbImage->createThumb($uploadFileThumbPath, 640);

Related

PHP Imagick black areas after converting PDF to JPG

I'm using Imagick to generate JPG thumbnails for PDFs files but some of them generate with black areas (http://i.imgur.com/fKBncKw.jpg) – I'm assuming it's caused by transparency in the PDFs but can anything be done about it?
Code I'm using to generate these:
$imagick = new Imagick($filename);
$imagick->setIteratorIndex(0);
$imagick->setImageFormat('jpg');
return $imagick->getImageBlob();
Is there a way to flatten the PDF and/or add a white background so that the black areas don't appear?
Here is a solution which will only work for PNG to JPG.
This code adds a white background to the transparent areas in PNG and converts it to JPG.
What it does?
This code takes all PNG images from a folder, converts them to JPG's with white backgrounds and saves them in another folder.
<?php
ini_set('max_execution_time', 3000);
$dir = 'transparent/';
$arr = scandir($dir);
for($i=0;$i<count($arr);$i++)
{
if($i==0 || $i==1)
{
}
else{
$input_file = "transparent/".$arr[$i];
$output_file = "White/".str_replace('.png','.jpg',$arr[$i]);
$input = imagecreatefrompng($input_file);
list($width, $height) = getimagesize($input_file);
$output = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($output, 255, 255, 255);
imagefilledrectangle($output, 0, 0, $width, $height, $white);
imagecopy($output, $input, 0, 0, 0, 0, $width, $height);
imagejpeg($output, $output_file);
}
}
?>
Its Image Processing and GD in PHP.
PHP Manual
Hope it helps, you can change it as you want.
Try this code: Imagick::setCompressionQuality
$im = new imagick(realpath($file).'[0]');
$im->setCompression(Imagick::COMPRESSION_JPEG);
$im->setCompressionQuality(100);
$im->setImageFormat("jpeg");
$im->writeImage("imagename.jpg");
Alternative solution: this may help:
<?php
//Note that the function returns an Imagick object and does not modify the existing object. Below is my code for converting a PNG with transparency into a JPG with a background color. This code illustrates the difference.
$im = new Imagick($filename);
$im->setImageBackgroundColor('white');
$im->flattenImages(); // This does not do anything.
$im = $im->flattenImages(); // Use this instead.
$im->setImageFormat('jpg');
$im->writeImage('image.jpg');
?>
use like this
class ImageConvertorLib{
private $CI;
/**
* loading codeIgniter instance
*/
public function __construct(){
$this->CI =& get_instance();
}
public function pdfToJpg($param){
$filename = $param['filename'];
$image_name = $param['image_name'];
$path = $param['path'];
$db_path = $param['db_path'];
$im = new Imagick();
$im->setResolution(220,220);
$im->readimage($filename."[0]");
$im->setImageFormat('jpeg');
$im->setImageBackgroundColor('#ffffff');
$im->flattenImages();
$image_name = $image_name.".jpg";//"save_as_name.jpg";
$imageprops = $im->getImageGeometry();
/*if ($imageprops['width'] <= 175 && $imageprops['height'] <= 300) {
// don't upscale
} else {
$im->resizeImage(175,300, imagick::FILTER_LANCZOS, 0.9, true);
}*/
$im->writeImage($path.$image_name);
if($im){
$Img = array();
$Img['status'] = 1;
$Img['image'] = ($db_path.$image_name);
return $Img;
}
$im->clear();
$im->destroy();
}
}
After endless attempts to append a pdf file with a jpeg image without getting black areas, I found the solution: the function transformImageColorspace
Used in this order works perfectly:
$im = new Imagick();
$im->readImage("file.pdf");
$im->transformImageColorspace(Imagick::COLORSPACE_SRGB);
$im->setImageFormat('jpeg');
$im->writeImage('image.jpg');

Merge JPEG and PNG with transparent Background to one Image PHP

i have the following script for coping a JPEG and a PNG to an existing PNG called base.png. Within the function "transparent_background" i replace the white background with transparency. This function is the problem. Standlone the function is working with output directly in the browser. please see the comment out "//imagepng($img);". but if i return the $img out of the function its still a jpeg i think, thats why it isnt transparent. The second function is just for resize.
<?php
function transparent_background($img)
{
$img = imagecreatefromjpeg($img); //or whatever loading function you need
$colors= array("255","255","255");
$remove = imagecolorallocate($img, $colors[0], $colors[1], $colors[2]);
imagecolortransparent($img, $remove);
//imagepng($img);
return $img;
imagedestroy($img);
}
function resize($img, $w){
$img = imagecreatefromjpeg($img);
$ratio = imagesx($img)/imagesy($img);
if( $ratio > 1) {
$width = $w;
$height = $w/$ratio;
}
else {
$width = $w*$ratio;
$height = $w;
}
$dst = imagecreatetruecolor($width,$height);
imagecopyresampled($dst,$img,0,0,0,0,$width,$height,imagesx($img),imagesy($img));
return $dst;
imagedestroy($dst);
imagedestroy($img);
}
$h="https://images-eu.ssl-images-amazon.com/images/I/415zYwg2-TL.jpg";
$base = imagecreatefrompng("base.png");
$logo = imagecreatefrompng("fs_logo_line.png");
$pos1=resize($h,"730");
$pos1=transparent_background($h);
imagecopy($base,$pos1,0, 5, 0, 0, imagesx($pos1),imagesy($pos1));
imagecopy($base,$logo,0, 1136, 0,0,imagesx($logo),imagesy($logo));
imagepng($base);
?>
I think the problem is, that i get a jpeg back from the transparent_background function and thats why the image in $pos1 is not transparent. Any ideas how i can solve that? I have tried with ob_start & ob_get_contents but this also didn't work.
You can merge the two images together using the PHP GD2 library.
Example:
<?php
# If you don't know the type of image you are using as your originals.
$image = imagecreatefromstring(file_get_contents($your_original_image));
$frame = imagecreatefromstring(file_get_contents($your_frame_image));
# If you know your originals are of type PNG.
$image = imagecreatefrompng($your_original_image);
$frame = imagecreatefrompng($your_frame_image);
imagecopymerge($image, $frame, 0, 0, 0, 0, 50, 50, 100);
# Save the image to a file
imagepng($image, '/path/to/save/image.png');
# Output straight to the browser.
imagepng($image);
?>
Add imagealphablending($frame,true); before imagecopymerge() if you want to keep PNG frame transparancy over the image.

Can't get image resize code to work in PHP

I am building a thumbnail system, but my code outputs a bunch or random icons. It apparently should work, but it doesn't.
Code:
<?php
// The file
$filename = 'post/imgres/posts/1.jpg';
// Set a maximum height and width
$width = 200;
$height = 200;
// Content type
header('Content-Type: image/jepg');
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output
imagejpeg($image_p, null, 100);
?>
I found a class called simpleimage by claviska. and my code is now done. it all looks like this.
The code that takes care of the thumbnails:
function isThumb($thumbnail)
{
if (file_exists($thumbnail))
{
return true;
}
return false;
}
function makeThumb($original, $destination)
{
$img = new abeautifulsite\SimpleImage($original);
$img->fit_to_width(256);
$img->save($destination);
}
?>
The code that loads the images:
<?php
//Image loader
//Folder containing images.
$filedir = "imgres/posts/";
//Retrieve the images in the folder.
$images = glob($filedir."*.{jpg,JPG,png,PNG,gif,GIF}",GLOB_BRACE);
//Make sure the image array is not empty, or null.
if (!empty($images))
{
//Load the images into the website.
foreach ($images as $image)
{
if (pathinfo($image,PATINFO_EXTENSION) == "gif" || pathinfo($image, PATHINFO_EXTENSION)=="GIF")
{
echo '<img src="'.$image.'"/>';
}
else
{
echo '<img src="'.getThumb($image).'"/>';
}
}
}
else
{
//Write out an error message to warn the user.
echo "<p>No images were found in the server. This is most likely an error in the PHP code, incompatibility, or something went wrong with our storage solution. Contact admin! Information needed: Browser, OS, and has the site worked before?</p>";
}
?>
PHP Image thumbnailing is a common task and there are plenty of solid image thumbnailing examples and sources are out there. I'm not sure what your script is doing but here is a barebone basic script which always works and its straight forward.
You should cover and support all image types png's and gif's. But since you're doing jpegs, let use that for now. Adding support for other image types shouldn't be that difficult.
/* read the source image */
$source_image = imagecreatefromjpeg($src);
$width = imagesx($source_image);
$height = imagesy($source_image);
/* find the "desired height" of this thumbnail, relative to the desired width */
$desired_height = floor($height * ($desired_width / $width));
/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
/* copy source image at a resized size */
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
// Content type, you need this line of code to
// display image to browser or for testing it on the UI
header('Content-Type: image/jepg');
/* create the physical thumbnail image to its destination */
imagejpeg($virtual_image, $dest);

How to get image thumbnail from given link?

When sharing link on Facebook, Facebook get Title,Meta Description and Image from given link.
I have no idea how they get the image. I search on the internet as well as, but I could n't find a way.
How to get image thumbnail from given URL?
Well, save file to your server using file_put_contents(), and then you can create thumbnail. you can't get thumbnail directly from url.
Save file like this :
$url = 'http://example.com/image.ext';
$img = 'yourImgNameOrWithPath.ext';
file_put_contents($img, file_get_contents($url));
Create thumbnail using following code :
function createThum($filename,$thumb_width,$thumb_height,$destination)
{
$my_input_file = $filename;
$my_output_file = $destination;
$jpeg_quality = 100;
$size = getimagesize($my_input_file);
//$thumb_width = ($size[0] / $size[1]) * $thumb_height;
$src_img = imagecreatefromjpeg($my_input_file);
$dst_img = imagecreatetruecolor($thumb_width,$thumb_height);
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_width, $thumb_height, $size[0], $size[1]);
imagejpeg($dst_img, $my_output_file, $jpeg_quality);
imagedestroy($src_img);
imagedestroy($dst_img);
return true;
}

Resize images with PHP

I have a quick question that I'm not quite sure to set up. I've seen examples elsewhere but nothing specifically like my situation. I would like to resize images using PHP so they're readable and not just wonkily stretched like if you use HTML. If they're not 250 pixels wide, or 160 pixels tall, how can I resize the picture so it's proportionate but fits within that space?
Thanks!
PHP does not manipulate images directly. You will need to use an image manipulation library such as gd or ImageMagick to accomplish this goal.
In ImageMagick, image resizing is accomplished like this:
$thumb = new Imagick('myimage.gif');
$thumb->resizeImage(320,240,Imagick::FILTER_LANCZOS,1);
$thumb->writeImage('mythumb.gif');
With GD, you can do it like this:
<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Output
imagejpeg($image_p, null, 100);
?>
Ok, so below is an Image object that I use in my store. It maintains scale - requires GD
<?php
class Store_Model_Image extends My_Model_Abstract
{
const PATH = STORE_MODEL_IMAGE_PATH;
const URL = "/store-assets/product-images/";
public function get_image_url($width, $height)
{
$old_file = self::PATH . $this->get_filename();
$basename = pathinfo($old_file, PATHINFO_FILENAME);
$new_name = sprintf("%s_%sx%s.jpg", $basename, $width, $height);
if(file_exists(self::PATH . $new_name))
{
return self::URL . $new_name;
}
else
{
list($width_orig, $height_orig, $image_type) = #getimagesize($old_file);
$img = FALSE;
// Get the image and create a thumbnail
switch($image_type)
{
case 1:
$img = #imagecreatefromgif($old_file);
break;
case 2:
$img = #imagecreatefromjpeg($old_file);
break;
case 3:
$img = #imagecreatefrompng($old_file);
break;
}
if(!$img)
{
throw new Zend_Exception("ERROR: Could not create image handle from path.");
}
// Build the thumbnail
if($width_orig > $height_orig)
{
$width_ratio = $width / $width_orig;
$new_width = $width;
$new_height = $height_orig * $width_ratio;
}
else
{
$height_ratio = $height / $height_orig;
$new_width = $width_orig * $height_ratio;
$new_height = $height;
}
$new_img = #imagecreatetruecolor($new_width, $new_height);
// Fill the image black
if(!#imagefilledrectangle($new_img, 0, 0, $new_width, $new_height, 0))
{
throw new Zend_Exception("ERROR: Could not fill new image");
}
if(!#imagecopyresampled($new_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig))
{
throw new Zend_Exception("ERROR: Could not resize old image onto new bg.");
}
// Use a output buffering to load the image into a variable
ob_start();
imagejpeg($new_img, NULL, 100);
$image_contents = ob_get_contents();
ob_end_clean();
// lastly (for the example) we are writing the string to a file
$fh = fopen(self::PATH . $new_name, "a+");
fwrite($fh, $image_contents);
fclose($fh);
return self::URL . $new_name;
}
}
}
I resize the image at request time, so the first time the page loads an image will be resized to the required size for the template. (this means I don't have to crash a shared host trying to regenerate image thumbnails everytime my design changes)
So in the template you pass your image object, and when you need a image thumb,
<img src="<?php echo $image->get_image_url(100, 100); ?>" />
you now have a 100x100 thumb, which is saved to the Server for reuse at a later date
gd and imagemagick are two tools that may work for you
http://php.net/manual/en/book.image.php
http://php.net/manual/en/book.imagick.php
Here is something I used to use
class cropImage{
var $imgSrc,$myImage,$cropHeight,$cropWidth,$x,$y,$thumb;
function setImage($image,$moduleWidth,$moduleHeight,$cropPercent = "1") {
//Your Image
$this->imgSrc = $image;
//getting the image dimensions
list($width, $height) = getimagesize($this->imgSrc);
//create image from the jpeg
$this->myImage = imagecreatefromjpeg($this->imgSrc) or die("Error: Cannot find image!");
if($width > $height) $biggestSide = $width; //find biggest length
else $biggestSide = $height;
//The crop size will be half that of the largest side
//$cropPercent = 1.55; // This will zoom in to 50% zoom (crop)
if(!$cropPercent) {
$cropPercent = 1.50;
}
$this->cropWidth = $moduleWidth*$cropPercent;
$this->cropHeight = $moduleHeight*$cropPercent;
//$this->cropWidth = $biggestSide*$cropPercent;
//$this->cropHeight = $biggestSide*$cropPercent;
//getting the top left coordinate
$this->x = ($width-$this->cropWidth)/2;
$this->y = ($height-$this->cropHeight)/2;
}
function createThumb($moduleWidth,$moduleHeight){
$thumbSize = 495; // will create a 250 x 250 thumb
$this->thumb = imagecreatetruecolor($moduleWidth, $moduleHeight);
//$this->thumb = imagecreatetruecolor($thumbSize, $thumbSize);
imagecopyresampled($this->thumb, $this->myImage, 0, 0,$this->x, $this->y, $moduleWidth, $moduleHeight, $this->cropWidth, $this->cropHeight);
//imagecopyresampled($this->thumb, $this->myImage, 0, 0,$this->x, $this->y, $thumbSize, $thumbSize, $this->cropWidth, $this->cropHeight);
}
function renderImage(){
header('Content-type: image/jpeg');
imagejpeg($this->thumb);
imagedestroy($this->thumb);
}
}
Call it by using
$image = new cropImage;
$image->setImage($imagepath,$moduleWidth,$moduleHeight,$scaleRelation);
$image->createThumb($moduleWidth,$moduleHeight);
$image->renderImage();
Use GD or ImageMagick. Here you may find a real production example of code (used by MediaWiki) that supports consoled ImageMagick interface (transformImageMagick method), ImageMagick extension interface (transformImageMagickExt method) and GD (transformGd method).
There a simple to use, open source library called PHP Image Magician that will can help you out.
Example of basis usage:
$magicianObj = new imageLib('racecar.jpg');
$magicianObj -> resizeImage(100, 200, 'crop');
$magicianObj -> saveImage('racecar_small.png');

Categories