PHP gd create image, add to folder and db - php

I have created this image:
header('content-type: image/jpeg');
//Load our base image
$image = imagecreatefrompng(BASEPATH . '../images/blogMainImage.png');
//Setup colors and font file
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
$font_path = BASEPATH . '../fonts/ACME Explosive.ttf';
//Get the positions of the text string
$text = wordwrap($_POST['title'], 15, "\n");
//Create Month
imagettftext($image, 16, 0, 20, 40, $black, $font_path, $text);
//Create final image
imagejpeg($image, '', 100);
//Clear up memory;
imagedestroy($image);
I have successfully created the image. Now what i need to do is to get the created image filename, save the filename to db and file to a upload folder..
Is it possible?
Thanks.

This is probably what you need:
$name ='myimage.png';
// make sure you create a folder called **images** in the directory where the script is and give it write permissions.
$save_path = realpath(dirname(__FILE__).'/images/'.$name);
// I assume that you want to use the image in a website.
$imageurl = "http://www.mysite.com/images/$name";
imagejpeg($im, $save_path); // saves the image to **this_dir/images/myimage.png**
imagedestroy($im);
in regards to store the filename in a db, you'll need to set the the database first and then use something like this:
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO Photos(save_path, imageurl)
VALUES ("$save_path", "$imageurl")");
mysqli_close($con);

I think you can also add this codes:
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysql_query("UPDATE lms_users SET userPic='$actual_image_name' WHERE userId='$_SESSION[email]'");
}
else
echo "failed";

you need a name and a route to save the image:
// Save the image as 'test.jpg'
$name_image="test.jpg";
imagejpeg($im, 'folder_to_save_image/'.$name_image);
and you can save the name in your data base
check imagejpeg

Related

Save image as file in a folder on the server

I have this code running...
$im = imagecreatefromstring($arr['IMAGE']->load());
$result = $arr['IMAGE']->load();
echo $result;
exit();
and this code is showing the image on the browser. My question is...how to save as a file and save on the server?
I am using this code and it is saving as a file but there isn't a image.
define('UPLOAD_DIR', 'testuploads/');
// $img = str_replace('data:image/png;base64,', '', $result);
// $img = str_replace(' ', '+', $img);
$data = imagejpeg($result);
$file = UPLOAD_DIR . uniqid() . '.jpeg';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
use imagejpeg($result, $file) or imagepng if it is a png, instead of file_put_contents.
(where $result is your img, and $file your path+file name)
EDIT: see doc: http://php.net/manual/en/function.imagejpeg.php
example:
<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
// Save the image as 'simpletext.jpg'
imagejpeg($im, 'simpletext.jpg');
?>

Php Photos Edit

Hello i have a folder with a 3000 photos and i need a script that add my site logo buttom the image, i have script to edit images but i need a one that open images and make the procces,
my script
<?php
$logo = imagecreatefrompng("logo.png");
header('Content-type: image/jpg');
$image = imagecreatefromjpeg("image.jpg");
imagecopy($image, $logo, 132, 95, 0, 0, 25, 25);
imagejpeg($image);
imagedestroy($image);
?>
also if anybody have a program for windows please send to me.
I would do it like this:
function add_png_logo(){
$dir = APPPATH.'assets/img/'; # Where your PNG photos are
$dirUpload = APPPATH.'assets/uploads/'; # Where they will be saved
$baseUrl = 'http://127.0.0.1/tests/assets/uploads/'; # Base to link merged images
# Where the work begins
$iteractor = new DirectoryIterator($dir);
$ext = ['png'];
$i = 0;
# Function to save individual files
function save_png($getFilename,$getFilePath){
$medida = array('width'=>'1024','height'=>'1024',);
// Creates a temp image
$TempPngFile = imagecreatetruecolor($medida['width'], $medida['height']);
# Defines a transparent color to fill all image
$TransparentColor = imagecolorallocatealpha($TempPngFile, 0, 0, 0, 127);
imagefill($TempPngFile, 0, 0, $TransparentColor);
# Forces transparency definition
imagealphablending($TempPngFile, true);
imagesavealpha($TempPngFile, true);
# Open image
$logo = imageCreateFromPng(APPPATH.'cache/mark.png');
# Fix transparency definitions
imageAlphaBlending($logo, true);
imageSaveAlpha($logo, true);
# Open image
$img2 = imageCreateFromPng($getFilename);
# Forces transparency definition
imageAlphaBlending($img2, true);
imageSaveAlpha($img2, true);
# insert $logo and $img2 in $TempPngFile and setting positioning
imagecopy($TempPngFile, $img2, 0, 0, 0, 0, imagesx($img2), imagesy($img2));
imagecopy($TempPngFile, $logo, 25, 25, 0, 0, imagesx($logo), imagesy($logo));
# Save final image to $getFilePath
imagepng($TempPngFile, $getFilePath);
// Destroy images
imageDestroy($TempPngFile);
imageDestroy($logo);
imageDestroy($img2);
}
# Loop in $dir, get all PNG files to overlap $logo on left top
foreach ($iteractor as $entry) {
if ($entry->isFile()) {
if (in_array($entry->getExtension(), $ext)) {
$getFilename = $dir.$entry->getFilename();
$getImageName = $entry->getFilename().'_'.$i++.'_.png';
$getFilePath = $dirUpload.$getImageName;
save_png($getFilename, $getFilePath);
echo 'Created image: '.$getImageName.'<br>';
}
}
}
}
OBS: It uses the php-gd extension. And certainlly there is a way to convert JPG to PNG before overlap the files (or you should first convert your 3000 photos to PNG), but I'm too lazy now, and it works! And now it's on your hands!

