If you put the second parameter in imagepng
it will not display and save, it's as described in the documentation link
If not set or NULL, the raw image stream will be outputted directly.
In other words, if the second parameter is not set or it is NULL
it will display, otherwise it will save to a file.
So whenever in doubt, search the documentation and read how to use each parameter and see the examples. In case your code should look like this:
<?php
$file = "img.png";
$width = 500;
$height= 500;
list($width_origin, $height_origin) = getimagesize($file);
$ratio = $width_origin / $height_origin;
if ($width/$height > $ratio) {
$width = $height * $ratio;
}else{
$height = $width / $ratio;
}
$image_final = imagecreatetruecolor($width, $height);
$imagem_origin= imagecreatefrompng($file);
imagecopyresampled($image_final,$imagem_origin, 0, 0, 0, 0, $width, $height, $width_origin, $height_origin);
header("Content-Type: image/png");
imagepng($image_final); //Exibe a imagem
If you want to view and save at the same time, you can use several methods, such as saving to a stream or file directly:
-
Using readfile
:
if (imagepng($image_final, $file)) //salva para um arquivo
{
header("Content-Type: image/png");
readfile($file);
} else {
echo 'Erro ao salvar';
}
-
fopen
+ stream_get_contents
This is a little more complicated, but if you need to do some manipulation in the stream it might be interesting to use it.
$handle = fopen($handle, 'wb');
if (!$handle) {
die('Erro ao abrir o arquivo para escrita');
}
if (imagepng($image_final, $handle)) //salva para um arquivo
{
header("Content-Type: image/png");
echo stream_get_contents($handle);
} else {
echo 'Erro ao salvar';
}
fclose($handle);
What each parameter does:
The function is basically
bool imagepng ( resource $image [, mixed $to [, int $quality [, int $filters ]]] )
-
$image
It should be an resource of an image, returned by image-authoring functions, for example imagecreatetruecolor()
, imagecreatefrompng()
, etc.
-
$to
The path or an open stream (which will be automatically closed when the function returns) to save the file. If not set or is NULL
, the image will be displayed in the output.
-
$quality
Compression level: if 0 (no compression) up to 9.
-
$filters
Lets you reduce the size of the PNG file. This is a bitmask field which you can set any combination of constants PNG_FILTER_XXX
. If you use PNG_NO_FILTER
or PNG_ALL_FILTERS
or use them respectively will disable or enable all filters.