1

I'm uploading images from the pc to a server using this php code

  $ImageToLoad=mysql_real_escape_string($_POST['image_attached']);

if($ImageToLoad){

$token=$token;//variable
$ImageToLoad = str_replace('data:image/png;base64,', '', $ImageToLoad);
$ImageToLoad = str_replace('data:image/jpeg;base64,', '', $ImageToLoad);
$ImageToLoad = str_replace(' ', '+', $ImageToLoad);
$fileData = base64_decode($ImageToLoad);    


$destino_path="/images/$token/image.png";

file_put_contents($destino_path, $fileData);

}

It works ok.

PROBLEM

I need to know how to resize it/crop them before to store the image in the server. Otherwise it keeps the same size (problem when huge image)

Dan
  • 497
  • 3
  • 12

2 Answers2

3

Resizing images can be is a costly operation and should be handled by a specialized library. In the past, the default pointer was ImageMagick's Imagick::resizeImage. However, this package does not work for everybody and other solutions have emerged in the meantime.

I suggest gumlet's php-image-resize. Resizing a base64 encoded image can be as simple as that:

$image = ImageResize::createFromString(base64_decode('R0lGODlhAQABAIAAAAQCBP///yH5BAEAAAEALAAAAAABAAEAAAICRAEAOw=='));
$image->scale(50);
$image->save('image.jpg');
wp78de
  • 16,078
  • 6
  • 34
  • 56
  • OK...I see the point. but I dont actually use libraries...do I need to install it on the server? – Dan Jun 09 '18 at 21:11
  • 1
    It's not that hard. Just use composer, if available, or put the lib source files on the server and include `'/path/to/ImageResize.php';` – wp78de Jun 09 '18 at 21:15
1

If we want to create a temp image from an image file for resizing, we can use

imagecreatefromjpeg($filename);

or

imagecreatefrompng($filename);

If we want to create a temp image from blob we can use

imagecreatefromstring($blob);

imagecreatefromstring()

So, give this a try:

<?php
$filename = 'folder_name/resized_image.png'; // output file name

$im = imagecreatefromstring($fileData);
$source_width = imagesx($im);
$source_height = imagesy($im);
$ratio =  $source_height / $source_width;

$new_width = 300; // assign new width to new resized image
$new_height = $ratio * 300;

$thumb = imagecreatetruecolor($new_width, $new_height);

$transparency = imagecolorallocatealpha($thumb, 255, 255, 255, 127);
imagefilledrectangle($thumb, 0, 0, $new_width, $new_height, $transparency);

imagecopyresampled($thumb, $im, 0, 0, 0, 0, $new_width, $new_height, $source_width, $source_height);
imagepng($thumb, $filename, 9);
imagedestroy($im);
?>
Michael Eugene Yuen
  • 2,332
  • 2
  • 15
  • 17
  • this is what I was looking for....but once created how do I upload it to the server? I think I wont be able to use `file_put_contents($destino_path, $fileData);` anymore1 – Dan Jun 09 '18 at 21:14
  • 1
    simply change your output name.. $filename = "$desintao_path"; – Michael Eugene Yuen Jun 10 '18 at 00:48