PHP Add text to image and save

I am attempting to have a PHP file add an ID to an uploaded image and resave the image. For some reason the code below is not working even though it looks very similar to other examples I have found online. What am I doing wrong?
$productStyle = isset($_POST['productStyle']) ? encodechars($_POST['productStyle']) : "";
$productSize = isset($_POST['productSize']) ? encodechars($_POST['productSize']) : "";
$itemID = isset($_POST['itemID']) ? encodechars($_POST['itemID']) : "";
if ($productStyle!=""){
$fileLocation ='/home/abcdefg/public_html/uploads/'.$productStyle;
$photoLoc = $fileLocation . "/" . $itemID.".png";
if(!is_dir($fileLocation)) {
mkdir($fileLocation , 0777); //create directory if it doesn't exist
}
//add id to image
$im = imagecreatefrompng($_FILES["file"]["tmp_name"]);
$font = 'Verdana.ttf'; //<-- this file is included in directory
$grey = imagecolorallocate($im, 128, 128, 128);
imagettftext($im, 10, 0, 11, 20, $grey, $font, $itemID);
imagepng($im, $photoLoc); //<-- This does not work
imagedestroy($im);
//move_uploaded_file($_FILES["file"]["tmp_name"], $photoLoc); //<-- This will move the file to the correct folder but without the text added
}
first, move the original file and then remove after watermarking.
$productStyle = isset($_POST['productStyle']) ? encodechars($_POST['productStyle']) : "";
$productSize = isset($_POST['productSize']) ? encodechars($_POST['productSize']) : "";
$itemID = isset($_POST['itemID']) ? encodechars($_POST['itemID']) : "";
if ($productStyle!=""){
$fileLocation ='/home/abcdefg/public_html/uploads/'.$productStyle;
$photoLoc = $fileLocation . "/" . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]);
if(!is_dir($fileLocation)) {
mkdir($fileLocation , 0777); //create directory if it doesn't exist
}
//add id to image
$im = imagecreatefrompng($photoLoc);
$font = 'Verdana.ttf'; //<-- this file is included in directory
$grey = imagecolorallocate($im, 128, 128, 128);
imagettftext($im, 10, 0, 11, 20, $grey, $font, $itemID);
imagepng($im, $photoLoc); //<-- This does not work
imagedestroy($im);
unlink($photoLoc);
//move_uploaded_file($_FILES["file"]["tmp_name"], $photoLoc); //<-- This will move the file to the correct folder but without the text added
}
or just change
$im = imagecreatefrompng($_FILES["file"]["tmp_name"]);
to
$im = imagecreatefrompng($_FILES["file"]["name"]);

How to resize an uploded image before using it in an imagecreatefromjpeg function?

