I'm saving some of my image in to mysql database using base64_encode.
now I want to restore them back to file system.
How can I do that?
Edit...!
Ok, I did not explain enough.
I use this code to encode my image and save them in to a blob table:
function base64_encode_image ($imagefile) {
$imgtype = array('jpg', 'gif', 'png');
$filename = file_exists($imagefile) ? htmlentities($imagefile) : die('Image file name does not exist');
$filetype = pathinfo($filename, PATHINFO_EXTENSION);
if (in_array($filetype, $imgtype)){
$imgbinary = fread(fopen($filename, "r"), filesize($filename));
} else {
die ('Invalid image type, jpg, gif, and png is only allowed');
}
return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
}
and use this code to show my image in browser:
if (!isset($_GET['id']) && !ctype_digit($_GET['id'])){
die('Error');
} else {
require_once( addslashes(dirname(dirname(__FILE__)) . '/config.php') );
require_once( addslashes(dirname(__FILE__) . '/Functions.php'));
$row = mysql_fetch_array(mysql_query ("SELECT `id`,`cover_small` FROM `om_manga` WHERE `Active` = '1' AND `id` = '".sql_quote($_GET['id'])."'"));
if (isset($row['id'])){
header("Content-type: image/jpeg");
readfile($row['cover_small']);
} else {
die('Error');
}
}
Now i want them back to a jpg file.
The size of all those image are less then 3kb.
Use PHP's base64_decode() function to convert the encoded data back to binary.
Since base64_decode returns a string, you can use file_put_contents() to write the decoded contents to a file.
It makes me wonder why you're storing the image base64 encoded if you're not using it in that format. You could just as easily store the image in binary format in a binary blob column.
Base64 encoding adds a 33% character overhead (not bytes).
Edit for revised question
The answer to your second question is subjective without context. Without knowing the details of your system, I can't recommend whether you should extract the images.
Decode it the same way you encoded it...
base64_decode()
You might want to store the file extension of the image when writing it to the database so that you can restore it accurately. Just concatenate the new name with the existing extension.
What you should so is something similar to this :
// Retrieved values from database
$encodedImg = $sqlResult['encoded_img'];
$ext = $sqlResult['encoded_img_ext'];
// Concatenate new file name with existing extention
// NOTE : This parameter is a full path. Make sure that the folder
// you are writing the file to has the correct permissions allowing the
// script write access.
$newImagePath = "/some/path/on/the/servers/filesystem/";
$newImageName = $newImagePath."decoded_image.".$ext;
// Saving the decoded file with the new file name.
file_put_contents($newImageName, base64_decode($encodedImg));
Related
I am using Glide to deliver image content from one of my sites. This is working well and I have now built a file upload so that admins can upload images to the site for subsequent download.
Some of the images that admins will upload will be much larger than I need (or want the overhead of storing on the server), so I want to downsize them, preferably during the upload routine or failing that, just after they have been saved to their new location (storage/app/images)
So, I've been hacking around with intervention for instance without much success because of my poor understanding of the file names and paths available from getClientOriginalName/Extension etc.
Could anyone show me a pattern for this which would work well. Ideally I'd love to include something like I've seen on others' examples like...
$img = Image::make('foo.jpg')->resize(300, 200);
... in the correct place in my code
foreach($files as $file) {
$fileExtension = $file->getClientOriginalExtension();
$fileMimeType = $file->getMimeType();
if(in_array($fileExtension, $allowableExtensions)) {
if(in_array($fileMimeType, $allowableMimes)) {
array_push($dbFileList, $file->getClientOriginalName());
$newImage = '/images/' . $propertyCode . '/' . $file->getClientOriginalName();
Storage::put('/images/' . $propertyCode . '/' . $file->getClientOriginalName(), file_get_contents($file));
}else{
$errorMessage = 'At least one file was not an image, check your results...';
}
}else{
$errorMessage = 'At least one file was not an image, check your results...';
}
}
Update 1:
Storage::put('/images/' . $propertyCode . '/' . $file->getClientOriginalName(), file_get_contents($file));
$img = Image::make($file);
Storage::put('/images/new/' . $file->getClientOriginalName(), $img);
This updated code outputs the files to the /new directory and all looks fine, but the output files have 'zero bytes'. What am I missing?
Update 2: Final code
The final answer (after using the proper code provided by contributors) was that:
I had to move my app from virtual box on to the dev machine (iMac) to prevent extra confusion with paths
The path for the images must exist prior to making the ->save()
The path variable must be set in advance of the ->save()
I don't need the Storage::put at all, so the larger file never ends up on the server.
Then this final code started to work.
$path = storage_path('app/smallpics/')."/".$file->getClientOriginalName();
$img = Image::make($file)->resize(300,200)->save($path);
Much thanks to all of you. You make my Laravel learning curve a bit less terrifiying!!
You can use Intervention to manipulate your image (resize etc.) as
$new_image = Image::make($file)->resize(300,200)->save('/path/to/save');
The image upload and resize work flow is like:
Upload the image from tmp to your directory.
Make a copy of that image by setting the height, width, quality and save it in the same or some other directory.
Delete the original image.
So as per your code flow:
Storage::put('/images/' . $propertyCode . '/' . $file->getClientOriginalName(), file_get_contents($file));
after this code, put the image compress code and after that delete the original image.
you can use Intervention or just use imagemagick convert command line command for resize or convert.
Pay attention to comments :
public function saveUploadPic(Request $request)
{
$pic = $request->file('<NAME_OF_FILE_INPUT_IN_HTML_FORM>');
#check for upload correctly
if(!$pic->isValid())
{
throw new Exception("IMAGE NOT UPLOADED CORRECTLY");
}
#check for mime type and extention
$ext = $pic->getClientOriginalExtension();
$mime = $pic->getMimeType();
if(!in_array($mime, $allowedMimeTypeArray) || !in_array($ext, $allowedExtArray))
{
throw new Exception("This Image Not Support");
}
#check for size
$size = $pic->getClientSize() / 1024 / 1024;
if($size > $allowedSize)
{
throw new Exception("Size Of Image Is More Than Support Size");
}
########################YOU HAVE TWO OPTION HERE###################
#1- save image in a temporary location with random hash for name if u need orginal image for other process
#below code save image in <LARAVEL_APP_PATH>/storage/app/tmp/pics/
$hash = md5(date("YmdHis").rand(1,10000));
$pic->storeAs('tmp/pics', $hash.'.'.$ext);
#Then resize or convert it
$img = Image::make(storage_path('app/tmp/pics/'.$hash.'.'.$ext))->resize(300, 200);
#save new image whatever u want
$img->save('<PATH_TO_SAVE_IMAGE>');
#after u finish with orginal image delete it
Storage::delete(storage_path('app/tmp/pics/'.$hash.'.'.$ext);
#2- Or just use below for resize and save image witout need to save in temporary location
$img = Image::make($pic->getRealPath())->resize(300,200);
$img->save('<PATH_TO_SAVE_IMAGE>');
}
if you want to use convert see this link.
I have file contents which I am receiving from my form in string form (base64), and now before using file_put_contents() function to save the file, I wanna know the information related to it, like it's size and mimetypes and so on.
So the question is how to retrieve a file's information just by it's data(base 64 string)
For ex, let's say I have this string:-
Object {files: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAvwA…Fb+kScAm4BFwC6yGB/w9uNEwUj3EmdQAAAABJRU5ErkJggg==", text: "hi"}files: "data:image/png;base64,iVBORw0KGgoAAAANS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ZUbAjzbCmwB6EahGBPqwRjt9p7seAOgH2G9DMeuuFV6TS8AlsCYScMC/Jh3tj+kScAnMIQFSgubdPIk52QGmAfQYqLts6z5EM2nPBXgloJA4fWeOAeSXugRcAi6B5UrAAf9y5e93dwm4BNZJAgD5TL1Ja/+8XoOu5Mc4ASglOBAUPARFpKvn83pcAi4Bl8AaS8AB/xp3vj+6S8AlsAQJ2BShdoOtJTTFb+kScAm4BFwC6yGB/w9uNEwUj3EmdQAAAABJRU5ErkJggg=="text: "hi"__proto__: Object
54:783
$encoded_data = 'iVBORw0KGgoAAAANSUhEUgAAAvwA…Fb+kScAm4BFwC6yGB/w9uNEwUj3EmdQAAAABJRU ....';
$size = strlen(base64_decode($encoded_data));
remember base64 encoding increases the original data in size by about 33%
Now we can write a function -
function getFileSize($base64string){
$bytes = strlen(base64_decode($base64string));
$roughsize = (((int)$bytes) / 1024.0)* 0.67;
return round($roughsize,2);
}
this function will return filesize in Kb.
Now to know the Mime Type you can use Fileinfo
$imgdata = base64_decode($encoded_data);
$f = finfo_open();
$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);
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.
I want to return an image over an URL like http://placehold.it/500x500.
I have my URL http://example.inc/assets/image/35345, which calls an action on controller. The controller get some data (name, id, etc.) from database and also a binary string of the image content.
On the frontend site, i have my img tag, where i want to call the url in my src attribute.
<img src="http://example.inc/assets/image/35345">
Some more information, i use slim PHP Framework and my server is an ubuntu 13.x system (vagrant etc.). I am an typically frontend developer and dont have good skills # PHP.
Following snippets works:
$file = fopen($name, 'wb');
fwrite($file, $binaryData);
fclose($file);
but I dont want to generate files in a directory. Is this possible?
EDIT: Content-Type and Content-Length Headers are set, that is not the problem.
Grab the contents of the image, base_64 encode it, then return a a base64 image.
$file = file_get_contents($name);
list($width, $height, $type, $attr) = getimagesize($file);
echo '<img src="data:image/'.$type.';'.base64_encode($file).'"/>';
You should upload images in directory by using something like this. This code will upload your image in directory.
if ($_FILES['file']['name'] != "") {
$filename = $_FILES['file']['name']; //getting name of the file from form
$filesize = $_FILES['file']['size'];
$info = new SplFileInfo($filename);
$ext = $info->getExtension();
$filesize1 = ($filesize * .0009765625) * .0009765625;
if (!($ext == 'jpg' || $ext == 'png' || $ext == 'jpeg')) {
//set some error message and redirect
}
if ($filesize1 >= 5.0) {
//set message image size should be less than 5 mb
}
$target_path = $_SERVER['DOCUMENT_ROOT'] . "../images/profile_images/";
move_uploaded_file($_FILES['file']['tmp_name'], "$target_path" . $_FILES['file']['name']) or
die("Could not copy file!");
}
Insert image name(with extension) in database.($filename here)
Fetch image name from database and store in variable($profile_image here),use it in img src.
<a href='../images/profile_images/$profile_image'><img alt='Avatar' src='../images/profile_images/$profile_image'></a>
You can use only Anchor tag to redirect user on image in another tab in browser.
hope this answer will help you.
Because i had an mssql database with iso charset i have converted all of my results to utf-8, the problem was, that the bytestring also converted to utf-8.
after non converting the bytestring i also returned the bytestring and set the header content type to image/extension
Providing user to upload images has wide usage, however, checking file extension and MIME type not guarantee correct file type.
Alternative:
I used imagejpeg() and imagecreatefromjpeg() functions for creating the image from $_FILE['userfile']['tmp_name'] and then saving it in images/ dir. In this case, I ignored move_uploaded_file() function.
Are still this code vulnerable to fake image uploading attack?
$filename = $_FILE['inputfile']['name'];
$upload_path = 'images/';
//extract extension
$ext = strtolower(substr($filename, strrpos($filename, '.') + 1));
// return mime type ala mimetype extension
$finfo = finfo_open(FILEINFO_MIME_TYPE);
//get MIME type of the given file
$mime = finfo_file($finfo, $filename);
//close finfo
finfo_close($finfo);
if (is_uploaded_file($_FILES['inputfile']['tmp_name'])) {
//first check: file extension and mime type
if(!in_array($ext, array('jpeg', 'jpg', 'gif', 'png')) && !in_array($mime, array('image/jpeg', 'image/gif', 'image/png')) ){
die("Error1: Invalid Image type");
}
if($ext == 'jpeg' || $ext == 'jpg'){
$im = #imagecreatefromjpeg($_FILE['inputfile']['tmp_name']);
if($im){
$createimage = imagejpeg($im, $upload_path.$_FILE['inputfile']['name']);
if(!$createimage){
die("Error3: Can't create image!");
}
//last check
$filecontent = file_get_contents($upload_path.$_FILE['inputfile']['name']);
//clean the file from any php code
$filecontent = str_replace(array("<?php", "<?", "?>"), "", $filecontent);
$handle = fopen($upload_path.$_FILE['inputfile']['name'], "wb");
fwrite($handle, $filecontent);
fclose($handle);
}
else{
die("Error2: Invalid Image Detected");
}
}
}
One can always embed PHP code safely in a perfectly valid image file. There are too many ways to do that to worth even thinking avoiding them. Many valid image formats, many data containers such as EXIF in jpg for example, pixel level and compression manipulation, etc.
To be on the safe side one should protect the server from arbitrary file inclusion attacks and sanitize the file extensions to escape from apache configuration mistakes.
A more crazy approach is to create a slightly modified copy of the image, more exactly create a new image from the original one modified, a slight resize or color manipulation will delete the bitmap level PHP injections while copying will save you from most of the PHP injected in other data containers within the image.