Image flipping using php - php

I am provided with a hosting plan with php gd version 2 and I cannot install any other library. I know image flipping can be done by using imagesx() imagesy() and imagecreatetruecolor() but they are not available in GD version 2. and I cannot upgrade to higher version.
So, is there any other way to flip image horizontally and vertically using php gd version 2 or just with php? Thanks millions.

Maybe this will help... you will need to modify it to flip vertical though...
$size_x = imagesx($img);
$size_y = imagesy($img);
$temp = imagecreatetruecolor($size_x, $size_y);
imagecolortransparent($temp, imagecolorallocate($temp, 0, 0, 0));
imagealphablending($temp, false);
imagesavealpha($temp, true);
$x = imagecopyresampled($temp, $img, 0, 0, ($size_x-1), 0, $size_x, $size_y, 0-$size_x, $size_y);
if ($x) {
$img = $temp;
}
else {
die("Unable to flip image");
}
header("Content-type: image/gif");
imagegif($img);
imagedestroy($img);
Credit to Markus: Here is the link

Related

imagerotate fails for small image

I have a 1x2px image, when I use imagerotate I get this error
Warning: imagerotate(): gd warning:
one parameter to a memory allocation multiplication is negative or zero,
failing operation gracefully in file#line
Sample code
header('Content-type: image/png');
$angle = 320;
$image = imagecreatefrompng('small.png');
$bg_color = imagecolorallocatealpha($image, 0, 0, 0, 127);
$temp_image = imagerotate($image, -$angle, $bg_color);
imagesavealpha($image, 1);
imagepng($image);
Is there a workaround for this issue?
PHP 5.5.12
WAMP

Is there higher quality way of converting php image resources to jpeg or png besides using imagejpeg or imagepng

