Home » Php » php – How to convert uploaded images always into JPG format?

php – How to convert uploaded images always into JPG format?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have simply upload:

$path = “uploads/”;

$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
move_uploaded_file($tmp, $path.$actual_image_name);

How can i add for this function imagejpeg? I would like always save image with JPG format.

How to&Answers:

Try this:

<?php

$path = "uploads/";

$img = $_FILES['photoimg']['tmp_name'];
$dst = $path . $_FILES['photoimg']['name'];

if (($img_info = getimagesize($img)) === FALSE)
  die("Image not found or not an image");

$width = $img_info[0];
$height = $img_info[1];

switch ($img_info[2]) {
  case IMAGETYPE_GIF  : $src = imagecreatefromgif($img);  break;
  case IMAGETYPE_JPEG : $src = imagecreatefromjpeg($img); break;
  case IMAGETYPE_PNG  : $src = imagecreatefrompng($img);  break;
  default : die("Unknown filetype");
}

$tmp = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $width, $height, $width, $height);
imagejpeg($tmp, $dst.".jpg");

?>

Answer:

Make sure GD Library is installed and use it to convert gif or png to jpg like

    if ($_FILES["photoimg"]["type"] == "image/jpeg" || $_FILES["photoimg"]["type"] == "image/png" || $_FILES["photoimg"]["type"] == "image/gif" )
    {
      if ($_FILES["photoimg"]["type"] == "image/png" || $_FILES["photoimg"]["type"] == "image/gif" )
      {
       imagejpeg(imagecreatefromstring(file_get_contents($_FILES["photoimg"]["tmp_name"])), "converted.jpg");
       $actual_image_name = time().$session_id.".".$ext;
       move_uploaded_file("converted.jpg", $path.$actual_image_name);
      }
      else
      {
        $actual_image_name = time().$session_id.".".$ext;
        $tmp = $_FILES['photoimg']['tmp_name'];
        move_uploaded_file($tmp, $path.$actual_image_name);
      }
    }