How do I get Image Data from an Image Resource? - php

I'm working with the Microsoft Azure cloud and need to upload images there. Its class upload methods putBlob() and putBlobData() require either the data itself (not the resource) or the directory string as arguments, none of which is available before the image is actually written to the Blob.
$fp = fopen($tmp_name, 'r');
$data = fread($fp, filesize($tmp_name));
fclose($fp);
//Setup watermark destination
$new_watermarked_image_name = "watermark.jpg";
// Create image resources
$image = imagecreatefromstring($data);
$watermark = imagecreatefrompng('images/watermark_large.png');
$copyright = imagecreatefrompng('images/copyright.png');
// Merge image resource s
$image = overlay_watermark_full_size($image, $watermark);
$image = overlay_watermark_lower_right($image, $copyright);
imagejpeg($image, $new_watermarked_image_name, 100);
//put original image
$AzureStorageBlob->putBlob("uploads", "name", $tmp_name);
//put watermarked image
$AzureStorageBlob->putBlobData("uploads", "name", ?); // ? needs to be data

You need to capture the buffer with ob_start, something like:
ob_start();
imagejpeg($tmp_img);
$i = ob_get_clean();
$i is your image blob

By using latest SDK for PHP you can do this by just passing the image stream:
$image_stream = fopen($tmp_name, 'r');
// Check README.md of how to create $blobRestProxy
$blobRestProxy->createBlockBlob('container_name', 'my_image', $image_stream);
Let me know if you have any further questions

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

php take image, rotate and save rotated image on server

Want to take image from own server rotate certain angle and save the image.
Image file $filename = 'kitten_rotated.jpg'; With echo '<img src='.$filename.'>'; i see the image.
Then
$original = imagecreatefromjpeg($filename);
$angle = 90.0;
$rotated = imagerotate($original, $angle, 0);
Based on this https://stackoverflow.com/a/3693075/2118559 answer trying create image file
$output = 'google.com.jpg';
If i save the same image with new file name, all works
file_put_contents( $output, file_get_contents($filename) );
But if i try to save rotated image, then file_put_contents(): supplied resource is not a valid stream resource.
file_put_contents( $output, $rotated );
Here https://stackoverflow.com/a/12185462/2118559 read $export is going to be a GD image handle. It is NOT something you can simply dump out to a file and expect to get a JPG or PNG image.. but can not understand how to use the code in that answer.
How to create image file from $rotated?
Tried to experiment, based on this http://php.net/manual/en/function.imagecreatefromstring.php
$fh = fopen( 'some_name.png' , 'w') or die("can't open file");
fwrite($fh, $data );
fclose($fh);
Does it means that need something like
$data = base64_encode($rotated);
And then write in new file?
I have not tested this, but I think you need to encode the image as base 64 first.
If you check the string from any Image URL, you'd see data:image/png;base64, preceding the hash. Prepending this to your image string and saving.
Here is a function that may help, based on what you already have:
// Function settings:
// 1) Original file
// 2) Angle to rotate
// 3) Output destination (false will output to browser)
function RotateJpg($filename = '',$angle = 0,$savename = false)
{
// Your original file
$original = imagecreatefromjpeg($filename);
// Rotate
$rotated = imagerotate($original, $angle, 0);
// If you have no destination, save to browser
if($savename == false) {
header('Content-Type: image/jpeg');
imagejpeg($rotated);
}
else
// Save to a directory with a new filename
imagejpeg($rotated,$savename);
// Standard destroy command
imagedestroy($rotated);
}
// Base image
$filename = 'http://upload.wikimedia.org/wikipedia/commons/b/b4/JPEG_example_JPG_RIP_100.jpg';
// Destination, including document root (you may have a defined root to use)
$saveto = $_SERVER['DOCUMENT_ROOT']."/images/test.jpg";
// Apply function
RotateJpg($filename,90,$saveto);
If you want to save image just use one of GD library functions: imagepng() or imagepng().
imagerotate() returns image resource so this is not something like string.
In your case just save rotate image:
imagejpg($rotated, $output);
And now You can use $output variable as your new filename to include in view like before:
echo '<img src='.$output.'>';
Don't forget to include appropriate permissions in directory where You're saveing image.

unlink base64 encoded image not working

hi guys ive created a base64 encoded image captured with web cam now i convert the .png to .jpg all works fine but now i get two images on server both .png and .jpg how do i go about deleting the .png or is their a way to convert to jpg without saving .png image to disk thanx here my code
$rawData = $_POST['imgBase64'];
$filteredData = explode(',', $rawData);
$unencoded = base64_decode($filteredData[1]);
$randomName = rand(1000, 99999999999);
//Create the image
$fp = fopen('user/'.$randomName.'.png', 'w');
fwrite($fp, $unencoded);
//convert image from png to jpg
$image = imagecreatefrompng('user/'.$randomName.'.png');
imagejpeg($image, 'user/'.$randomName.'.jpg', 80);
unlink($fp);
ive tried it with
unlink($image);
unlink($_SERVER['DOCUMENT_ROOT'] . "/user/.$randomName.'.png'");
imagedestroy($fp);
imagedestroy($image);
Use the function unlink() but passing the file name to it instead of the file handler.
So from your example it would be:
EDIT: You might need to close the file first:
fclose( $fp );
unlink( 'user/'.$randomName.'.png' );
as far as i understand all you need is:
$data = base64_decode( $_POST['imgBase64']);
// image resource from your string
$image = imagecreatefromstring($data);
imagejpeg($image, 'user/'.$randomName.'.jpg', 80);

PHP: how can I convert jpeg to png and then zip (without making a copy)

So what I'm trying to do is:
- given an image url -> convert image to png
- zip resulting png
I have the following code which successfully does the conversion and zipping (I'm going to expand it later to test the extension to auto convert formats):
$file = "../assets/test.jpg";
$img = imagecreatefromjpeg($file);
imagePng($img, "files/temp.png" );
$zip->addFile( "files/temp.png", "test.png" );
What I want to know is, is it possible to do this without creating a copy of image before it's zipped
See ZipArchive::addFromString().
$file = "../assets/test.jpg";
// capture output into the internal buffer
ob_start();
$img = imagecreatefromjpeg($file);
imagepng($img);
// get contents from the buffer
$contents = ob_get_clean();
$zip = new ZipArchive();
$zip->open('archive.zip', ZipArchive::CREATE);
// and put them in the zip file...
$zip->addFromString('name_in_the_zip.png', $contents);

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

Categories