PHP output DataURI base64_encode - php

I want to take a local image, resize it and output the dataURI. Why is my base64_encode code not working?
<?php
// Create an image instance
$imagearray = array('pop3', 'aboutme', 'passions', 'lindahlstudios', 'blog');
foreach ($imagearray as $key) {
echo $key;
//load image
$im = imagecreatefrompng($key.'button4.png');
//set width of resize
$width = 70;
$ratio = $width / imagesx($im);
$height = imagesy($im) * $ratio;
echo ' resizeTo-'.$width.'x'.$height.'<br>';
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $im, 0, 0, 0, 0, $width, $height, imagesx($im), imagesy($im));
//save image to file
//imagepng($new_image, $key.'button4_'.$width.'.png');
//print DataURI
echo base64_encode($new_image);
imagedestroy($new_image);
}
?>

imagecreatetruecolor returns an image resource, what you need to create the data uri is an image file, also the data uri format is data:[<MIME-type>][;charset=<encoding>][;base64],<data>
echo 'data:image/png;base64,'.base64_encode(file_get_contents($new_image_file));
If you don't want to save a file to read, you can use imagepng and output buffering
ob_start();
imagepng($new_image);
echo 'data:image/png;base64,'.base64_encode(ob_get_clean());

Related

Failed to show the resized image in a PDF using PHP

I am trying to load an image from an external URL, then resize it and show it in a PDF. I am trying to achieve it using a single image for now, but the whole functionality will be inside a foreach loop for handling a lot of very large images.
Firstly, I resized the image, then get the contents of the image, applied base65 encoding, built up a source string from that and added the string to my img src tag. Here's my code -
$filename = 'https://jooinn.com/images/nature-319.jpg'; // URL of the image
$percent = 0.25; // percentage of resize
// Content type
header('Content-type: image/jpeg');
// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Output
$imageData = base64_encode(file_get_contents($image_p));
// Format the image SRC: data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image_p).';base64,'.$imageData;
// Echo out a sample image
echo '<img src="' . $src . '">';
imagedestroy($image_p);
I think the problem is with this line $imageData = base64_encode(file_get_contents($image_p));, I'm doing it wrong. It works nicely with URL's but how can I make it work for a resized image here? For example, the following works perfectly as long as I don't use the resized image -
$filename = 'https://jooinn.com/images/nature-319.jpg'; // URL of the image
// Output
$imageData = base64_encode(file_get_contents($filename));
// Format the image SRC: data:{mime};base64,{data};
$src = 'data: '.mime_content_type($filename).';base64,'.$imageData;
// Echo out a sample image
echo '<img src="' . $src . '">';
Indeed, as you said, the following line in the code is wrong:
$imageData = base64_encode(file_get_contents($image_p));
The $image_p variable is not a filename but a resource created by imagecreatetruecolor.
You first have to convert it to a jpeg file using imagejpeg().
You can avoid saving an intermediate file before encoding to base64 using the ob_*xxx* functions
ob_start();
imagejpeg($image_p);
$imageContent = ob_get_contents();
$imageData = base64_encode($imageContent);
ob_end_clean();
You also have a problem with this line, again as $image_p is not a filename:
$src = 'data: '.mime_content_type($image_p).';base64,'.$imageData;
As you are creating a jpeg file you should just replace it with:
$src = 'data: image/jpeg;base64,'.$imageData;
For convenience here is the full working script:
$filename = 'https://jooinn.com/images/nature-319.jpg'; // URL of the image
$percent = 0.25; // percentage of resize
// Content type
header('Content-type: image/jpeg');
// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Output
ob_start();
imagejpeg($image_p);
$imageContent = ob_get_contents();
$imageData = base64_encode($imageContent);
ob_end_clean();
// Format the image SRC: data:{mime};base64,{data};
$src = 'data: image/jpeg;base64,'.$imageData;
// Echo out a sample image
echo '<img src="' . $src . '">';
imagedestroy($image_p);

Resize image from base64_encode

