how to retrieve blob file to image in php? - php

I am using plupload to upload file in my php based website, with large file uploading the file becomes a file named 'blob' without any suffix. I know this is a binary file that contains the raw data, question is how to retrieve the data and save it back as an image file, say .png/.jpg or etc? I tried:
$imageString = file_get_contents($blogPath);
$image = imagecreatefromstring($imageString);
But it gives me some 'Data is not in recognized format...' error, any thoughts? Thanks in advance.

Your call to imagecreatefromstring() should work just fine if your file_get_contents() is working. Use var_dump($imageString) to verify. Did you mean to name your variable $blobPath instead of $blogPath?
You don't need to load this image though. Just rename the file.
rename($blobPath, 'new/path/here.jpg');
http://php.net/manual/en/function.rename.php

I am storing the uploaded image files for late use, like attaching them to posts or products(my site is e-commerce CMS). I figured that my image file didn't get fully uploaded to the server, the image before upload is 6mb, but the blob file is just 192kb, so my best guess is that what get uploaded is just a chunk instead of the whole package, and yet that brought up another question: how should I take all the pieces and assemble them as one complete image file? As mentioned earlier, I am using plupload for js plugin and php as backend, the backend php code to handle uploading goes like this:
move_uploaded_file($_FILES["file"]["tmp_name"], $uploadFolder . $_FILES["file"]["name"]);

Instead of doing that you should do this to display image to the browser
<img src="data:image/jpeg;base64,'.base64_encode( $row['blob_image'] ).'"/>
I'm not sure what imagecreatefromsting does or how it encodes the image.
I looked at the documentation for that function; you're missing:
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data); <--- this operation

Related

Saving a remote image programmatically with PHP

I am trying to migrate some content from one resources into another and need to save some images (several hundred) located at a remote resource.
Suppose I have only the URL to an image:
https://www.example.com/some_image.jpg
And I would like to save it into the filesystem using PHP.
If I were uploading the image, I essentially would do the following:
<input type="file" name="my_image" />
move_uploaded_file($_FILES['my_image']['tmp_name'], '/my_img_directory');
But since I only have the URL, I would imagine something like:
$img = 'https://www.example.com/some_image.jpg';
$file = readfile($img);
move_uploaded_file($file, '/my_img_directory');
Which of course wouldnt work since move_uploaded_file() doesn't take an output buffer as a first argument.
Essentially, I would need to get $img into the $_FILES[] array under this approach. Or may some other approach?
You can use PHP's copy function to copy remote files to a location on your server:
copy("https://example.com/some_image.jpg", "/path/to/file.jpg");
http://php.net/manual/en/function.copy.php
$image = file_get_contents('http://www.url.com/image.jpg');
file_put_contents('/images/image.jpg', $image); //Where to save the image on your server

$_FILES to a resource - Laravel 5 and Dropbox

