Resizing image when inserting with php
I want that when inserting the image on the site by type = "file" it resizes to 400x300, I have tried everything but I can not.
Image verification code to send pro BD and insert on website:
require_once("conn.php");
$imgm=$_FILES['imageM'];
$imgf=$_FILES['imageF'];
$destinoM = 'img/mini/';
$tipoM = $imgm["type"];
$sizeM = $imgm["size"];
$tempM = $imgm["tmp_name"];
$extM = end(explode(".",$imgm["name"]));
$nomeM = "mini_" . "_" . rand(0,99999) . date("zdmYHisu") . "." . $extM;
echo $destinoM . "<br />" . $tipoM . "<br />" . $sizeM . "<br />" . $tempM . "<br />" . $extM . "<br />" . $nomeM;
if (preg_match("/^image\/(gif|jpeg|jpg|png)$/",$tipoM)){
$caminhoM = $destinoM . $nomeM;
move_uploaded_file($tempM,$caminhoM);
}
$query = "INSERT INTO `TABELAPT` (`nome`, `tipo`, `desc`, `menu`, `imageM`, `imageF`) VALUES ('".$nome."', '".$tipo."', '".$desc."', '".$menu."', '".$nomeM."', '".$nomeF."')";
// Executa a query
$inserir = mysql_query($query);
if ($inserir) {
echo "Post inserido com sucesso!";
} else {
echo "Não foi possível inserir o Post, tente novamente.";
// Exibe dados sobre o erro:
echo "Dados sobre o erro:" . mysql_error();
}
2
Author: Vitor Subhi, 2016-11-08
2 answers
There is an extension for working with images, it is called php-GD, its installation will be required.
private function resizeImage(&$file) {
$source = imagecreatefromstring($file);
$width = imagesx($source);
$height = imagesy($source);
$newwidth = 400;
$newheight = 300;
$thumb = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
ob_start();
imagejpeg($thumb);
$imagedata = ob_get_contents();
ob_end_clean();
imagedestroy($source);
imagedestroy($thumb);
return $imagedata;
}
Send as function parameter the contents of the sent file
$file = file_get_contents($_FILES['imageM']['tmp_name']);
Then just choose where the disk will save the return
You need to use the functions ImageMagick or GD of PHP to work with images.
With GD, you can do this way
function resize_image($file, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*abs($r-$w/$h)));
} else {
$height = ceil($height-($height*abs($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;
}
And call this function like this...
$img = resize_image(‘$destinoM/$nomeM.$tipoM’, 400, 300);
2
Author: Shaolin Fantastic, 2016-11-08 18:08:56