0

I wrote this php function to resize images:

function resizeImage($file,$width,$height){
    $size=getimagesize($file);
    $src = imagecreatefromjpeg($file);
    $dst = imagecreatetruecolor($width,$height);
    imagecopyresampled($dst,$src,0,0,0,0,$width,$height,$size[0],$size[1]);
    return $dst;
}

Unfortunately, certain images get rotated by 180 degrees when I use this function. What can I do about it?

principal-ideal-domain
  • 3,998
  • 8
  • 36
  • 73
  • It doesn't look like this code is doing any rotation. My guess would be that the orientation of these images is actually in the image exif data and that data is being removed by imagecopyresampled. https://stackoverflow.com/questions/21028044/php-keep-exif-data-using-imagecopyresampled – gmfm Sep 13 '18 at 22:15
  • @gmfm Can I modify the function in such a way that it reads the rotation from the exif file and applies it to the resized image? – principal-ideal-domain Sep 13 '18 at 22:17
  • take a look at https://stackoverflow.com/questions/7489742/php-read-exif-data-and-adjust-orientation – gmfm Sep 13 '18 at 22:22
  • @gmfm Thanks. I took a look and could fix my function. I'll post an answer. – principal-ideal-domain Sep 14 '18 at 07:32

1 Answers1

0

gmfm gave me a useful link in the comments. Here is the corrected function:

function resizeImage($file,$width,$height){
    $size=getimagesize($file);
    $src=imagecreatefromjpeg($file);
    $dst=imagecreatetruecolor($width,$height);
    imagecopyresampled($dst,$src,0,0,0,0,$width,$height,$size[0],$size[1]);
    $exif=exif_read_data($file,'IFD0');
    if($exif['Orientation']==3){
        $dst=imagerotate($dst,180,0);
    }
    return $dst;
}
principal-ideal-domain
  • 3,998
  • 8
  • 36
  • 73