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
Related
On image upload , I want to resize image to 400 X 400 ratio. I have used GD library code as :
$profilePicture = $_FILES['imgProfilePicture']['tmp_name'];
// Get new dimensions
list($width_orig, $height_orig, $type) = getimagesize($profilePicture);
$ratio_orig = $width_orig/$height_orig;
if ($intWidth/$intHeigth > $ratio_orig) {
$intWidth = $intHeigth*$ratio_orig;
} else {
$intHeigth = $intWidth/$ratio_orig;
}
// Resample
$thumb = imagecreate($intWidth, $intHeigth);
ob_start();
$extension = image_type_to_extension($type);
if($extension == ".jpg" OR $extension=='.jpeg'){
$source = ImageCreateFromJpeg($profilePicture);
$newImage = imagejpeg($thumb, null, 9);
}elseif ($extension == ".gif"){
$source = ImageCreateFromGIF($profilePicture);
$newImage = imagegif($thumb, null, 9);
}elseif ($extension == '.png'){
$source = imageCreateFromPNG($profilePicture);
$newImage = imagepng($thumb, null, 9);
}
imagecopyresized($thumb, $source, 0, 0, 0, 0, $intWidth, $intHeigth, $width_orig, $height_orig);
$stream = ob_get_clean();
$imgProfilePicture = file_get_contents($stream);
$sql="update `".$doctorTableName."` set`imgProfilePicture`='".$imgProfilePicture."' where id='".$id."'";
$wpdb->query($sql);
& I have shown image using this code :
<img width="70" height="70" src="data:image/jpeg;base64, '.base64_encode($doctor->imgProfilePicture).' "/>
But I am getting error as :
Warning: file_get_contents() expects parameter 1 to be a valid path, string given
I got a code for this on this link under user contributions scaleImageFileToBlob()
http://php.net/manual/en/function.imagejpeg.php
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 "";
}
}
I am trying to upload some images using import.csv file. The images need to be resized before uploading. I am using this code for uploading but it is returning a black image of the given size.
<?php
error_reporting(E_ALL);
include('config.php');
include('inc/header.php');
define('CSV_PATH', '');
$csv_file = CSV_PATH . "importImage.csv"; // Name of your CSV file
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
$i = 0;
while (!feof($csvfile)) {
$csv_data[] = fgets($csvfile, 1024);
$csv_array = explode(",", $csv_data[$i]);
$insert_csv = array();
$url = $insert_csv['url'] = $csv_array[0];
$image = $insert_csv['image'] = $csv_array[1];
$raw = file_get_contents($url . $image);
/*RESIZE USING GD*/
/*
* PHP GD
* resize an image using GD library
*/
// File and new size
//the original image has 800x600
$filename = $raw;
//the resize will be a percent of the original size
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = 200;
$newheight = 200;
// Load
$thumb = imagecreate($newwidth, $newheight);
$source = imagecreate($filename);
// Resize
$imgnew = imagecopyresampled($thumb, $source, 0, 0, 0, 0, newwidth, $newheight, $width, $height);
imagejpeg($thumb, 'Mypath' . time() . '.jpg'); // save resized image to
//Output and free memory
imagedestroy($thumb);
$i++;
}
fclose($csvfile);
echo "File data successfully imported to database!!";
mysql_close($connect);
?>
The following script will easily allow you to resize images using PHP and the GD library.
https://github.com/nomisoft/White-Hat-Classes/tree/master/Simple-Image
First, check that the $url.$image is a real image.
Second, getimagesize requires an image path, not the image
I'm pretty sure you want this: http://runnable.com/UnF-tFdudNt1AABt/how-to-resize-an-image-using-gd-library-for-php
I'm uploading an image file, copying it, resizing it, then moving the original file and resizing it!
I've written the following function, I know there's a lot of room to tidy the code up etc.
public function useImage($image, $photoid){
$source = $image['tmp_name'];
$target = "projectimages/";
//prepare the largest image
copy($source, $target);
$targetname = $photoid."large.jpg";
$file = $target.$targetname;
list($width, $height) = getimagesize($file);
$modwidth = 800;
$diff = $width / $modwidth;
$modheight = $height / $diff;
$tn = imagecreatetruecolor($modwidth, $modheight);
$image = imagecreatefromjpeg($file);
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);
imagejpeg($tn, $file, 100);
//prepare the smaller image
move_uploaded_file($source, $target);
$targetname = $photoid."small.jpg";
$file = $target.$targetname;
list($width, $height) = getimagesize($file);
$modwidth = 400;
$diff = $width / $modwidth;
$modheight = $height / $diff;
$tn = imagecreatetruecolor($modwidth, $modheight);
$image = imagecreatefromjpeg($file);
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);
imagejpeg($tn, $file, 100);
}
I'm getting plenty of errors but the crucial one that the others are built upon is the first one when I try and copy or move the uploaded file...
Warning: copy(projectimages/) [function.copy]: failed to open stream: Is a directory in /Applications/MAMP/htdocs/bs/classes/image.php on line 171
I've used var_dump on image and it appears the image is in place.
Any ideas?
The destination of the copy() call is a directory. Try to change your code like this:
$source = $image['tmp_name'];
$target = "projectimages/";
//prepare the largest image
$targetname = $photoid."large.jpg";
$file = $target.$targetname;
copy($source, $file);
// The rest of your code goes here.
My app is receiving base64-encoded image-files from the webbrowser. I need to save them on the client. So I did:
$data = base64_decode($base64img);
$fileName = uniqid() . '.jpg';
file_put_contents($uploadPath . $fileName, $data);
return $fileName;
Which works fine.
Now I need to compress & resize the image to max. 800 width & height, maintaining the aspect-ratio.
So I tried:
$data = base64_decode($base64img);
$fileName = uniqid() . '.jpg';
file_put_contents($uploadPath . $fileName, $data);
return $fileName;
which does not work (error: "imagejpeg() expects parameter 1 to be resource, string given").
And of course, this does compress, but not resize.
Would it be best to save the file in /tmp, read it and resize/move via GD?
Thanks.
2nd part
Thanks to #ontrack I know now that
$data = imagejpeg(imagecreatefromstring($data),$uploadPath . $fileName,80);
works.
But now I need to resize the image to max 800 width and height. I have this function:
function resizeAndCompressImagefunction($file, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*($r-$w/$h)));
} else {
$height = ceil($height-($height*($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $dst;
}
So I thought I could do:
$data = imagejpeg(resizeAndCompressImagefunction(imagecreatefromstring($data),800,800),$uploadPath . $fileName,80);
which does not work.
You can use imagecreatefromstring
To answer the second part:
$data = imagejpeg(resizeAndCompressImagefunction(imagecreatefromstring($data),800,800),$uploadPath . $fileName,80);
$data will only contain either true or false to indicate wether the operation of imagejpeg was a success. The bytes are in $uploadPath . $fileName. If you want the actual bytes back in $data you have to use a temporary output buffer:
$img = imagecreatefromstring($data);
$img = resizeAndCompressImagefunction($img, 800, 800);
ob_start();
imagejpeg($img, null, 80);
$data = ob_get_clean();