how to create image and header it in PHP? - php

I have one problem with PHP create image. What is wrong with my following code?
<?php
$filename = 'play';
$img = "http://www.slcentral.com/ipod-mp3-player/5.JPG";
$image = imagecreatefromjpeg($img);
$cleft = 0;
$ctop = 45;
$canvas = imagecreatetruecolor(480, 270);
imagecopy($canvas, $image, 0, 0, $cleft, $ctop, 480, 360);
$image = $canvas;
$imageWidth = imagesx($image);
$imageHeight = imagesy($image);
// ADD THE PLAY ICON
$play_icon = "f-play.png";
$logoImage = imagecreatefrompng($play_icon);
imagealphablending($logoImage, TRUE);
$logoWidth = imagesx($logoImage);
$logoHeight = imagesy($logoImage);
// CENTER PLAY ICON
$left = round($imageWidth / 2) - round($logoWidth / 2);
$top = round($imageHeight / 2) - round($logoHeight / 2);
// CONVERT TO PNG SO WE CAN GET THAT PLAY BUTTON ON THERE
imagecopy( $image, $logoImage, $left, $top, 0, 0, $logoWidth, $logoHeight);
imagepng( $image, $filename .".png", 9);
// MASHUP FINAL IMAGE AS A JPEG
$input = imagecreatefrompng($filename .".png");
$output = imagecreatetruecolor($imageWidth, $imageHeight);
$white = imagecolorallocate($output, 255, 255, 255);
imagefilledrectangle($output, 0, 0, $imageWidth, $imageHeight, $white);
imagecopy($output, $input, 0, 0, 0, 0, $imageWidth, $imageHeight);
// OUTPUT TO 'i' FOLDER
header("Content-type: image/jpeg");
imagejpeg($output, $filename . ".jpg", 95);
// UNLINK PNG VERSION
#unlink($filename .".png");
die();
?>
Above code is create one image from giving url and add play icon to it. And I want to access to http://coolrss.com/create-img.php it will show image with play icon.
Please help!

Make sure the path has the right permission or you will get:
PHP Warning: imagepng(): Unable to open 'play.png' for writing: Permission denied in /var/www/coolrss/public_html/create-img.php on line 32
Make sure you have installed GD.
Start your code with this header (after the php tag (<?php))
header("Content-Type: image/jpeg");
At the end (last line) add
imagejpeg($output, NULL, 100);
Your code looks like this now:
<?php
header("Content-Type: image/jpeg");
$filename = 'play';
$img = "http://www.slcentral.com/ipod-mp3-player/5.JPG";
$image = imagecreatefromjpeg($img);
$cleft = 0;
$ctop = 45;
$canvas = imagecreatetruecolor(480, 270);
imagecopy($canvas, $image, 0, 0, $cleft, $ctop, 480, 360);
$image = $canvas;
$imageWidth = imagesx($image);
$imageHeight = imagesy($image);
// ADD THE PLAY ICON
$play_icon = "f-play.png";
$logoImage = imagecreatefrompng($play_icon);
imagealphablending($logoImage, TRUE);
$logoWidth = imagesx($logoImage);
$logoHeight = imagesy($logoImage);
// CENTER PLAY ICON
$left = round($imageWidth / 2) - round($logoWidth / 2);
$top = round($imageHeight / 2) - round($logoHeight / 2);
// CONVERT TO PNG SO WE CAN GET THAT PLAY BUTTON ON THERE
imagecopy( $image, $logoImage, $left, $top, 0, 0, $logoWidth, $logoHeight);
imagepng( $image, $filename .".png", 9);
// MASHUP FINAL IMAGE AS A JPEG
$input = imagecreatefrompng($filename .".png");
$output = imagecreatetruecolor($imageWidth, $imageHeight);
$white = imagecolorallocate($output, 255, 255, 255);
imagefilledrectangle($output, 0, 0, $imageWidth, $imageHeight, $white);
imagecopy($output, $input, 0, 0, 0, 0, $imageWidth, $imageHeight);
imagejpeg($output, NULL, 100);
Screenshot - Works for me

Related

PHP - Resizing and saving PNG images. Some are all black