Well, I've uploaded an app to Heroku, and I've discovered that I can't upload files to it. Then I started to use Dropbox as storage option, and I've done a few tests, of send and retrieve link, and all worked fine.
Now, the problem is to use the uploadFile() method on DropboxAdapter. He accepts an resource as the file, and I did'nt work well. I've done a few tests, and still no way. Here is what I am doing, if anyone could me point a solution, or a direction to this problem, please. :)
Here is my actual code for the update user (Update the user image, and get the link to the file).
$input = $_FILES['picture'];
$inputName = $input['name'];
$image = imagecreatefromstring(file_get_contents($_FILES['picture']['tmp_name']));
Storage::disk('dropbox')->putStream('/avatars/' . $inputName, $image);
// $data = Storage::disk('dropbox')->getLink('/avatars/' . $inputName);
return dd($image);
In some tests, using fopen() into a file on the disk, and doing the same process, I've noticed this:
This is when I've used fopen() on a file stored on the public folder
http://i.imgur.com/07ZiZD5.png
And this, when i've die(var_dump()) the $image that I've tried to create. (Which is a suggestion from this two links: PHP temporary file upload not valid Image resource, Dropbox uploading within script.
http://i.imgur.com/pSv6l1k.png
Any Idea?
Try a simple fopen on the uploaded file:
$image = fopen($_FILES['picture']['tmp_name'], 'r');
https://www.php.net/manual/en/function.fopen.php
You don't need an image stream but just a filestream, which fopen provides.

Display user input image without saving it to a folder

How can I display an image and pass it as an input parameter in an executable in php without saving the image in a folder. The user gives the image path as input and I am using ajax to display the image when it is selected when I save it to a folder it works but how can I display it without saving it in a folder? My code now is
move_uploaded_file($_FILES["file"]["tmp_name"],"upload/".$_FILES["file"]["name"]);
//echo "Stored in "."upload/".$_FILES["file"]["name"];
echo "<img src='upload/".$_FILES["file"]["name"]."' class='preview'>";
I tried
<img src=$_FILES["file"]["tmp_name"]. class='preview'>
but it didnt work. As I will have thousands of input from thousands of user I dont want to save it. Is there any optimised and efficient method to do this?
I think, its not possible to show image without saving it. You could try to save the image in temp folder on the server side and clean this folder periodically to avoid much space consumption.
The src attribute of the <img> tag should be an URL accessible by the client.
You try to give a local path (ex: path/to/your/file.jpg) of a temporary file as URL, it will not working.
info: The uploaded image is save on the local disk on a temp directory, and could be deleted by PHP later.
If you want to show the image without moving it at a place reacheable by a URL, you can try to load its content as base64 content
$imagedata = file_get_contents($_FILES["file"]["tmp_name"]);
$base64 = base64_encode($imagedata);
and use in your HTML
<img src="data:image/png;base64, <?php echo $base64; ?>" />
I don't think you can show the image without saving it.
You need to save the file either to the filesystem or to memory if you want to later output
Your problem here is that $_FILES only exists in the script that the image was sent to. so when you initiate another http request for img source, php no longer has any clue what file your trying to read.
You need a way to tell which image to be read on http request.
One thing you can do is that you can save the file in a place accessible by the client and then just have php delete it after you output it. So once the image is outputted it will be deleted and no longer be existing in the file system.
Another approach would be to get the image from the memory by directly writing the contents to httpresponse.
You can do this way
$image = file_get_contents($_FILES["file"]["tmp_name"]);
$enocoded_data = base64_encode($image);
and when you show your image tag :
<img src="data:image/png;base64, <?php echo $enocoded_data ; ?>" />
Hope any of these helps you

Resize image directly from Rackspace Cloud Files 'object' without downloading?

I have moved my images to Rackspace Cloud Files and am using their PHP API. I am trying to do the following:
Get an image from my "originals" container
Resize it, sharpen it, etc.
Save the resized image to the "thumbs" container
My problem is with #2. I was hoping to resize without having to copy the original to my server first (since the images are large and I'd like to resize dynamically), but can't figure out how. This is what I have so far (not much):
$container = $conn->get_container("originals");
$obj = $container->get_object("example.jpg");
$img = $obj->read();
Part of the problem is I don't fully understand what is being returned by the read() function. I know $img contains the object's "data" (which I was able to print out as gibberish), but it is neither a file nor a url nor an image resource, so I don't know how to deal with it. Is it possible to convert $img into an image resource somehow? I tried imagecreatefromjpeg($img) but that didn't work.
Thanks!
First, you cannot resize an image without loading it into memory. Unless the remote server offers some "resize my image for me, here are the parameters" API, you have to load the image in your script to manipulate it. So you'll have to copy the file from the CloudFiles container to your server, manipulate it, then send it back into storage.
The data you receive from $obj->read() is the image data. That is the file. It doesn't have a file name and it's not saved on the hard disk, but it is the entire file. To load this into gd to manipulate it, you can use imagecreatefromstring. That's analogous to using, for example, imagecreatefrompng, only that imagecreatefrompng wants to read a file from the file system by itself, while imagecreatefromstring just accepts the data that you have already loaded into memory.
You can try to dump the content of the $img variable into a writable file as per the below:
<?php
$filename = 'modifiedImage.jpg';
/*
* 'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate
* the file to zero length. If the file does not exist, attempt to create it.
*/
$handle = fopen($filename, 'w+');
// Write $img to the opened\created file.
if (fwrite($handle, $img) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote to file ($filename)";
fclose($handle);
?>
More details:
http://www.php.net/manual/en/function.fopen.php
http://www.php.net/manual/en/function.fwrite.php
Edit:
You might also want to double check the type of data returned by the read() function, because if the data is not a jpg image, if it's for example a png, the extension of the file needs to be changed accordingly.

How to save a phpthumb output into a file?

I am trying to save PhpThumb output. As what I could find on-line was not sufficient or too complex, I would like to ask if any one knows how to it?
$thumb_src="\"phpThumb/phpThumb.php?src=../apartmentsPhotos/".$num['ref']."/1.JPG&h=119&q=100\"";
echo" '<'img src=".$thumb_src />";
So what I want to do is to save the img src into an Image.
(So far I was creating the thumbnails on the fly but it seems that google and my web server donĀ“t like it too much. Saving the thumbnails will ensure that in no time I will have all my thumbnails in real files and then I will use this function just for new content.)
From phpThumb's FAQ
The best way is to call phpThumb as an object and call RenderToFile() to save the
thumbnail to whatever filename you want. See /demo/phpThumb.demo.object.php for an example. The other way is to use the 'file' parameter (see /docs/phpthumb.readme.txt) but this parameter is deprecated and does not work in phpThumb v1.7.5 and newer.
Once you have generated the URL with this line you posted:
$thumb_src="\"phpThumb/phpThumb.php?src=../apartmentsPhotos/".$num['ref']."/1.JPG&h=119&q=100\"";
Pass it as a $_GET variable to another page, call it serveThumb.php:
if (!isset($_GET['img']))
exit;
header('Content-type: application/pdf');
echo file_get_contents($_GET['img']);
You might have to add your own validation to serveThumb.php. Now you can save the result of serveThumb.php as a JPG.
Alternatively, save the contents of the image as a JPG file.
if (!isset($_GET['img']))
exit;
$img = file_get_contents($_GET['img']);
file_put_contents("myImage.jpg", $img);

Categories