Image transparency in imagepng() and imagegif() - php

I want to resize 2 types of images (png, gif) with transparent background...
But in png it works well in big size of the original image.
eg. Original file dimension is 150x150
change into 200x200 or exceeding the original size it works well. but in 100x100 it displays
Then the last GIF it doesn't work.
Here my code for png
$new_img = imagecreatetruecolor($max_w, $max_h);
imagealphablending($new_img, false);
imagesavealpha($new_img, true);
$transparentindex = imagecolorallocatealpha($new_img, 255, 255, 255, 127);
imagefill($new_img, 0, 0, $transparentindex);
imagepng($new_img, $dir);
Here my code for gif
imagegif($new_img, $dir);

I know no PHP, but this seems to do the trick:
#!/usr/local/bin/php -f
<?php
$neww=100;
$newh=100;
// Load original image and get its dimensions
$img = imagecreatefrompng("badge.png");
$w=imagesx($img);
$h=imagesy($img);
// Create output image, and fill with lots of transparency
$out = imagecreatetruecolor($neww,$newh);
imagealphablending($out,false);
$transparentindex = imagecolorallocatealpha($out,0,0,0,127);
imagefill($out,0,0,$transparentindex);
imagesavealpha($out, true);
// Copy original image, reized on top
imagecopyresized($out,$img,0,0,0,0,$neww,$newh,$w,$h);
imagepng($out,"out.png");
?>

Here is a little hack :)
Don't have any other ideas.
It involves a second image (1x1 trasparent gif)
create image
resize
create a transparent background with same size as resized image
use imagecolortransparent() to get the rgb index
imagecopymerge() images
voilĂ 
.
$dir = 'http://i.stack.imgur.com/DbhrJ.png';
$max_w = 50;
$max_h = 50;
// get image size
list($src_w, $src_h) = getimagesize($dir);
if ($src_w > $max_w) {
$ratio = $max_w / $src_w;
$max_w = $src_w * $ratio;
}
else if ($src_h > $max_h) {
$ratio = $max_h / $src_h;
$max_h = $src_h * $ratio;
}
// resize image to $max_w and $max_h, and also save alpha
$src = imagecreatefromstring(file_get_contents($dir));
$new_img = imagecreatetruecolor($max_w, $max_h);
imagealphablending($new_img, false);
imagesavealpha($new_img, true);
imagecopyresampled($new_img, $src, 0, 0, 0, 0, $max_w, $max_h, $src_w, $src_h);
// create a new image with $max_w and $max_h
$maxsize = imagecreatetruecolor($max_w, $max_h);
// add 1x1 gif and resize, then copy over $maxsize
$background = imagecreatefromgif("http://i.imgur.com/atRjCdk.gif"); // transparent 1x1 gif
imagecopyresampled($maxsize, $background, 0, 0, 0, 0, $max_w, $max_h, 1, 1);
// allocate transparency
$transparent = imagecolortransparent($maxsize);
$transparent_index = imagecolorallocate($maxsize, $transparent['red'], $transparent['green'], $transparent['blue']);
imagecolortransparent($maxsize, $transparent_index);
// image copy
imagecopymerge($maxsize, $new_img, 0, 0, 0, 0, $max_w, $max_h, 100);
// save or output
imagegif($maxsize, $path_to_save);
// destroy images
imagedestroy($maxsize);
imagedestroy($new_img);
imagedestroy($background);
imagedestroy($src);

Related

imagefttext() function (php) increases size of image

Trying to put watermark to an image
Image Original Size :- 10.8 MB
After watermarking:- New Image Size:- 37.9 MB
$text = "Afrophoto";
//the text i want as watermark
//create a new image
$newImg = imagecreatefromjpeg($image);
//set the watermark font color to red
$fontColor = imagecolorallocate($newImg, 255, 255, 255);
$font_file = 'fontArial.ttf';
list($width, $height) = getimagesize($image);
//write the watermark on the created image
imagefttext($newImg, 50, 50, $j, $i, $width - 100, $height - 100, $text);
//output the new image with a watermark to a file
imagejpeg($newImg,"uploads/".$_FILES[$field]['name'],100);
imagepng($newImg,"uploads/".$_FILES[$field]['name'].".png");
imagedestroy($newImg);
Here I used Png image
Actual size banned.png: 53.2KB
with watermark bbimage_3.png: 40.8 KB
<?php
$imageURL = "banned.png";
list($width,$height) = getimagesize($imageURL);
$imageProperties = imagecreatetruecolor($width, $height);
$targetLayer = imagecreatefrompng($imageURL);
imagecopyresampled($imageProperties, $targetLayer, 0, 0, 0, 0, $width, $height, $width, $height);
$WaterMarkText = 'CONFIDENTIAL';
$watermarkColor = imagecolorallocate($imageProperties, 191,191,191);
imagestring($imageProperties, 5, 130, 117, $WaterMarkText, $watermarkColor);
imagepng($imageProperties, 'bbimage_3.png');
header('Content-type: image/jpeg');
imagepng ($imageProperties);
imagedestroy($targetLayer);
imagedestroy($imageProperties);
?>
imagecopy: This function copies source image onto destination image by overwriting destination image pixels.
While merging png images with transparent background as a watermark, imagecopymerge() function will not preserve transparency onto the destination. So, imagecopy() is preferable for image watermarking.