I'm resizing and saving PNGs with PHP. The first example doesn't work, the PNG ends up being completely black, but the second example works. The first example doesn't have a transparent background but the second one does. Why doesn't the first example work? Is it a problem with the URL?
<?php
$id = "example";
//$originalFile = "https://th.bing.com/th/id/OIP.v_YT6iKMW6sOOVdCxVYQkwHaE8?pid=ImgDet&rs=1.png"; // Doesn't work
$originalFile = "https://cdn.globalxetfs.com/content/files/210618-China_Materials_02.png"; // Works
list($originalWidth, $originalHeight) = getimagesize($originalFile);
$originalImage = #imagecreatefrompng($originalFile);
$newHeight = 255;
$newWidth = 255;
// Create empty canvas
$resizedImage = "";
$resizedImage = imagecreatetruecolor($newWidth, $newHeight); // width, height
// Preserve transparency
imagesavealpha($resizedImage, true);
$color = imagecolorallocatealpha($resizedImage, 0, 0, 0, 127);
imagefill($resizedImage, 0, 0, $color);
// Resize image
imagecopyresampled(
$resizedImage, $originalImage, 0, 0, 0, 0,
$newWidth, $newHeight, $originalWidth, $originalHeight
);
header('Content-type: image/png');
$imageName = $id;
$imageName = $imageName . ".png";
if(imagepng($resizedImage, "images/" . $imageName)){
echo "Image uploaded";
}
?>
The "first example" actually is a JPG file (after the server image rendering) , so you need to use
#imagecreatefromjpeg instead of #imagecreatefrompng
So the codes (working) should be:
<?php
$id = "example";
$originalFile = "https://th.bing.com/th/id/OIP.v_YT6iKMW6sOOVdCxVYQkwHaE8?pid=ImgDet&rs=1.png";
//$originalFile = "https://cdn.globalxetfs.com/content/files/210618-China_Materials_02.png";
list($originalWidth, $originalHeight) = getimagesize($originalFile);
$originalImage = #imagecreatefromjpeg($originalFile);
$newHeight = 255;
$newWidth = 255;
// Create empty canvas
$resizedImage = "";
$resizedImage = imagecreatetruecolor($newWidth, $newHeight); // width, height
// Preserve transparency
imagesavealpha($resizedImage, true);
$color = imagecolorallocatealpha($resizedImage, 0, 0, 0, 127);
imagefill($resizedImage, 0, 0, $color);
// Resize image
imagecopyresampled(
$resizedImage, $originalImage, 0, 0, 0, 0,
$newWidth, $newHeight, $originalWidth, $originalHeight
);
header('Content-type: image/png');
//$imageName = $id;
//$imageName = $imageName . ".png";
//if(imagepng($resizedImage, "images/" . $imageName)){
// echo "Image uploaded";
//}
imagepng($resizedImage);
?>

How to add text on image using PHP

I have this image:
Between the text, I want to add some text. To do that I have the following code:
<?php
error_reporting(E_ALL);
$thumb_src = 'copyright-symbol.png';
$explode = explode('.', $thumb_src);
$extension = strtolower( end ( $explode ) );
$file_name = basename( $thumb_src );
//image_resize_base_width( $relative_url, $relative_url, 350, $extension);
$jpg_image = imagecreatefrompng( $thumb_src );
// set font size
$font = #imageloadfont($jpg_image);
$fontSize = imagefontwidth($font);
$orig_width = imagesx($jpg_image);
$orig_height = imagesy($jpg_image);
// Create your canvas containing both image and text
$canvas = imagecreatetruecolor( $orig_width, ($orig_height + 40 ) );
// Allocate A Color For The background
$bcolor = imagecolorallocate( $canvas, 255, 255, 255 );
// Add background colour into the canvas
imagefilledrectangle( $canvas, 0, 0, $orig_width, ($orig_height + 40), $bcolor );
// Save image to the new canvas
imagecopyresampled( $canvas, $jpg_image, 0, 0, 0, 0, $orig_width, $orig_height, $orig_width, $orig_height );
$font_path = 'font/arial.ttf';
$path = 'upload';
$text = 'cc-by-nd-';
// Allocate A Color For The Text
$color = imagecolorallocate($canvas, 0, 0, 0);
// Print Text On Image
imagettftext( $canvas, 13, 0, 0, $orig_height + 25, $color, $font_path, $text) ;
// Send Image to Browser
imagepng( $canvas, $path . '/' . $file_name );
// Clear Memory
imagedestroy($canvas);
But the code is not adding text to the image. Is there anything wrong in my code?
You may change the codes to
<?php
error_reporting(E_ALL);
header('Content-Type: image/png');
$thumb_src = 'copyright-symbol.png';
$explode = explode('.', $thumb_src);
$extension = strtolower( end ( $explode ) );
$file_name = basename( $thumb_src );
//image_resize_base_width( $relative_url, $relative_url, 350, $extension);
$jpg_image = imagecreatefrompng( $thumb_src );
// set font size
$font = #imageloadfont($jpg_image);
$fontSize = imagefontwidth($font);
$orig_width = imagesx($jpg_image);
$orig_height = imagesy($jpg_image);
// Create your canvas containing both image and text
$canvas = imagecreatetruecolor( $orig_width, ($orig_height + 40 ) );
// Allocate A Color For The background
$bcolor = imagecolorallocate( $canvas, 255, 255, 255 );
// Add background colour into the canvas
imagefilledrectangle( $canvas, 0, 0, $orig_width, ($orig_height + 40), $bcolor );
// Save image to the new canvas
imagecopyresampled( $canvas, $jpg_image, 0, 0, 0, 0, $orig_width, $orig_height, $orig_width, $orig_height );
$font_path = './font/arial.ttf';
//$path = 'upload';
// Create some colors
$white = imagecolorallocate($canvas, 255, 255, 255);
$grey = imagecolorallocate($canvas, 128, 128, 128);
$black = imagecolorallocate($canvas, 0, 0, 0);
imagefilledrectangle($canvas, 0, 0, 399, 29, $white);
// The text to draw
// Replace path by your own font path
$font = 'font/arial.ttf';
$text = 'cc-by-nd-';
// Add some shadow to the text
imagettftext( $canvas, 100, 0, ($orig_width / 2) - 300, ($orig_height/2) , $color, $font_path, $text) ;
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($canvas);
imagedestroy($canvas);
?>

