0

I have given an option to user to Export Images As JPG and I have stored png images
So, i have created some php script to do so.
png is converting fine..
but when i downloaded the jpg image and try to open in image viewer, its showing corrupted.
My php code:

Converting PNG to JPG

$input_file = 'images/image1364926178.png';
$filename = time().'.jpg';
$output_file = 'images/'.$filename;                 
$input = imagecreatefrompng($input_file);
if($input){
    list($width, $height) = getimagesize($input_file);
    $output = imagecreatetruecolor($width, $height);
    $white = imagecolorallocate($output,  255, 255, 255);
    imagefilledrectangle($output, 0, 0, $width, $height, $white);
    imagecopy($output, $input, 0, 0, 0, 0, $width, $height);
    imagejpeg($output,$output_file);
}

Script downloading jpg image

$Image_file_name = '/images/'.$filename;
$filedetail = getimagesize($filename);
$mimetype = $filedetail['mime'];
if (file_exists($filename)) {
    @ob_end_clean();                    
    header('Content-Description: File Transfer');
    header('Content-Type: '.$mimetype);
    header('Content-Disposition: attachment; filename='.basename($filename));
    header("Content-Transfer-Encoding: binary");
    header('Accept-Ranges: bytes');
    header('Cache-Control: private');
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
}

What am i doing wrong?
OR
Is there any better idea for how to do that?

Thanks in Advance

Shail Paras
  • 1,125
  • 1
  • 14
  • 34
  • Does this answer your question? [Use PHP to convert PNG to JPG with compression?](https://stackoverflow.com/questions/1201798/use-php-to-convert-png-to-jpg-with-compression) – AamirSohailKmAs Nov 28 '21 at 15:11

1 Answers1

1

A simple google let me get this question on stackoverflow, a simple function is given to convert images.

For the correct jpg headers I found this answer.

Combining the two should do the job

Community
  • 1
  • 1
MKroeders
  • 7,562
  • 4
  • 24
  • 39