Save image as file in a folder on the server - php

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');
?>

Related

Use PHP to convert base64 JPEGs to transparent PNG

I want convert base64 jpeg or jpg (white background) to transparent png with my own code :
$img = str_replace(array('data:image/jpeg;base64', 'data:image/jpg;base64', 'data:image/bmp;base64', 'data:image/png;base64'), '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . $fn . str_replace('image/', '.', $type);
$success = file_put_contents($file, $data); //when its done it saves the image data
I'm following this post but image cannot save to dir, modified code:
$img = str_replace(array('data:image/jpeg;base64', 'data:image/jpg;base64', 'data:image/bmp;base64', 'data:image/png;base64'), '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . $fn . str_replace('image/', '.', $type);
$success = file_put_contents($file, $data); //when its done it saves the image data
imagesavealpha($img, true);
$color = imagecolorallocatealpha($img, 0, 0, 0, 127);
imagefill($img, 0, 0, $color);
imagepng($img, 'test.png');
Also, following post but the image show error when opened, modified code:
$img = str_replace(array('data:image/jpeg;base64', 'data:image/jpg;base64', 'data:image/bmp;base64', 'data:image/png;base64'), '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . $fn . str_replace('image/', '.', $type);
$success = file_put_contents($file, $data); //when its done it saves the image data
$image = imagealphablending($file, true);
$transparentcolour = imagecolorallocate($image, 255,255,255);
imagecolortransparent($image, $transparentcolour)

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"]);

PHP gd create image, add to folder and db

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

Add text over an image when uploading it in PHP

I have a pictures website like Quickmeme.com and I would like to add text over images.
I currently let the user upload the picture manually, writing the comments with Paint program in Windows which is a bad idea and I need help ...
here is the code I use for Uploading an image, I am thinking of adding a text field below the upload field so what ever the user writes in that box will be printed on the image as an imagetext ... So how can I do that with php?
<?php if(isset($_POST["upload"])){
$tmp_name = $_FILES["file"]["tmp_name"];
$file_name = basename($_FILES["file"]["name"]);
$random = rand(1, 9999999999);
$directory = "Uploads/" . $random . $file_name;
$time = strftime("%H:%M:%S", time());
$date = strftime("%Y-%m-%d", time());
if(move_uploaded_file($tmp_name, $directory)){
if(mysql_query("")){
$query = mysql_query(""); $fetch = mysql_fetch_array($query);
if(mysql_query("")){
header("Location: index.php");
exit;
}
}
}
} ?>
Here is my website http://www.picturepunches.net
You can try
if (isset($_POST["upload"])) {
$tmp_name = $_FILES["file"]["tmp_name"];
$file_name = basename($_FILES["file"]["name"]);
$random = rand(1, 9999999999);
$directory = "Uploads/" . $random . $file_name;
$time = strftime("%H:%M:%S", time());
$date = strftime("%Y-%m-%d", time());
switch (strtolower(pathinfo($file_name, PATHINFO_EXTENSION))) {
case "jpg" :
$im = imagecreatefromjpeg($_FILES["file"]["tmp_name"]);
break;
case "gif" :
$im = imagecreatefromgif($_FILES["file"]["tmp_name"]);
break;
case "png" :
$im = imagecreatefrompng($_FILES["file"]["tmp_name"]);
break;
default :
trigger_error("Error Bad Extention");
exit();
break;
}
$font = 'verdana.ttf';
$grey = imagecolorallocate($im, 128, 128, 128);
$red = imagecolorallocate($im, 255, 0, 0);
// Add some shadow to the text
imagettftext($im, 10, 0, 11, 20, $grey, $font, $date);
imagettftext($im, 10, 0, 10, 35, $grey, $font, $time);
imagettftext($im, 10, 0, 10, 50, $red, $font, $random);
// imagepng($im);
imagedestroy($im);
if (move_uploaded_file($tmp_name, $directory)) {
if (mysql_query("")) {
$query = mysql_query("");
$fetch = mysql_fetch_array($query);
if (mysql_query("")) {
header("Location: index.php");
exit();
}
}
}
}
Output
Uploaded Final
First, check if you have the GD extension installed, next,
Use the GD functions
//Loading the file
$rImg = ImageCreateFromJPEG("MyPicture.jpg");
//Font Color (black in this case)
$color = imagecolorallocate($rImg, 0, 0, 0);
//x-coordinate of the upper left corner.
$xPos = 100;
//y-coordinate of the upper left corner.
$yPos = 30;
//Writting the picture
imagestring($rImg,5,$xPos,$yPos,"My text in the picture",$color);
//The new file with the text
header('Content-type: image/jpeg');
imagejpeg($rImg, NULL, 100);
you can use this tutorial
http://blog.doh.ms/2008/02/12/adding-text-to-images-in-real-time-with-php/

'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