Uploading a base64 image as an image file - php

So I'm receiving an image in base64 encoding. I want to decode the image and upload it in a specific directory. The encoded file is an image and I'm using $file = base64_decode($base64_string); to decode it. Uploading it via file_put_contents('/uploads/images/', $file); always results in failed to open stream: No such file or directory error.
So, how do I take the decoded string, and upload it on a specific path?
Thanks.

Your path is wrong.
/uploads/images
is checking for a folder in the / directory called uploads. You should specify the full path to the folder:
/var/www/vhosts/MYSITE/uploads/images

I had the same problem and finally solved using this:
<?php
$file = base64_decode($base);
$photo = imagecreatefromstring($file);
//create a random name
$RandomStr = md5(microtime());
$name = substr($RandomStr, 0, 3);
$name .= date('Y-m-d');
$name .= '.jpg';
//assign name and upload your image
imagejpeg($photo, 'images/'.$name, 100);

Related

Store blob as a file in S3 with Laravel

I am using a file upload plugin in Vue to upload some image and pdf files through an API and it has an option to create a blob field when uploading the files.
The request sent to Laravel is as follows. I can access the blob from the browser by copying and pasting the URL on the browser.
On the Server side code, I am trying to save the file with the following code but the saved file is some corrupted 64byte file rather than the actual image. How would we store the blob as a normal file in the filesystem?
if ($request->has('files')) {
$files = $request->get('files');
$urls = [];
foreach ($files as $file) {
$filename = 'files/' . $file['name'];
// Upload File to s3
Storage::disk('s3')->put($filename, $file['blob']);
Storage::disk('s3')->setVisibility($filename, 'public');
$url = Storage::disk('s3')->url($filename);
$urls[] = $url;
}
return response()->json(['urls' => $urls]);
}
Try by replacing this:
Storage::disk('s3')->put($filename, $file['blob']);
with this:
Storage::disk('s3')->put($filename, base64_decode($file['blob']));

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

php return image from url

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

dynamicaly creating file ,file path not working on server machine

I am saving canvas to a file. Code creates a png file in the upload folder. It is working correctly on local machine but when i try to run this on the server, I am not able to find the file in the upload folder. am i giving wrong path ?
After file creation i am printing alert, so i get file creation alert but file is not just created in the upload folder .
if ( isset($_POST["image"]) && !empty($_POST["image"]) ) {
// get the image data
$data = $_POST['image'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
//Image name
$filename ="image". md5(uniqid()) . '.png';
$file ='../upload/'.$filename;
// decode the image data and save it to file
file_put_contents($file,$data);
}
make sure directory '../upload' exists or create it first

damaged file during upload with file_put_contents

I try to upload an image in a directory using file_put_contents,The file is uploaded but it is damaged and I can not open it. here is my code :
define('UploadDir','../Dir/images');
$path = "image.png";
$data="..."; //image base64 string
$file = UploadDir ."/". $path;
$success = file_put_contents($file, $data);
echo $success ? $file : 'Unable to save the file.';
$data="..."; //image base64 string
Assuming $data contains what the comment says, if you put a base64 string in an image it will obviously not be a valid image - it will be a file containing a base64 encoded string.
To be valid (or have a chance at being valid) decode the string before writing it to the file:
$data="..."; //image base64 string
$file = UploadDir ."/". $path;
$success = file_put_contents($file, base64_decode($data));
Is the directory ../Dir/images chmoded to 777? sometimes php won't allow you to access directories if they don't have enough permission.
Try to see if it has enough permissions, if not, then set it to 777 and try it.

Categories