How to encode the image file in PHP - php

i am using one file upload form field,from that field i want to encode the filename,don't to want to move the any temporary folder,directly i want to insert the database,while display the image directly fetch DB and display the website,I want encode like data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA
$path = basename($_FILES['file']['name']);//here i am getting filename
$im = file_get_contents($path);//here i am getting false
$imdata = base64_encode($im); // so can't here encode the filename
$horoscope = array("encode" => $imdata,"path" =>$path,"getcontents" =>$im);
echo json_encode($horoscope);

PHP uploads the file into a temporary file and tells you where that is in the $_FILES['file']['tmp_name'] the $_FILES['file']['name'] holds the file name that the user called the file on their system, the one they select in the browser.
So if you want to grab the file before you have done a move_uploaded_file() on the file use $_FILES['file']['tmp']
$path = $_FILES['file']['tmp_name'];
$im = file_get_contents($path);
$imdata = base64_encode($im);
$horoscope = array("encode" => $imdata,
"path" =>$path,
"getcontents" =>$im
);
echo json_encode($horoscope);
I was not sure what you were passing back the $path for, so that may still need to be $_FILES['file']['name'].
$horoscope = array("encode" => $imdata,
"path" => $_FILES['file']['name'],
"getcontents" => $im
);
RE:Comment 1
I assume you want to store the base64encoded version of the file to the database so that will be $imdata
RE:Comment 2
To get the extension of the incoming file use pathinfo()
$path = $_FILES['file']['tmp_name'];
$file_parts = pathinfo($path);
$extn = $path_parts['extension'];
But beware, just because the extension says .png is not actual guarantee that it is a .png file

Related

Set an extension and make full file from base64 encode to able to use laravel file method in php

I had base64 encoded data.
Look my code, please.
First of all, see my code.
$data = "data:image/png;base64,iVBORw0KGgoAAAA..........";
$image_array_1 = explode(";", $data);
$image_array_2 = explode(",", $image_array_1[1]);
$data = base64_decode($image_array_2[1]);
$imageName = uniqid().time().".png";
I want to set an extension .png to complete my file so that I can count this file extension by laravel method $image->getClientOriginalExtension() and others laravel file methods.
sorry for miss spell of language.
Hope I make you understand.
This works, although I cannot say if it's the best way to go about it. It's a full working example with a 1x1 black pixel png image. This assumes you already removed the data:image/png;base64, portion from the image data.
$data = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR
42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=');
// Create a temp file and write the decoded image.
$temp = tmpfile();
fwrite($temp, $data);
// Get the path of the temp file.
$tempPath = stream_get_meta_data($temp)['uri'];
// Initialize the UploadedFile.
$imageName = uniqid().time().".png";
$file = new \Illuminate\Http\UploadedFile($tempPath, $imageName, null, null, true);
// Test if the UploadedFile works normally.
echo $file->getClientOriginalExtension(); // Shows 'png'
$file->storeAs('images', 'test.png'); // Creates image in '\storage\app\images'.
// Delete the temp file.
fclose($temp);

How to save Data Url like save $_FILES in php

How to save DATA URL like save $_FILES in php?
my code is:
$dataurl = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAB...."
$image_content = base64_decode(str_replace("#^data:image/\w+;base64,#i","", $dataurl)); // remove "data:image/png;base64,"
$tempfile = tmpfile(); // create temporary file
$filesize = fwrite($tempfile, $image_content); // fill data to temporary file
$metaDatas = stream_get_meta_data($tempfile);
$tmpFilename = $metaDatas['uri'];
$file = array(
'name' => 'MyFile.jpg',
'type' => 'image/jpeg',
'tmp_name' => $tmpFilename,
'error' => 0,
'size' => $filesize,
);
move_uploaded_file($file['tmp_name'], $location);
The problem maybe in move_uploaded_file($file['tmp_name'], $location);
Read the description in PHP guide for move_uploaded_file before using this function.
The important part is (qoute from the description):
This function checks to ensure that the file designated by filename is
a valid upload file (meaning that it was uploaded via PHP's HTTP POST
upload mechanism). If the file is valid, it will be moved to the
filename given by destination.
The file you created was NOT uploaded via PHP HTTP POST upload mechanism, it was a temporary file you have created yourself, so you can not move it with this function.
If the data arrives as a Base64 encoded string, you can just write the file directly to the desired location. The move_uploaded_file function is ONLY for files uploads, and Base64 strings sent in the body are not files.