My image file size is 800x600 and I want to resize this 800x600 to 400x300 then save both images(800x600 and 400x300) in the database base64_encode format. I can save in database first image (800x600) but how to convert a second image (400x300) in base64_encode format and save in database? I don't want to use two input fields. I think one input field enough for that.
$image = ($_FILES["my_image"]["name"]);
$theme_image = ($_FILES["my_image"]["tmp_name"]);
$bin_string = file_get_contents("$theme_image");
$theme_image_enc = base64_encode($bin_string);
You have to make a little script for create the new image from the first one and make the base64_encode on it
$WIDTH = 400; // The size of your new image
$HEIGHT = 300; // The size of your new image
$QUALITY = 100; //The quality of your new image
$DESTINATION_FOLDER = DependOfYourRepository; // The folder of your new image
// The directory where is your image
$filePath = DependOfYourRepository;
// This little part under depend if you wanna keep the ratio of the image or not
list($width_orig, $height_orig) = getimagesize($filePath);
$ratio_orig = $width_orig/$height_orig;
if ($WIDTH/$HEIGHT > $ratio_orig) {
$WIDTH = $HEIGHT*$ratio_orig;
} else {
$HEIGHT = $WIDTH/$ratio_orig;
}
// The function using are different for png, so it's better to check
if ($file_ext == "png") {
$image = imagecreatefrompng($filePath);
} else {
$image = imagecreatefromjpeg($filePath);
}
// I create the new image with the new dimension and maybe the new quality
$bg = imagecreatetruecolor($WIDTH, $HEIGHT);
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopyresampled($bg, $image, 0, 0, 0, 0, $WIDTH, $HEIGHT, $width_orig, $height_orig);
imagedestroy($image);
imagejpeg($bg, $DESTINATION_FOLDER.$filename, $QUALITY);
$bin_string_little = file_get_contents($DESTINATION_FOLDER.$filename);
// I remove the image created because you just wanna save the base64 version
unlike($DESTINATION_FOLDER.$filename);
imagedestroy($bg);
$theme_image_enc_little = base64_encode($bin_string_little);
// And now do what you want with the result
EDIT 1
It's possible to do it without using a directory for the second image but it's quite tricky.
$theme_image_little = imagecreatefromstring(base64_decode($theme_image_enc));
$image_little = imagecreatetruecolor($WIDTH, $HEIGHT);
// $org_w and org_h depends of your image, in your case, i guess 800 and 600
imagecopyresampled($image_little, $theme_image_little, 0, 0, 0, 0, $WIDTH, $HEIGHT, $org_w, $org_h);
// Thanks to Michael Robinson
// start buffering
ob_start();
imagepng($image_little);
$contents = ob_get_contents();
ob_end_clean();
$theme_image_enc_little = base64_encode($contents):

PHP image resize isn't working

I found the following script from PHP site to half the size of the image. I use the database to fetch the link of the image. Other things are working correctly which means there isn't any kind of error anywhere except this one.
echo "<img src='".// File and new size
$filename = '$row["image"]';
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output
imagejpeg($thumb);
"'>"
Error:
The whole page is destroyed and there is a broken link of an image.
Hope you guys will help me!
It works after you drop those lines:
echo "<img src='".// File and new size
"'>"
header does it for you, informs that there is jpg coming, no need to echo image tag.
The other solution is to remove this line:
header('Content-Type: image/jpeg');
And create new file, then use it as a source of an image:
// Output
$new_filename = 'new_image.jpg';
imagejpeg($thumb,$new_filename);//saves new image to a file, instead of outputting it to the screen
echo "<img src='$new_filename'>";
Try this it works
<?php
$filename = '$row["image"]';
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output
echo "<img src='".imagejpeg($thumb)."'>";
?>

Using imagejpeg() save to folder but doesn't preview image on the browser

Index.php
<?php
error_reporting(E_ALL);
// File and new size
//the original image has 800x600
$filename = 'images/lazy1.jpg';
//the resize will be a percent of the original size
$percent = 0.5;
// Content type
header('Content-Type: image/jpg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output and free memory
//the resized image will be 400x300
imagejpeg($thumb, "raj.jpg", 100);
imagedestroy($thumb);
echo "Image Resize Successfully";
?>
I am using imagejpeg() to save file. i want save file in folder but not show on browser. in browser only show this message "Image Resize successfully".
<?php
error_reporting(E_ALL);
// File and new size
//the original image has 800x600
$filename = 'images/lazy1.jpg';
//the resize will be a percent of the original size
$percent = 0.5;
//Removed lines here
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output and free memory
//the resized image will be 400x300
imagejpeg($thumb, "raj.jpg", 100);
imagedestroy($thumb);
echo "Image Resize Successfully";
?>

Save an image Resized with PHP

I am working on improving my Facebook app. I need to be able to resize an image, then save it to a directory on the server. This is the code I have to resize:
<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;
// Content type
header('Content-type: image/jpeg');
// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Output
imagejpeg($image_p, null, 100);
?>
My question is, how would I save this resized image? Would I need to? Is there a way to manipulate the resized image without saving it?
According to the manual on imagejpeg(), the optional second parameter can specify a file name, which it will be written into.
Filename
The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.
To skip this argument in order to provide the quality parameter, use NULL.
It's usually a good idea to write the results to disk for some basic caching, so that not every incoming request leads to a (resource intensive) GD call.
function resize($img){
/*
only if you script on another folder get the file name
$r =explode("/",$img);
$name=end($r);
*/
//new folder
$vdir_upload = "where u want to move";
list($width_orig, $height_orig) = getimagesize($img);
//ne size
$dst_width = 110;
$dst_height = ($dst_width/$width_orig)*$height_orig;
$im = imagecreatetruecolor($dst_width,$dst_height);
$image = imagecreatefromjpeg($img);
imagecopyresampled($im, $image, 0, 0, 0, 0, $dst_width, $dst_height, $width_orig, $height_orig);
//modive the name as u need
imagejpeg($im,$vdir_upload . "small_" . $name);
//save memory
imagedestroy($im);
}
it should be work
http://www.php.net/manual/en/function.imagecopyresampled.php#90038

Categories