Placing a watermark on transparent gif

I'm trying to make a image uploader and everything is working pretty good with the exception of placing a watermark on top of a transparent gif. The gif it self stays transparent but, the part of the watermark that gets placed on the gif's transparent background gets a red background for some reason and I'm struggling to find out why. Any suggestions?
else if ($this->fileType === "image/gif") {
$newFilename = $this->placeholder();
$img = imageCreateFromGif($this->fileTmpName);
imageAlphaBlending($img, true);
imageSaveAlpha($img, true);
if($this->watermarkEnabled === true) {
$this->watermark($img);
}
$newFilename = imageGif($img, $newFilename.".".$this->fileExtension);
}
function watermark($img) {
// creating png image of watermark
$watermark = imagecreatefrompng($this->watermarkImage);
// getting dimensions of watermark image
$watermarkWidth = imagesx($watermark);
$watermarkHeight = imagesy($watermark);
// placing the watermark 10px from bottom and right
$destX = $this->imageSize[0] - $watermarkWidth - 10;
$destY = $this->imageSize[1] - $watermarkHeight - 10;
// creating a cut resource
$cut = imagecreatetruecolor($watermarkWidth, $watermarkHeight);
imagefill($cut,0,0,0x7fff0000);
// copying that section of the background to the cut
imagecopy($cut, $img, 0, 0, $destX, $destY, $watermarkWidth, $watermarkHeight);
// placing the watermark now
imagecopy($cut, $watermark, 0, 0, 0, 0, $watermarkWidth, $watermarkHeight);
// merging both of the images
imagecopymerge($img, $cut, $destX, $destY, 0, 0, $watermarkWidth, $watermarkHeight, 100);
imagedestroy($watermark);
}
I solved this by converting the image from Gif to Png and then add the watermark.

image manipulation width and height setting

in my project i just do image watermarking or image combine it's working fine and code for that.
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<?php
if(isset($_POST['submit']))
{
// Give the Complete Path of the folder where you want to save the image
$folder="uploads/";
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "$folder".$_FILES["fileToUpload"]["name"]);
$file='uploads/'.$_FILES["fileToUpload"]["name"];
$uploadimage=$folder.$_FILES["fileToUpload"]["name"];
$newname= time();
$ext = pathinfo($_FILES["fileToUpload"]["name"], PATHINFO_EXTENSION);
// Set the thumbnail name
$thumbnail = $folder.$newname.".".$ext;
$imgname=$newname.".".$ext;
// Load the mian image
if ($ext=="png" || $ext=="PNG") {
$source = imagecreatefrompng($uploadimage);
}
else if ($ext=="gif" || $ext=="GIF") {
$source = imagecreatefromgif($uploadimage);
}
else if ($ext=="bmp" || $ext=="BMP") {
$source = imagecreatefrombmp($uploadimage);
}
else{
$source = imagecreatefromjpeg($uploadimage);
}
// load the image you want to you want to be watermarked
$watermark = imagecreatefrompng('uploads/logo1.png');
// get the width and height of the watermark image
$water_width = imagesx($source)/2;
$water_height = imagesy($watermark);
// get the width and height of the main image image
$main_width = imagesx($source);
$main_height = imagesy($source);
$im_middle_w = $main_width/2;
$im_middle_h = $main_height/2;
// Set the dimension of the area you want to place your watermark we use 0
// from x-axis and 0 from y-axis
$dime_x = $im_middle_w - $water_width/2;
$dime_y = $im_middle_h - $water_height/2;
// copy both the images
imagecopy($source, $watermark, $dime_x, $dime_y, 0, 0, $water_width, $water_height);
// Final processing Creating The Image
imagejpeg($source, $thumbnail, 100);
unlink($file);
}
?>
<img src='uploads/<?php echo $imgname;?>'>
</body>
</html>
but problem with setting $water_width and i want set as half of my source image. but when i have source image of less width or more width compare to $water_width it's set it like that. see image when source image width is more.
and when width is less.
so my problem is how to set $water_width as half of source image width?
by Alex your answer it's came up like this.
This will resize watermark to half-width of original image and put it in the centre:
// load the image you want to you want to be watermarked
$watermark = imagecreatefrompng('uploads/logo1.png');
// get the width and height of the watermark image
$water_width = imagesx($watermark);
$water_height = imagesy($watermark);
// get the width and height of the main image image
$main_width = imagesx($source);
$main_height = imagesy($source);
// resize watermark to half-width of the image
$new_height = round($water_height * $main_width / $water_width / 2);
$new_width = round($main_width / 2);
$new_watermark = imagecreatetruecolor($new_width, $new_height);
// keep transparent background
imagealphablending( $new_watermark, false );
imagesavealpha( $new_watermark, true );
imagecopyresampled($new_watermark, $watermark, 0, 0, 0, 0, $new_width, $new_height, $water_width, $water_height);
// Set the dimension of the area you want to place your watermark we use 0
// from x-axis and 0 from y-axis
$dime_x = round(($main_width - $new_width)/2);
$dime_y = round(($main_height - $new_height)/2);
// copy both the images
imagecopy($source, $new_watermark, $dime_x, $dime_y, 0, 0, $new_width, $new_height);
// Final processing Creating The Image
imagejpeg($source, $thumbnail, 100);
imagedestroy($source);
imagedestroy($watermark);
imagedestroy($new_watermark);
You can try imagettftext method, if you don't want any such high perfection in transparency. You can have try of this code. You have to save a font file in your directory, here I used arial.ttf.
$im = imagecreatefrompng("png.png"); //create image data
$font = 'arial.ttf'; //font file name
$randomString = "example.com"; //string need to be shown
$main_width = imagesx($im); //finding width and height
$main_height = imagesy($im);
$posx= $main_width/2; //finding center
$posy = $main_height/2;
$color = imagecolorallocate($im, 200, 200, 200); //Creating color
$size = ($main_width/25)+1; //determine size of font. +1 to avoid 0
$temp = $size*5;
$posx = $posx-$temp; //adjust to average center
imagettftext($im,$size,0, $posx, $posy, $color, $font , $randomString); //apply a text
You have to adjust posx and posy for your text position. Size also can be adjusted with some logics.
$color = imagecolorallocate($im, 0, 0, 0);= black
and $color = imagecolorallocate($im, 255, 255, 255); = white.
You have to adjust this for your required text color.