Retrieving external image and saving locally results in distorted image

Stuck on this one. I have this function below that simply takes $ImageSrc which is an external image from anywhere, eg imgur, and then saves it locally (this is not a scraper, I'm allowing people to attach images to their profiles)
public function UploadScreenshot($ImageSrc, $Title, $Description = false) {
$RandomName = substr(md5($Title . time()), 0, 20);
$UploadDir = "/home/vanrust/public_html/Screenshots/";
$file = pathinfo($ImageSrc);
$ext = $file["extension"];
if (!in_array($ext, array('jpg','png','bmp','jpeg'))) return array("error" => "Invalid File Type");
$RandomName = "{$RandomName}.{$ext}";
$image = file_get_contents($ImageSrc);
file_put_contents($UploadDir . $RandomName, $image);
}
The result of the file no matter what is unrecognizable.
The image:
After UploadScreenshot() has retrieved it:
Try to use rename() to move the original file to the new location and rename it.
$file = pathinfo($ImageSrc);
$ext = $file["extension"];
if (!in_array($ext, array('jpg','png','bmp','jpeg'))) return array("error" => "Invalid File Type");
$RandomName = "{$RandomName}.{$ext}";
rename($UploadDir . $RandomName, $ImageSrc);
}
Alternatively, you can use move_uploaded_file() if your $ImageSrc does contain a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism).
file_put_contents() needs to be used with caution. A single offset (in binary codes) at the beginning or at the end of the file will significantly alter the picture. It requires a validation at the end to compare both files bytes.

How to add an image from url to temp?

I am using the SimpleImage.php class from: http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/ , to resize, compress and save the images.
Usually using it with an image from input:
$tmp_dir = $_FILES['file']['tmp_name'];
$file_name = 'something.jpg';
include('SimpleImage.php');
$image = new SimpleImage();
$image->load($tmp_dir);
$image->resizeToWidth($width);
$image->save('imgd/l'.$file_name);
But how can I deal just with the image url? (from another website)
$img = file_get_contents($url);
The above $img variable keeps the actual image.
So how can I save it to temp to use it?
If this is the right way.
If it's possible not to have to change SimpleImage.php class.
With tempnam()
Creates a file with a unique filename, with access permission set to
0600, in the specified directory. If the directory does not exist,
tempnam() may generate a file in the system's temporary directory, and
return the name of that.
<?php
$tmpfname = tempnam("/tmp", "UL_IMAGE");
$img = file_get_contents($url);
file_put_contents($tmpfname, $img);
include('SimpleImage.php');
$image = new SimpleImage();
$image->load($tmpfname);
$image->resizeToWidth($width);
$image->save('imgd/l'.$file_name);
?>

uploadifive - change filename on upload

I am using uploadifive to upload images - however I want to change the name of the images to "newimage" I am not sure where or how to do this with what is provided - this is the last modification I need to deploy.
You're going to need to do the name change in the PHP script that handles the uploading (I'm assuming your using PHP since that's uplidfy's standard). It can be a bit tricky because you have to separate the incoming file name from it's extension. This should be enough to get you started.
$theFile = $_FILES['file_upl']['name'];
$tempFile = $_FILES['file_upl']['tmp_name'];
$newName = "newname";
$saveDir = $_SERVER['DOCUMENT_ROOT']."/images/";
//Function returns the extension from the '.' on
function get_ext($from_file) {
$ext = strtolower(strrchr($from_file,'.'));
return $ext;
}
//This will rename the file to $newname + the extension
$theFile = $newname.get_ext($theFile);
//Save the file
move_uploaded_file($tempFile,$saveDir.$theFile);
$file = 'uploaded_img.jpg';
$remote_file = 'Saved.txt';
ftp_put($conn_id, $remote_file, $file, FTP_ASCII)
just change the name of the remote file

Categories