I have a code that allows file upload and some text input. It uses the uploaded file in an imagacreatefromjepg and imagecopymerge. I want to resize the uploaded file to a definite size which is 255x175. how can i make it? Here is what is have:
$now = time();
while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))
{
$now++;
}
// now let's move the file to its final and allocate it with the new filename
#move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename)
or error('receiving directory insuffiecient permission', $uploadForm);
$upload = $uploadFilename;
$im = imagecreatefromjpeg("bg.jpg");
$img2 = imagecreatefromjpeg($upload);
$black = imagecolorallocate($im, 0, 0, 0);
$font = 'arialbi.ttf';
$font2 = 'ariali.ttf';
imagettftext($im, 24, 0, 50, 280, $black, $font, $title);
imagettftext($im, 10, 0, 320, 362, $black, $font, $namehere);
imagecopymerge($im, $img2, 30, 350, 0, 0, imagesx($img2), imagesy($img2), 100);
$date_created = date("YmdHis");//get date created
$img_name = "-img_entry.jpg"; //the file name of the generated image
$img_newname = $date_created . $img_name; //datecreated+name
$img_dir =dirname($_SERVER['SCRIPT_FILENAME']) ."/". $img_newname; //the location to save the image
imagejpeg($im, $img_dir , 80); //function to save the image with the name and quality
$newpath = "/home3/site/public_html/mainfolder/image_entry/";//path to another folder
$newdir = $newpath.$img_newname;
copy ($img_dir, $newdir); //copy to new folder
imagedestroy($im);
Hope you can help me fix this. I have raed the posts Resize image before uploading PHP and Php resize width fix. But I dont know how to apply it in my case. Thanks for any and all help.
just after: imagecopymerge($im,... line
$mini_width = ...;// calculate desirable width
$mini_height = ...;// calculate desirable height
$mini_img = #ImageCreateTrueColor($mini_width, $mini_height);
imagecopyresampled($mini_img, $img2, 0, 0, 0, 0, $mini_width, $mini_height, imagesx($img2), imagesy($img2));
next line is $date_created = date(...
change imagejpeg($im, $img_dir , 80); to:
imagejpeg($mini_img, $img_dir , 80);
and finally change imagedestroy($im); to imagedestroy($mini_img);
Actually, you can, but not have to call imagedestroy() for all the resource images created above.

'imagecreatefrompng' is outputting a crashed image

I’m having problems with gd library in PHP when I try to do a imagecratefrompng. I’m running a script where the user input a text and it is added to a pre-created image. Problem is, when I output the image the image show as broken.
Can anyone help pointing if something is wrong with my script/image?
The image is a PNG, 600x956, 220kb file size.
GD Library is enabled. PNG, JPEG, GIF support are enabled.
Here is the code.
// Text inputed by user
$text = $_POST['text'];
// Postion of text inputed by the user
$text_x = 50;
$text_y = 817;
// Color of the text
$text_color = imagecolorallocate($img, 0, 0, 0);
// Name of the file (That is in the same directory of the PHP file)
$nomeDaImagem = "Example";
$img = imagecreatefrompng($nomeDaImagem);
//Text is retrieved by Post method
imagestring($img, 3, $text_x, $text_y, $text, $text_color);
header("Content-type: image/png");
imagepng($img);
imagedestroy($img);
There are a number of issues with your script:
You attempt to allocate the colour to the image, before you have actually created the image.
Your string to be written is in the variable $nome, but you are printing $text.
You don't check if $_POST['text'] exists, which may result in a Notice-level error.
You don't check if the file exists, which may result in a Warning-level error.
Here's an example of your code, fixed:
// Text inputed by user
$nome = isset($_POST['text']) ? $_POST['text'] : "<Nothing to write>";
// Postion of text inputed by the user
$text_x = 50;
$text_y = 817;
// Name of the file (That is in the same directory of the PHP file)
$nomeDaImagem = "Example";
$img = file_exists($nomeDaImagem)
? imagecreatefrompng($nomeDaImagem)
: imagecreate(imagefontwidth(3)*strlen($nome)+$text_x,imagefontheight(3)+$text_y);
// Color of the text
$text_color = imagecolorallocate($img, 0, 0, 0);
//Text is retrieved by Post method
imagestring($img, 3, $text_x, $text_y, $nome, $text_color);
header("Content-type: image/png");
imagepng($img);
imagedestroy($img);
Read more:--
http://php.net/manual/en/function.imagecreatefrompng.php
http://www.php.net/manual/en/function.imagecreatefromstring.php
or try this
<?php
function LoadPNG($imgname)
{
/* Attempt to open */
$im = #imagecreatefrompng($imgname);
/* See if it failed */
if(!$im)
{
/* Create a blank image */
$im = imagecreatetruecolor(150, 30);
$bgc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
/* Output an error message */
imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
}
return $im;
}
header('Content-Type: image/png');
$img = LoadPNG('bogus.image');
imagepng($img);
imagedestroy($img);
?>

Categories