change png image to jpg with php

Asked

Viewed 2,074 times

3

Guys I put together a PHP script that uploads a photo. The problem is that I need to convert it to jpg and to the size of 280px x x 280px. Does anyone know how to do that? I have to save as much disk space as possible.

Follow my script, I don’t want to use any class because I think this is very simple to do, I prefer to do it directly in my script that is very simple.

Follows:

<?php

// Recebe a imagem 
$imagem = $_FILES["imagem"];

// Verifica se tem imagem
if (!empty($imagem)) {

// Obtem o tamaho do arquivo
$tamanho = $imagem['size'];

// Tranforma em array o nome do arquivo
$arrArquivo = explode('.', $imagem['name']);

// Obtem a extensão do arquivo
$fileExtencion = trim($arrArquivo [count($arrArquivo) - 1]);

// Array com as extensões permitidas
$arrExtPermitidas = array('JPG', 'PNG');

// Caso a extensão não for permitida
if (!in_array(strtoupper($fileExtencion), $arrExtPermitidas)) {
    ?>
    <script>
        alert('ATENÇÃO. Formato da imagem não é suportado. Use apenas JPG,PNG.');
        history.back();
    </script>
    <?php

    die;
}

// Verifica se o diretório existe   
if (!is_dir("Arquivos/Produtos")) {
    mkdir("Arquivos/Produtos", 0775, true);
}

// Diretorio dos arquivos
$pasta_dir = "Arquivos/Produtos/";

// Definindo o destino do arquivo
$arquivo_nome = $pasta_dir . 'foto' . '.' . $fileExtencion;

// Faz o upload da imagem
move_uploaded_file($imagem["tmp_name"], $arquivo_nome);

} 
  • 1

    This is only possible after doing move_uploaded_file

  • Okay, could you explain or send me an example?

2 answers

3


You will need to:

After move_uploaded_file, make sure the extension is PNG. If it is:

$imagem = imagecreatefrompng($arquivo_nome); //cria uma imagem PNG a partir do caminho
$w = imagesx($imagem); //largura da imagem original
$h = imagesy($imagem); //altura da imagem original
$temp = imagecreatetruecolor(280, 280); //Cria uma imagem 280x280 vazia
imagecopyresized($temp, $imagem, 0, 0, 0, 0, 280, 280, $w, $h); //Copia a imagem original já redimensionada pra imagem que estava vazia
imagejpeg($temp, $pasta_dir . 'foto' . '.jpg', 90); //Converte e salva como JPG com qualidade 90
//imagino que tu vá colocar algo entre 'foto' e a extensão pra diferenciar os nomes dos arquivos
imagedestroy($imagem);
imagedestroy($temp);
  • good muto worked, but I touched that 280px X 280px leaves some distorted images, It has as I limit only the width with 280px and php calculated the proportional height?

  • 1

    You’ll have to do the math, rule 3. And preferably put the 280 in a constant. I just left it right there to simplify.

  • OK understood perfectly, based on your code I am checking the file extension. if it is png I convert it and delete the old photo (png). How I will resize an image that is already jpg?

  • 1

    You need to calculate the desired dimensions even before the $temp = .... Then it makes all the rest the size you want.

  • Um ok, thanks for the help ;)

0

As a complement to the answer, I suggest you use a library that facilitates the image processing process.

The PHP GD library, as quoted in one of the answers, is very good. But I believe that if you have to do a simple operation repeatedly it becomes tiresome, because the passage of parameters to it is extensive! (function of gd that you need to pass some nine parameters)

You can simplify your life, for example by using the library Gregwar\Image. I use and recommend.

To install, you use the composer

php composer.phar require gregwar/image

Then just use it:

use Gregwar\Image\Image;

Image::open($imagem["tmp_name"])
          ->resize(288, 288)
          ->save('nome_de_destino.jpg', 'jpg');

Still in the method save, you can pass a third argument optionally, which is the quality jpg you want to save to the image.

As I said, this way you have to do "less effort", making the operation and code simpler.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.