Currently I am using imagepng to convert an image resource based off of an original image to an png image type. This proved to have a higher level of quality than the imagejpeg function was creating for my jpg.
However you can clearly see that the compression algorithms in these two functions are not of as high quality as one that would be in something like Photoshop.
Does anyone know of a way to get a higher quality jpeg? Is there documentation on the format of the image resource and how it is converted to a jpeg or png? If I had that information I could at least try to implement a better algorithm.
//Create image
$im = apppic($filename, $colors);
imagepng($im, "images/app/".rtrim($path_array[$count],"jpeg")."png", 0);
function promopic ($filename, $colors){
if(#imagecreatefromjpeg($filename))
$img = imagecreatefromjpeg($filename);
elseif(#imagecreatefrompng($filename))
$img = imagecreatefrompng($filename);
elseif(#imagecreatefromgif($filename))
$img = imagecreatefromgif($filename);
$width = imagesx($img);
$height = imagesy($img);
$imHeight = 625;
if( $width/$height > 4/5){$imWidth = 800; $imHeight = $height/$width*$imWidth ; }
else { $imWidth = $width/$height*$imHeight; }
$colorWidth = 1200 - $imWidth;
$numColors = count($colors);
$colorHeight = ceil($imHeight/$numColors) - 2;
$imHeight = ceil($imHeight/$numColors)* $numColors - 2;
$im = #imagecreate(1200, $imHeight+50)
or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 250, 250, 250);
$text_color = imagecolorallocate($im, 255, 255, 251);
$blue_color = imagecolorallocate($im, 40, 5, 251);
//Add color boxes
for ($i = 1; $i <= $numColors; $i++) {
$imcolorbox = #imagecreate($colorWidth, $colorHeight);
$rgb = hex2rgb($colors[($i-1)]);
$colorbox_color = imagecolorallocate($imcolorbox, $rgb[0], $rgb[1], $rgb[2]);
$dest_x = 1200-$colorWidth;
$dest_y = ($colorHeight + 2) * ($i-1);
$copy_image = imagecopy($im, $imcolorbox, $dest_x, $dest_y, 0, 0, $colorWidth, $colorHeight);
imagedestroy($imcolorbox);
//imagestring($im, 5, 1075, 2+$dest_y, "Reinvogue.com", $text_color);
//imagestring($im, 5, $imWidth+5, 2+$dest_y, "Reinvogue.com", $text_color);
//imagestring($im, 5, 1050, 17+$dest_y, "Hex: ".$colors[($i-1)], $text_color);
//imagestring($im, 5, 1050, 2+$dest_y, "RGB: ".$rgb[0]." ".$rgb[1]." ".$rgb[2], $text_color);
}
imagestring($im, 5, 10, $imHeight+15, "Powered by the Reinvogue.com Colorway Engine", $blue_color);
$copy_image = imagecopyresampled($im, $img, 0, 0, 0, 0, $imWidth-2, $imHeight, $width, $height);
return $im;
}
This should create a high quality image with a white background:
$im = #imagecreatetruecolor(1200, $imHeight+50)
$white = imagecolorallocate($im, 255, 255, 255);
imagefill($im, 0, 0, $white);
If you're working with png images you can even have a look at imagecolorallocatealpha (http://www.php.net/manual/en/function.imagecolorallocatealpha.php)
Hope this helps.
For high-quality PNG8 use pngquant2. PHP's built-in libgd fork has awful palette conversion.
Quoting: http://pngquant.org/php.html
<?php
/**
* Optimizes PNG file with pngquant 1.8 or later (reduces file size of 24-bit/32-bit PNG images).
*
* You need to install pngquant 1.8 on the server (ancient version 1.0 won't work).
* There's package for Debian/Ubuntu and RPM for other distributions on http://pngquant.org
*
* #param $path_to_png_file string - path to any PNG file, e.g. $_FILE['file']['tmp_name']
* #param $max_quality int - conversion quality, useful values from 60 to 100 (smaller number = smaller file)
* #return string - content of PNG file after conversion
*/
function compress_png($path_to_png_file, $max_quality = 90)
{
if (!file_exists($path_to_png_file)) {
throw new Exception("File does not exist: $path_to_png_file");
}
// guarantee that quality won't be worse than that.
$min_quality = 60;
// '-' makes it use stdout, required to save to $compressed_png_content variable
// '<' makes it read from the given file path
// escapeshellarg() makes this safe to use with any path
$compressed_png_content = shell_exec("pngquant --quality=$min_quality-$max_quality - < ".escapeshellarg( $path_to_png_file));
if (!$compressed_png_content) {
throw new Exception("Conversion to compressed PNG failed. Is pngquant 1.8+ installed on the server?");
}
return $compressed_png_content;
}

Empty space getting filled with black after GD imagecopy but only in some scenarios

I am experiencing an issue where I am allowing the user to resize images in a container and then need to create a resulting image that is the size of the container but with the image scaled and adjusted as per the users choices.
So for example say the container is 400 x 200 and the user wants to be able to put in a logo that is 600 x 100 they may wish to shrink the logo so it fits and leave space at the top and bottom. I need to be able to save that as an image that is 400x200 with the appropriate gaps at the top and bottom.
What I have found though is that if the image content (the logo in this example) extends beyond BOTH the top and the right of the container everything is fine OR if it DOESNT extend beyond either it is fine but if it extends beyond one and not the other then I get black fill- or something like that- see examples below...
Below are some examples of the results and this is the code I am using...
$cropped = wp_imagecreatetruecolor( $frame_w, $frame_h);
$backgroundColor = imagecolorallocatealpha($cropped, 0, 0, 0, 127);
//imageantialias( $cropped, true );
//if $img_y or $img_x are negative we need to apply the value to $img_x and $img_y
//if $img_y or $img_x are positive we need to apply the value to $dest_x and $dest_y
$dest_x = strstr($img_x,'-') ? 0 : abs($img_x);//if neg is true = 0 else offset inside
$dest_y = strstr($img_y,'-') ? 0 : abs($img_y);
$img_x = strstr($img_x,'-') ? abs($img_x) : 0;//if neg is true offset outside else 0
$img_y = strstr($img_y,'-') ? abs($img_y) : 0;
$img_w = $img_w > $frame_w ? $frame_w : $img_w;
$img_h = $img_h > $frame_h ? $frame_h : $img_h;
imagecopy( $cropped, $resized, $dest_x, $dest_y, $img_x, $img_y, $img_w, $img_h);
//imagecopymerge( $cropped, $resized, $dest_x, $dest_y, $img_x, $img_y, $img_w, $img_h,100);
//imagecopyresampled( $cropped, $resized, $dest_x, $dest_y, $img_x, $img_y, $frame_w, $frame_h, $img_w, $img_h );
imagefill($cropped, 0, 0, $backgroundColor);//putting this after the copy makes any black borders transparent again unless $resized does not extend beyond both dimensions
Examples
Image does not extend beyond top or beyond right (fine)
Image extends beyond bottom but not right (not fine)
Image extends beyond both (fine)
Image extends beyond right but not bottom (not fine)
Image Extends beyond neither (fine)
I have been literally tearing my hair out trying to fix this and tried every possible combination of imagesavealpha, imagecopymerged, imagecolorallocatealpha, imagealphablending etc I can think of but nothing seems to fix this...
So is this a bug/limitation of GD? Or can someone out there come to my rescue!
I don't know if this will help you, but I had an issue with this earlier today. The box expands but the area was black. Here's my code (which fixes it):
<?php
function createImage($text)
{
// Adds an extra space to fill underline
$text = " $text";
// Adds one line at the end
$text .= "\n";
// Wrap the text to fit the image
$text = wordwrap($text, 40, "\n");
// Count new lines
$newlines = substr_count($text, "\n");
// Count how long to expand
if($newlines == 0)
{
$height = 30;
}
else
{
$height = 30*$newlines-$newlines*5;
}
putenv('GDFONTPATH=' . realpath('.'));
header('Content-Type: image/png');
// Adding underline
$e = explode('<', $text);
for($i=0;$i<count($e);$i++)
{
$e[$i] = implode('̲', str_split($e[$i]));
}
// Creating image
$text = implode(' ', $e);
$im = imagecreatetruecolor(315, $height);
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
$purple = imagecolorallocate($im, 97, 26, 139);
imagefilledrectangle($im, 0, 0, 399, $height, $white);
$font = 'arialbd.ttf';
imagettftext($im, 11, 0, 10, 20, $purple, $font, $text);
imagepng($im);
imagedestroy($im);
}
createImage("asbdasddsa");
?>
i think this will happen only for PNG check with other formats
I'm not sure if this is an actual answer since it is basically 'Use ImageMagick' but anyway for those for whom ImageMagick is an option the code below might help them achieve the same thing as I was trying to above... Basically ImageMagick seems far superior to GD, no borders around rotated images, no hassles with transparency, no onwanted black fill, clearer resizing if you are enlarging...
$img_x = -50; //left offset of the image within the frame
$img_y = 50; //top offset of the image within the frame
$img_w = 400; //width of the image to be put in the frame
$img_h = 200; // height of the image to be put in the frame
$angle = 45; //rotation to be applied to the image before it is put into the frame
$frame_w = 300; //width of the frame the image is going into
$frame_h = 300; //height of the frame the image is going into
$img_path = 'path/to/image/file.jpg';
$image = new Imagick( $img_path );
$size = $image->getImageGeometry();
$orig_w = $size['width']; $orig_h = $size['height'];
$image->scaleImage( $img_w, $img_h );
//rotate if necessary
if($angle)
{
$image->rotateImage( new ImagickPixel('none'), $angle );
$size = $image->getImageGeometry();
$img_w = $size['width']; $img_h = $size['height'];
}
//composite into frame
//in imagemagick we create an image that is the size of the frame and make it transparent
$frame = new Imagick();
$frame->newImage($frame_w, $frame_h, new ImagickPixel("none"));
//then we composite the image itself into this with the respective offset values
$frame->compositeImage( $image, Imagick::COMPOSITE_DEFAULT, $img_x, $img_y );
//save it
$destfilename = "{$dir}/{$name}-{$img_suffix}.{$ext}";
$frame->writeImage($destfilename);
$frame->clear();
$frame->destroy();
$image->clear();
$image->destroy();
The above code produces this...yay!

PHP+GD: imagecopymerge not retaining PNG transparencies

I have two PNG files, "red.png" and "blue.png"; they are both mostly transparent, but there is a few pixels of red or blue splotches in various places.
I want to make a PHP script that merges the two; it should be as simple as something like:
$original = getPNG('red.png');
$overlay = getPNG('blue.png');
imagecopymerge($original, $overlay, 0,0, 0,0, imagesx($original), imagesy($original), 100);
header('Content-Type: image/png');
imagepng($original);
When I run this script, all I get is the blue dots -- with the transparency lost. I saw that I should add these:
imagealphablending($original, false);
imagesavealpha($original, true);
(on both the original and the overlay?) And that doesn't seem to help any.
I saw a few workarounds on PHP.net, something to the tune of:
$throwAway = imagecreatefrompng($filename);
imagealphablending($throwAway, false);
imagesavealpha($throwAway, true);
$dstImage = imagecreatetruecolor(imagesx($throwAway), imagesy($throwAway));
imagecopyresampled($dstImage, $throwAway,0,0,0,0, imagesx($throwAway), imagesy($throwAway), imagesx($throwAway), imagesy($throwAway));
, which should convert the PNG to a "truecolor" image and retain transparency. It does seem to do so, but now all I see is blue on a black background.
What do I do?!
This works perfectly for me:
$img1 = imagecreatefrompng('red.png');
$img2 = imagecreatefrompng('blue.png');
$x1 = imagesx($img1);
$y1 = imagesy($img1);
$x2 = imagesx($img2);
$y2 = imagesy($img2);
imagecopyresampled(
$img1, $img2,
0, 0, 0, 0,
$x1, $y1,
$x2, $y2);
imagepng($img1, 'merged.png', 0);
PHP Version 5.3.2
GD Version 2.0
libPNG Version 1.2.42
Have you tried saving the image to a file and checking that?

how to resize bmp,tiff image using gd library ? and also mention about imagemagick which is good to use [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 8 years ago.
Improve this question
i need to know which is better gd or imagemagick to resize an image
I like ImageMagick better. But I know GD it's pretty good too.
Here's an example on how to resize an image using PHP:
<?php
if(!extension_loaded('imagick')) {
dl('imagick.so');
}
$img = strip_tags($_GET['imagename']);
if(isset($_GET['size'])) {
$size = strip_tags($_GET['size']);
} else {
$size = 0;
}
if(isset($_GET['vsize'])) {
$vsize = strip_tags($_GET['vsize']);
} else {
$vsize = 0;
}
$image = new Imagick($img);
$image->thumbnailImage($size, $vsize);
header("Content-type: image/png");
print $image;
?>
Here is the link where I got the example from. Just copied it to have it right in the question. All credits go to the person who wrote it.
"Better" is a subjective term. Many resizing algorithms can provide better quality at the expense of a higher processing time. So decide what attributes you want (good quality, or a fast response time), and look at the results of each library.
There are only a limited number of resampling algorithms available to resize an image. Asking which program is better implies that if the program implements the better algorithms then the program is considered "good."
Below is a thumbnailer I wrote in PHP. I've stripped out the bits that add drop shadows and borders (Don't think i've broken it but haven't tested).
This uses the GD library in PHP and I've always been happy with the results.
NB: You can probably strip out more - eg it sets the BG colour of the thumbnail so that it matches the page background, etc...
In this case, it would be called like this:
thumbnail.php?size=400&image=SomeImage.jpg
The only slight issue is that with large files (ie very high quality from modern digital cameras) it can have memory issues. I rarely hit this problem though - usually anything that size can't be uploaded by a user as the webserver won't allow it.
<?php
$defaultsize = 400;
$defaultimage = "images/error.jpg";
ini_set("memory_limit", "32M");
$red = isset($_REQUEST['r']) ? $_REQUEST['r'] : 255;
$green = isset($_REQUEST['g']) ? $_REQUEST['g'] : 255;
$blue = isset($_REQUEST['b']) ? $_REQUEST['b'] : 255;
if(!isset($_REQUEST['size'])) {
$maxWidth=$defaultsize;
$maxHeight=$defaultsize;
} else {
$maxWidth=$_REQUEST['size'];
$maxHeight=$_REQUEST['size'];
}
if(!isset($_REQUEST['image'])) {
$picurl = $defaultimage;
} else {
$picurl = "../" . stripslashes($_REQUEST['image']);
}
//Find out about source file
$srcDetails = #getimagesize($picurl);
if($srcDetails) {
$srcWidth=$srcDetails[0];
$srcHeight=$srcDetails[1];
} else {
$srcWidth=$maxWidth;
$srcHeight=$maxHeight;
}
if($srcWidth/$srcHeight < $maxWidth/$maxHeight) {
//Too wide
$width = $maxHeight / $srcHeight * $srcWidth;
$height = $maxHeight / $srcHeight * $srcHeight;
} else {
//Too tall
$width = $maxWidth / $srcWidth * $srcWidth;
$height = $maxWidth / $srcWidth * $srcHeight;
}
switch ($srcDetails[2]) {
case 1: //GIF
$srcImage = ImagecreateFromGIF($picurl);
break;
case 2: //JPEG
$srcImage = ImagecreateFromJPEG($picurl);
break;
case 3: //PNG
$srcImage = ImagecreateFromPNG($picurl);
break;
case 6: //WBMP
$srcImage = ImagecreateFromWBMP($picurl);
break;
default:
//Possibly add some "Unknown File Type" error code here. However, if we do't return an image, we will error nicely later anyway
break;
}
if(#!$srcImage) {
// The nice error for no source image (include error mail to yourself here if you want...)
$srcImage = imagecreate($maxWidth, $maxHeight); /* Create a blank image */
$bgc = imagecolorallocate($srcImage, 255, 255, 255);
$tc = imagecolorallocate($srcImage, 0, 0, 0);
imagefilledrectangle($srcImage, 0, 0, 150, 30, $bgc);
/* Output an errmsg */
imagestring($srcImage, 4, 5, 5, "Error resizing image", $tc);
imagestring($srcImage, 4, 5, 20, "Tech support department", $tc);
imagestring($srcImage, 4, 5, 35, "has been informed", $tc);
}
//Create thumbnail
$thumb = imagecreatetruecolor ($width, $height);
$bg = ImageColorAllocate($thumb, $red, $green, $blue);
imagefill ($thumb, 0, 0, $bg);
//Add the image itself
Imagecopyresized ($thumb, $srcImage, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);
//Add a black border
imageline($thumb, 0, 0, 0, $height, $black);
imageline($thumb, 0, 0, $width, 0, $black);
imageline($thumb, 0, $height, $width, $height, $black);
imageline($thumb, $width, $height, $width, 0, $black);
//output header
//I leave this so late so if there ARE any errors, they are displayed as text not a broken image
//(this will happen when looking at the thumnailer directly but will display as a broken image in a webpage still)
header("Content-type: image/PNG");
imagePNG($thumb);
//Clear up memory
imagedestroy($srcImage);
?>

Categories