I use the below code to resize images (jpg, png, gif). The code is working perfectly. But the problem is after resizing the images, all transparent images (both png and gif) have a black background.
How can I maintain the transparency so that resized images will have not have black background?
$target = 'uploads/'.$newname;
move_uploaded_file( $_FILES['file']['tmp_name'], $target);;
$filename=$newname;
if($ext=='jpg'||$ext=='jpeg') {
$im = imagecreatefromjpeg('uploads/'.$filename);
} else if ($ext=='gif') {
$im = imagecreatefromgif('uploads/'.$filename);
} else if ($ext=='png') {
$im = imagecreatefrompng('uploads/'.$filename);
}
$ox = imagesx($im);
$oy = imagesy($im);
$nm = imagecreatetruecolor(400, 300);
imagecopyresized($nm, $im, 0,0,0,0,400,300,$ox,$oy);
imagejpeg($nm, 'thumbnails/' . $filename);
imagesavealpha() sets the flag to attempt to save full alpha channel
information (as opposed to single-color transparency) when saving PNG
images.
You have to unset alphablending (imagealphablending($im, false)), to
use it.
Try adding
imagealphablending( $nm, FALSE );
imagesavealpha( $nm, TRUE );
Here:
.
.
$nm = imagecreatetruecolor(400, 300);
imagealphablending( $nm, FALSE );
imagesavealpha( $nm, TRUE );
.
.
Also consider using imagecopyresampled instead of imagecopyresized.
imagecopyresampled() smoothly interpolates pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity.
Use imagecopyresampled($nm, $im, 0,0,0,0,400,300,$ox,$oy);
Instead of
imagecopyresized($nm, $im, 0,0,0,0,400,300,$ox,$oy);
I also had similar troubles where a black background still appeared when using:
imagealphablending($image, false);
imagesavealpha($image, true);
I found the below combination to be successful though:
imagecolortransparent($image, imagecolorallocate($thumbnail, 0, 0, 0));
imagealphablending($image, false);
Related
Currently I would like to create a transparent png with the lowest quality .
The code:
<?php
function createImg ($src, $dst, $width, $height, $quality) {
$newImage = imagecreatetruecolor($width,$height);
$source = imagecreatefrompng($src); //imagecreatefrompng() returns an image identifier representing the image obtained from the given filename.
imagecopyresampled($newImage,$source,0,0,0,0,$width,$height,$width,$height);
imagepng($newImage,$dst,$quality); //imagepng() creates a PNG file from the given image.
return $dst;
}
createImg ('test.png','test.png','1920','1080','1');
?>
However, there are some problems:
Do I need to specific a png file before creating any new file? Or can I create without any existing png file?
Warning: imagecreatefrompng(test.png): failed to open stream: No such file or directory in
C:\DSPadmin\DEV\ajax_optipng1.5\create.php on line 4
Although there are error message , it still generate a png file , however, what I found that is the file is a black color image , do I need to specific any parameter to make it transparent?
Thanks.
To 1)
imagecreatefrompng('test.png') tries to open the file test.png which then can be edited with GD functions.
To 2)
To enable saving of the alpha channel imagesavealpha($img, true); is used.
The following code creates a 200x200px sized transparent image by enabling alpha saving and filling it with transparency.
<?php
$img = imagecreatetruecolor(200, 200);
imagesavealpha($img, true);
$color = imagecolorallocatealpha($img, 0, 0, 0, 127);
imagefill($img, 0, 0, $color);
imagepng($img, 'test.png');
Take a look at:
imagecolorallocatealpha
imagefill
An example function copies transparent PNG files:
<?php
function copyTransparent($src, $output)
{
$dimensions = getimagesize($src);
$x = $dimensions[0];
$y = $dimensions[1];
$im = imagecreatetruecolor($x,$y);
$src_ = imagecreatefrompng($src);
// Prepare alpha channel for transparent background
$alpha_channel = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagecolortransparent($im, $alpha_channel);
// Fill image
imagefill($im, 0, 0, $alpha_channel);
// Copy from other
imagecopy($im,$src_, 0, 0, 0, 0, $x, $y);
// Save transparency
imagesavealpha($im,true);
// Save PNG
imagepng($im,$output,9);
imagedestroy($im);
}
$png = 'test.png';
copyTransparent($png,"png.png");
?>
1) You can create a new png file without any existing one.
2) You get a black color image because you use imagecreatetruecolor();. It creates a highest quality image with a black background. As you need a lowest quality image use imagecreate();
<?php
$tt_image = imagecreate( 100, 50 ); /* width, height */
$background = imagecolorallocatealpha( $tt_image, 0, 0, 255, 127 ); /* In RGB colors- (Red, Green, Blue, Transparency ) */
header( "Content-type: image/png" );
imagepng( $tt_image );
imagecolordeallocate( $background );
imagedestroy( $tt_image );
?>
You can read more in this article: How to Create an Image Using PHP
I'm trying to create a function that receives a PNG image and returns it with inverted colors. However, I'm having trouble with the transparency/alpha channel: basically, transparent pixels are coming back as either black or white, and thus transparency is not retained.
This is an example of a source image (which will of course vary), a PNG with a transparent background:
I would like to invert those colors while preserving transparency/alpha channel, like a CTRL+I in Photoshop. I'm using GD imagefilter function with the IMG_FILTER_NEGATE parameter
With the code:
$im = imagecreatefrompng($image_file);
imagefilter($im, IMG_FILTER_NEGATE);
header('image/png');
imagepng($im,NULL,0);
But it yields:
As you can see, transparent pixels turned black.
I then tried adding the alpha channel to the function imagecreatefrompng (like this):
$im = imagecreatefrompng($image_file);
imagealphablending($im, false);
imagesavealpha($im, true);
imagefilter($im, IMG_FILTER_NEGATE);
header('image/png');
imagepng($im,NULL,0);
But now I get white instead of black:
Now the issue seems to happen after the imagefilter function is applied. For example, if I run this code:
$im = imagecreatefrompng($image_file);
imagealphablending($im, false);
imagesavealpha($im, true);
//imagefilter($im, IMG_FILTER_NEGATE);
header('image/png');
imagepng($im,NULL,0);
The output image retains its transparent background, while remaining identical to the original image.
How can I invert colors of transparent PNGs without losing the transparent background?
NOTE: this is not the same question as imagecreatefrompng() Makes a black background instead of transparent? - the inversion step is the tricky part here
Here's what worked for me, dealing with transparent background and inverting image. Note that I'm using base64.
$im = imagecreatefromstring(base64_decode(str_replace('data:image/png;base64,', '', $base64)));
$width = imagesx($im);
$height = imagesy($im);
$dest_image = imagecreatetruecolor($width, $height);
imagealphablending($dest_image, FALSE);
imagesavealpha($dest_image, TRUE);
imagefilter($im, IMG_FILTER_NEGATE);
imagecopyresampled($dest_image, $im, 0, 0, 0, 0, $width, $height, $width, $height);
//optional output back to base64 or use imagepng with destination
ob_start();
imagepng($dest_image);
$contents = ob_get_contents();
ob_end_clean();
$base64 = 'data:image/png;base64,'.base64_encode($contents);
I am trying to resize images using cropThumbnailImage. I use cropThumbnailImage as it resizes to the shorter length of the original image and crops the image on the longer side equally on both sides so that center portion of the image remains uncropped. This works fine for jpg images but for png images, the resized pngs get a black background.
Following is the code I use.
$image = new \Imagick($src);
// resize & crop
$image->cropThumbnailImage($width, $height);
// save new resized file
$image->writeImage($dest);
Run this code for the following png image.
http://tuxpaint.org/stamps/stamps/animals/birds/cartoon/tux.png
http://www.cs.csubak.edu/~mcabrera/CS211/transparent.png
http://www.tcarms.com/media/assets/productPhotos/006_G2%20Contender/png/Pistol_12in_Ribbed_Blued_2720.png
The output image is resized as required but the png image gets black background.
Tried adding below lines from herebut did not work.
imagealphablending( $image, false );
imagesavealpha( $image, true );
There are other solutions out there in the web which achieve resizing of png images, but I did not find a solution that resizes image the way cropThumbnailImage does.
Transparency is preserved using the following snippet:
$im = new Imagick($imgPath);
$im->setImageFormat('png');
$im->writeImage('/files/thumbnails/new_title.png');
There is not transparency in your JPG... The JPG is not a transparent image... PNG and GIF are necessary here.
If you are refering to PNG, there is a PHP code who will help you to resize PNGs with transparency:
$x = "COORDINATES - X for crop";
$y = "COORDINATES - y for crop";
$w = "width";
$h = "height";
$img = imagecreatefrompng($img_path);
imagealphablending($img, true);
$img_cropped = imagecreatetruecolor($w, $h);
imagesavealpha($img_cropped, true);
imagealphablending($img_cropped, false);
$transparent = imagecolorallocatealpha($img_cropped, 0, 0, 0, 127);
imagefill($img_cropped, 0, 0, $transparent);
imagecopyresampled($img_cropped, $img, 0, 0, $x, $y, $w, $h, $w, $h); // you can also use imagecopy() here
imagepng($img_cropped, "your_image_cropped.png", 2);
imagedestroy($img);
imagedestroy($img_cropped);
EDIT: Try this:
$image = imagecreatefrompng ( $filename );
$new_image = imagecreatetruecolor ( $width, $height ); // new wigth and height
imagealphablending($new_image , false);
imagesavealpha($new_image , true);
imagecopyresampled ( $new_image, $image, 0, 0, 0, 0, $width, $height, imagesx ( $image ), imagesy ( $image ) );
$image = $new_image;
// saving
imagealphablending($image , false);
imagesavealpha($image , true);
imagepng ( $image, $filename );
Don't forget to define $filename, $width, $height!!!!
Currently I would like to create a transparent png with the lowest quality .
The code:
<?php
function createImg ($src, $dst, $width, $height, $quality) {
$newImage = imagecreatetruecolor($width,$height);
$source = imagecreatefrompng($src); //imagecreatefrompng() returns an image identifier representing the image obtained from the given filename.
imagecopyresampled($newImage,$source,0,0,0,0,$width,$height,$width,$height);
imagepng($newImage,$dst,$quality); //imagepng() creates a PNG file from the given image.
return $dst;
}
createImg ('test.png','test.png','1920','1080','1');
?>
However, there are some problems:
Do I need to specific a png file before creating any new file? Or can I create without any existing png file?
Warning: imagecreatefrompng(test.png): failed to open stream: No such file or directory in
C:\DSPadmin\DEV\ajax_optipng1.5\create.php on line 4
Although there are error message , it still generate a png file , however, what I found that is the file is a black color image , do I need to specific any parameter to make it transparent?
Thanks.
To 1)
imagecreatefrompng('test.png') tries to open the file test.png which then can be edited with GD functions.
To 2)
To enable saving of the alpha channel imagesavealpha($img, true); is used.
The following code creates a 200x200px sized transparent image by enabling alpha saving and filling it with transparency.
<?php
$img = imagecreatetruecolor(200, 200);
imagesavealpha($img, true);
$color = imagecolorallocatealpha($img, 0, 0, 0, 127);
imagefill($img, 0, 0, $color);
imagepng($img, 'test.png');
Take a look at:
imagecolorallocatealpha
imagefill
An example function copies transparent PNG files:
<?php
function copyTransparent($src, $output)
{
$dimensions = getimagesize($src);
$x = $dimensions[0];
$y = $dimensions[1];
$im = imagecreatetruecolor($x,$y);
$src_ = imagecreatefrompng($src);
// Prepare alpha channel for transparent background
$alpha_channel = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagecolortransparent($im, $alpha_channel);
// Fill image
imagefill($im, 0, 0, $alpha_channel);
// Copy from other
imagecopy($im,$src_, 0, 0, 0, 0, $x, $y);
// Save transparency
imagesavealpha($im,true);
// Save PNG
imagepng($im,$output,9);
imagedestroy($im);
}
$png = 'test.png';
copyTransparent($png,"png.png");
?>
1) You can create a new png file without any existing one.
2) You get a black color image because you use imagecreatetruecolor();. It creates a highest quality image with a black background. As you need a lowest quality image use imagecreate();
<?php
$tt_image = imagecreate( 100, 50 ); /* width, height */
$background = imagecolorallocatealpha( $tt_image, 0, 0, 255, 127 ); /* In RGB colors- (Red, Green, Blue, Transparency ) */
header( "Content-type: image/png" );
imagepng( $tt_image );
imagecolordeallocate( $background );
imagedestroy( $tt_image );
?>
You can read more in this article: How to Create an Image Using PHP
Hey guys i have a problem with merging two pictures...
I am trying to merge an png file (called badge) with an useruploaded picture.
Everything works fine when the user upload a png oder gif file, but if he uploads a jpeg image the output image looks really weird. It seems it is an color problem.
Here my code:
//Calculate position for badge (right bottom corner)
$badgeRightPosition = $imageWidth - $badgeWidth;
$badgeLeftPosition = $imageHeight - $badgeHeight;
$image = imagecreatefromstring(file_get_contents($image));
$badge = imagecreatefromstring(file_get_contents($badge));
$trueColorImage = imagecreatetruecolor($imageWidth, $imageHeight);
imagealphablending($trueColorImage, true);
imagesavealpha($trueColorImage, true);
imagealphablending($badge, true);
imagesavealpha($badge, true);
imagealphablending($image, true);
imagesavealpha($image, true);
imagecopyresized($trueColorImage, $image, 0, 0, 0, 0, $imageWidth, $imageHeight, $imageWidth, $imageHeight);
imagecopyresized($trueColorImage, $badge, $badgeRightPosition, $badgeLeftPosition, 0, 0, $imageWidth, $imageHeight, $badgeWidth, $badgeHeight);
Instead of imagecreatefromstring(file_get_contents($image)); I would try to directly open the file
$imgsrc = #ImageCreateFromJPEG($image);
if (!$imgsrc) $imgsrc = #ImageCreateFromPNG($image);
if (!$imgsrc) $imgsrc = #ImageCreateFromGIF($image);
if (!$imgsrc) $imgsrc = #ImageCreateFromWBMP($image);
Or check the file type by its ending and then use one of the functions above according to the file ending.