Unwanted dashed black border when rotating image in php

I am getting unwanted dashed black border when I rotate an image. I have tried to remove that but I am not finding any success. I am using the following function for image rotation. I try to preserve transparency. I have provided a image as well.
Here is an Image URL: http://s23.postimg.org/hep2pkol7/border.png
function imageRotation ($source, $rotang)
{
imagealphablending($source, false);
imagesavealpha($source, true);
$rotation = imagerotate($source, $rotang, imageColorAllocateAlpha($source, 0, 0, 0, 127));
imagealphablending($rotation, false);
imagesavealpha($rotation, true);
return $rotation;
}
I call the function something like that:
$rotatedImage = imageRotation($image, 10);
Here is the full code
<?php
// Some settings
$text = "Previously blogging";
$fontFace = 'Days.ttf';
$fontSize = 90;
$angle = 0;
$bbox = calculateTextBox($text, $fontFace, $fontSize, $angle);
$image = imagecreatetruecolor($bbox['width'], $bbox['height']);
// Define some colors
$black = imagecolorallocate($image, 0, 0, 0);
$yellow = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
//Fill the image with background color
imagefill($image, 0, 0, $yellow);
// Draw text
imagettftext($image, $fontSize, $angle, $bbox['left'], $bbox['top'], $black, $fontFace, $text);
$image = imageRotation($image, 20);
$im = imagecreatefromjpeg('weight-loss.jpg');
// Switch antialiasing on for one image
imageantialias($im, true);
$destWidth = imagesx($im);
$destHeight = imagesy($im);
$src_w = imagesx($image);
$src_h = imagesy($image);
$dst_x = ($destWidth - $src_w)/2;
$dst_y = ($destHeight - $src_h)/2;
imagecopy($im, $image, $dst_x, $dst_y, 0, 0, $src_w, $src_h);
header ('Content-Type: image/jpeg');
imagejpeg($im, null, 100);
imagedestroy($im);
imagedestroy($image);
function calculateTextBox($text,$fontFile,$fontSize,$fontAngle)
{
$rect = imagettfbbox($fontSize,$fontAngle,$fontFile,$text);
$minX = min(array($rect[0],$rect[2],$rect[4],$rect[6]));
$maxX = max(array($rect[0],$rect[2],$rect[4],$rect[6]));
$minY = min(array($rect[1],$rect[3],$rect[5],$rect[7]));
$maxY = max(array($rect[1],$rect[3],$rect[5],$rect[7]));
return array(
"left" => abs($minX),
"top" => abs($minY),
"width" => $maxX - $minX,
"height" => $maxY - $minY,
"box" => $rect
);
}
function imageRotation ($source, $rotang)
{
imagealphablending($source, false);
imagesavealpha($source, true);
$rotation = imagerotate($source, $rotang, imageColorAllocateAlpha($source, 0, 0, 0, 127), 0);
imagealphablending($rotation, false);
imagesavealpha($rotation, true);
return $rotation;
}
?>
This is neither a dashed border, nor a border at all actually. This happens because your images are low-resolution, what cause the the rotated borders to "break", because actual pixels don't rotate.
That's what I'm trying to explain:
A line, parallel to the "pixel construction"; one px is three dashes long:
-------------------------------------
It would look smooth.
Rotated line:
---
---
---
---
---
---
---
As you see, due to low resolution, it steps, not smoothly goes down.
If you use the higher resolution, the issue would go away. The visual effect of the "black" border appears because your white image contrasts with the other part of image.

black background is coming for transparent images while creating image in php [duplicate]