background of watermark is black on zubrag watermark Script

i am applying watermark onto the image using this code why the background of the watermark image is black after applying watermark even the watermark is in png format and it is transparent this is the script zubrag
$image_path = $filename;
// Where to save watermarked image
$imgdestpath = $destination_folder . basename($filename);
// Watermark image
$img = new Zubrag_watermark($image_path);
$img->ApplyWatermark($watermark_path);
$img->SaveAsFile($imgdestpath);
$img->Free();
function ApplyWatermark($watermark_path) {
$this->watermark_path = $watermark_path;
// Determine image size and type
$size = getimagesize($this->image_path);
$size_x = $size[0];
$size_y = $size[1];
$image_type = $size[2]; // 1 = GIF, 2 = JPG, 3 = PNG
// load source image
$image = $this->ImageCreateFromType($image_type, $this->image_path);
// Determine watermark size and type
$wsize = getimagesize($watermark_path);
$watermark_x = $wsize[0];
$watermark_y = $wsize[1];
$watermark_type = $wsize[2]; // 1 = GIF, 2 = JPG, 3 = PNG
// load watermark
$watermark = $this->ImageCreateFromType($watermark_type, $watermark_path);
// where do we put watermark on the image?
$dest_x = $size_x - $watermark_x - $this->offset_x;
$dest_y = $size_y - $watermark_y - $this->offset_y;
imagecopymerge($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_x, $watermark_y, 100);
$this->image = &$image;
$this->watermark = &$watermark;
$this->image_type = $image_type;
}
Try this - change
imagecopymerge($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_x, $watermark_y, 100);
to use a slightly different function, and remove the final variable:
imagecopy($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_x, $watermark_y);

php imagecopyresampled adds black background

I have a resize image script that takes a 130x81 image and adds it to a 130x130 image, when the imagecopyresampled function runs it adds a black background into the space that is left over, even though the base image is white. Code below, I could really appreciate some help.
The image I am trying to merge onto the 130x130 file php created is:
$width = 130;
$height = 130;
$filename = 'process-add.jpg'; //130x81px jpg
$this->_image = imagecreatefromjpeg($filename);
$background = imagecreatetruecolor(130,130);//create the background 130x130
$whiteBackground = imagecolorallocate($background, 255, 255, 255);
imagefill($background,0,0,$whiteBackground); // fill the background with white
imagecopyresampled($background, $this->_image,(130-$width)/2,(130-$height)/2, 0, 0, $width, $height, $width, $height); // copy the image to the background
ImageJpeg ($background,null,100); //display
I have read on multiple posts to add:
imagealphablending($background, false);
into the code which should fix it, but it doesn't make any difference.
Thanks in advance!
This has been solved. The issue was with teh width and height on the imagecopyresampled call. See the code block below:
<?
ini_set('allow_url_fopen', true);
$filename = 'http://img.yessy.com/1402152287-17201a.jpg'; // 130x81
$image = imagecreatefromjpeg($filename);
list($originalWidth, $originalHeight) = getimagesize($filename);
// Size of image to create
$width = 130;
$height = 130;
$background = imagecreatetruecolor($width, $height);//create the background 130x130
$whiteBackground = imagecolorallocate($background, 255, 255, 255);
imagefill($background,0,0,$whiteBackground); // fill the background with white
imagecopyresampled($background, $image, 0, ($height - $originalHeight) / 2, 0, 0, $originalWidth, $originalHeight, $originalWidth, $originalHeight); // copy the image to the background
header("Content-type: image/jpeg");
ImageJpeg ($background,null,100); //display
?>

Categories