Use PHP to convert base64 JPEGs to transparent PNG - php

I want convert base64 jpeg or jpg (white background) to transparent png with my own code :
$img = str_replace(array('data:image/jpeg;base64', 'data:image/jpg;base64', 'data:image/bmp;base64', 'data:image/png;base64'), '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . $fn . str_replace('image/', '.', $type);
$success = file_put_contents($file, $data); //when its done it saves the image data
I'm following this post but image cannot save to dir, modified code:
$img = str_replace(array('data:image/jpeg;base64', 'data:image/jpg;base64', 'data:image/bmp;base64', 'data:image/png;base64'), '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . $fn . str_replace('image/', '.', $type);
$success = file_put_contents($file, $data); //when its done it saves the image data
imagesavealpha($img, true);
$color = imagecolorallocatealpha($img, 0, 0, 0, 127);
imagefill($img, 0, 0, $color);
imagepng($img, 'test.png');
Also, following post but the image show error when opened, modified code:
$img = str_replace(array('data:image/jpeg;base64', 'data:image/jpg;base64', 'data:image/bmp;base64', 'data:image/png;base64'), '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . $fn . str_replace('image/', '.', $type);
$success = file_put_contents($file, $data); //when its done it saves the image data
$image = imagealphablending($file, true);
$transparentcolour = imagecolorallocate($image, 255,255,255);
imagecolortransparent($image, $transparentcolour)

Related

Save image as file in a folder on the server

I have this code running...
$im = imagecreatefromstring($arr['IMAGE']->load());
$result = $arr['IMAGE']->load();
echo $result;
exit();
and this code is showing the image on the browser. My question is...how to save as a file and save on the server?
I am using this code and it is saving as a file but there isn't a image.
define('UPLOAD_DIR', 'testuploads/');
// $img = str_replace('data:image/png;base64,', '', $result);
// $img = str_replace(' ', '+', $img);
$data = imagejpeg($result);
$file = UPLOAD_DIR . uniqid() . '.jpeg';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
use imagejpeg($result, $file) or imagepng if it is a png, instead of file_put_contents.
(where $result is your img, and $file your path+file name)
EDIT: see doc: http://php.net/manual/en/function.imagejpeg.php
example:
<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
// Save the image as 'simpletext.jpg'
imagejpeg($im, 'simpletext.jpg');
?>

php- compressing a base64 decoded image fails

I get images as base64 encoded string front end and I have to decode them and save them as images in server. Image can be of any format- png,gif or jpeg.
This part works fine. But sometimes the images uploaded by the users can be of very large size, so I'm trying to compress them from backend and this part failed miserably.
I have two functions. One for converting base64 string to image and other one for compressing it.
This is the function that converts the string to an image.
function uploadTimelineImage($base64Img)
{
$data= array();
$upAt=date('YmdHis');
if (strpos($base64Img, 'data:image/png;base64') !== false)
{
$img = str_replace('data:image/png;base64,', '', $base64Img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$extension= 'png';
}
if (strpos($base64Img, 'data:image/gif;base64') !== false)
{
$img = str_replace('data:image/gif;base64,', '', $base64Img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$extension= 'gif';
}
if (strpos($base64Img, 'data:image/jpeg;base64') !== false)
{
$img = str_replace('data:image/jpeg;base64,', '', $base64Img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$extension= 'jpeg';
}
$fileName = 'img'.$upAt.$extension;
$filePath = 'foldername/'.'img'.$upAt.$extension;
//upload image to folder
$success = file_put_contents($filePath, $data);
$result = $success ? 1 : 0;
//call to compression function
$compressThisImg= $filePath;
$d = compress($compressThisImg, $fileName, 80);
if($result==1)
{
return $fileName;
}
else
{
return null;
}
}
And this is the function that does compressing:
//Function to compress an image
function compress($source, $destination, $quality)
{
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source);
elseif ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source);
elseif ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source);
imagejpeg($image, $destination, $quality);
return $destination;
}
But the above function does not do any compression, it throws error:
failed to open stream: No such file or directory
and my function uploads the original image.
Why you dont use this function for create any type of image form base64 edncoded image string?
function uploadTimelineImage($base64Img,$h,$w)
{
$im = imagecreatefromstring($base64Img);
if ($im !== false) {
$width = imagesx($im);
$height = imagesy($im);
$r = $width / $height; // ratio of image
// calculating new size for maintain ratio of image
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagedestroy($im);
$fileName = 'img'.date('Ymd').'.jpeg';
$filepath = 'folder/'.$fileName ;
imagejpeg($dst,$filepath);
imagedestroy($dst);
return $fileName;
}
else
{
return "";
}
}

How can I resize an image from URL using PHP?

I'm receiving Images from URLs and I would like to save these images into a new directory, in three different sizes. I'm already getting the URLs here, now I just need a way to resize each image, with a specific height and width.
I dont want to resize uploaded images, only Images from a specific URL.
My code:
$content = file_get_contents('http://www.joomlaworks.net/images/demos/galleries/abstract/7.jpg');
$name = "http://www.joomlaworks.net/images/demos/galleries/abstract/7.jpg";
$parts = explode('.', $name);
$new_url = rand(0, pow(10, 5)) . '_' . time() . '.' . $parts[count($parts) - 1];
file_put_contents(DIRECTORY.'/' . $new_url , $content);
How can I do that? Thanks.
here is the solution based on imagecopyresampled (GD library) http://php.net/manual/en/function.imagecopyresampled.php
$content = file_get_contents('http://www.joomlaworks.net/images/demos/galleries/abstract/7.jpg');
$name = "http://www.joomlaworks.net/images/demos/galleries/abstract/7.jpg";
$parts = explode('.', $name);
$new_url = rand(0, pow(10, 5)) . '_' . time() . '.' . $parts[count($parts) - 1];
file_put_contents(DIRECTORY.'/' . $new_url , $content);
resizeImage($new_url, DIRECTORY.'/1_' . $new_url, 100, 100);
resizeImage($new_url, DIRECTORY.'/2_' . $new_url, 200, 200);
resizeImage($new_url, DIRECTORY.'/3_' . $new_url, 300, 300);
function resizeImage($source, $dest, $new_width, $new_height)
{
list($width, $height) = getimagesize($source);
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($source);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image_p, $dest, 100);
}

convert image 64X64 px after decoding base64 image in php

hi i am retriving a base64 encoded version of image and i have to stored it by cropping it to small size. now i am not able to crop the image please help me
my Code is as follow..
Please help me in cropping base 64 image
$data = str_replace('data:image/png;base64,', '', $note['file']);
$data = str_replace(' ', '+', $data);
$decodedFile = base64_decode($data);
$file = fopen($destination , 'wb');
if(!fwrite($file, $decodedFile)){
//return("ERROR: can't save file to $destination");
return '-1';
}
fclose($file);
You can use the gd library for create the image file from binary code:
function binaryToFile($binary_imagen, $width, $height, $new_name, $url_destiny) {
try{
//actual size
$info = getimagesizefromstring($binary_imagen);
$old_width = $info[0];
$old_height = $info[1];
//new resource
$resource = imagecreatefromstring($binary_imagen);
$resource_copy = imagecreatetruecolor($width, $height);
imagealphablending( $resource_copy , false );
imagesavealpha( $resource_copy , true );
imagecopyresampled($resource_copy, $resource, 0, 0, 0, 0,
$width, $height,
$old_width, $old_height);
$url = $url_destiny."/".$new_name".png";
$final = imagepng($resource_copy, $url, 9);
imagedestroy($resource);
imagedestroy($resource_copy);
return 1;
}catch (Exception $e) {
return 0;
}
}
Not sure what your need but if it is some what like this you want to achieve then may be this will help you
PHP crop image from base64_decode

How to resize image before creating from Canvas?

I have PHP script to create PNG image from base 64 string from canvas, I need to figure out how to work it, this new PHP script doesn't create resized PNG files.
Reference:
CanvasPic = Base64 string
Working PHP script but no resize.
<?php
if (!file_exists('userCanvas/'))
{
mkdir('userCanvas', 0755, true);
}
else
{
$name = $_POST['name'];
$img = $_POST['CanvasPic'];
define('UPLOAD_DIR', 'userCanvas/');
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Could not save the file!';
}
?>
New script but won't create resized PNG images:
<?php
if (!file_exists('userCanvas/'))
{
mkdir('userCanvas', 0755, true);
}
else
{
$name = $_POST['name'];
$img = $_POST['CanvasPic'];
define('UPLOAD_DIR', 'userCanvas/');
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$width = 350;
$height = 250;
header('Content-Type: image/png');
list($width_orig, $height_orig) = getimagesize($file);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig)
{
$width = $height*$ratio_orig;
}
else
{
$height = $width/$ratio_orig;
}
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefrompng($file);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
$success = file_put_contents($image_p, $data);
print $success ? $image_p : 'Could not save the file!';
}
?>
Edit: I found errors (skipped line number and URL), I had no idea how to fix these errors.
I found errors, (skipped URL locations and code line):
PHP Warning: getimagesize(userCanvas/53bc7c926a606.png): failed to open stream: No such file or directory
PHP Warning: Division by zero in
PHP Warning: imagecreatetruecolor(): Invalid image dimensions
PHP Warning: imagecreatefrompng(userCanvas/53bc7c926a606.png): failed to open stream: No such file or directory
PHP Warning: imagecopyresampled() expects parameter 1 to be resource, boolean given
PHP Warning: file_put_contents(): Filename cannot be empty

Categories