This question already has an answer here:
PHP & GD - transparent background being filled with nearby color
(1 answer)
Closed 8 years ago.
I am writing the code for watermark in php using below code but for transaparent images, black background is coming:
$font_path = $_SERVER['DOCUMENT_ROOT'] . "/fonts/arial.ttf"; // Font file
$water_mark_text_2 = "IndustrialStores.com"; // Watermark Text
list($owidth,$oheight) = getimagesize($oldimage_name);
$width = $owidth;
$height = $oheight;
$image = imagecreatetruecolor($width, $height);
$extension = pathinfo($oldimage_name, PATHINFO_EXTENSION);
$extension = strtolower($extension);
if($extension=="jpg" || $extension=="jpeg" ){
$image_src = imagecreatefromjpeg($oldimage_name);
}
else if($extension=="png"){
$image_src = imagecreatefrompng($oldimage_name);
}
else if($extension=="gif"){
$image_src = imagecreatefromgif($oldimage_name);
}
else if($extension=="bmp"){
$image_src = imagecreatefrombmp($oldimage_name);
}
else{
copy($oldimage_name, $new_image_name);
unlink($oldimage_name);
return true;
}
imagecopyresampled($image, $image_src, 0, 0, 0, 0, $width, $height, $owidth, $oheight);
$blue = imagecolorallocate ($image, 179, 179, 179);
$bbox = imageftbbox($width/15, 0, $font_path, 'IndustrialStores.com');
$x = $bbox[0] + (imagesx($image) / 2) - ($bbox[4] / 2);
$y = $bbox[1] + (imagesy($image) / 2) - ($bbox[5] / 2) - 5;
imagettftext($image, $width/15, 0, $x, $y, $blue, $font_path, $water_mark_text_2);
imagejpeg($image, $new_image_name, 100);
imagedestroy($image);
unlink($oldimage_name);
I already tried so many other answers fro stackoverflow like using :
$im = imagecreatetruecolor(55, 30);
$red = imagecolorallocate($im, 255, 0, 0);
$black = imagecolorallocate($im, 0, 0, 0);
// Make the background transparent
imagecolortransparent($im, $black);
but there is no use of all this
Would adding these lines help?
else{
copy($oldimage_name, $new_image_name);
unlink($oldimage_name);
return true;
}
// add these lines here!
imagealphablending($image, false);
imagesavealpha($image, true);
imagecopyresampled($image, $image_src, 0, 0, 0, 0, $width, $height, $owidth, $oheight);
$blue = imagecolorallocate ($image, 179, 179, 179);

center text in image

So I have an image, and I am writing text and a color box onto the image. It works but it's being added to the image in the top right corner, but I need it in the center of the image. I tried changing the x and y variables, but it only moves the text and not the white box.
Here is code
$image_filepath = './kenshin.jpg';
saveImageWithText("Welcome to Eureka!", $color, $image_filepath);
function saveImageWithText($text, $color, $source_file) {
$public_file_path = '.';
// Copy and resample the imag
list($width, $height) = getimagesize($source_file);
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($source_file);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height);
// Prepare font size and colors
$text_color = imagecolorallocate($image_p, 0, 0, 0);
$bg_color = imagecolorallocate($image_p, 255, 255, 255);
$font = $public_file_path . '/arial.ttf';
$font_size = 12;
// Set the offset x and y for the text position
$offset_x = 0;
$offset_y = 20;
// Get the size of the text area
$dims = imagettfbbox($font_size, 0, $font, $text);
$text_width = $dims[4] - $dims[6] + $offset_x;
$text_height = $dims[3] - $dims[5] + $offset_y;
// Add text background
imagefilledrectangle($image_p, 0, 0, $text_width, $text_height, $bg_color);
// Add text
imagettftext($image_p, $font_size, 0, $offset_x, $offset_y, $text_color, $font, $text);
// Save the picture
imagejpeg($image_p, $public_file_path . '/output.jpg', 100);
// Clear
imagedestroy($image);
imagedestroy($image_p);
};
Here is output
Try this. It will help you…
<?php
$img = imagecreatefromjpeg("girl-hugging-the-globe.jpg"); // image.jpg is the image on which we are going to write text ,you can replace this iamge name with your
if(!$img) die("Unabe to load image");
$red = imagecolorallocate($img, 255, 0, 0);
$green = imagecolorallocate($img, 0, 255, 0);
$width = 600;// it will store width of image
$height = 100; //it will store height of image
$fontsize = 6; // size of font
$text = "Block Prints Online"; // Define the text
$pos = ( $width - imagefontwidth($fontsize)*STRLEN($text) );// calculate the left position of the text:
imagestring($img, $fontsize, 200, 150, $text, $red);
header('Content-type: image/jpeg');
imagejpeg($img);//it will output a jpeg image
imagedestroy($img);//it will destroy $img*/
?>

Categories