Rename uploaded file

I am trying to convert & rename an uploaded image to a jpg and rename it to thumb.jpg

function convertImage($originalImage, $outputImage, $quality)
{
    // jpg, png, gif or bmp?
    $exploded = explode('.',$originalImage);
    $ext = $exploded[count($exploded) - 1]; 

    if (preg_match('/jpg|jpeg/i',$ext))
        $imageTmp=imagecreatefromjpeg($originalImage);
    else if (preg_match('/png/i',$ext))
        $imageTmp=imagecreatefrompng($originalImage);
    else if (preg_match('/gif/i',$ext))
        $imageTmp=imagecreatefromgif($originalImage);
    else if (preg_match('/bmp/i',$ext))
        $imageTmp=imagecreatefrombmp($originalImage);
    else
        return 0;

    // quality is a value from 0 (worst) to 100 (best)
    imagejpeg($imageTmp, $outputImage, $quality);
    imagedestroy($imageTmp);

    return 1;
}

But I dont think its working

$thumb = convertImage($upload_directory.$tmp, $upload_directory.'thumb,jpg', 100);
								 
echo 'Original Image: '.$upload_directory.$tmp.'<br>';
echo 'MIME type: '.$mime.'<br>';
echo 'New Image: '.$upload_directory.$thumb.'<br>';
echo 'FINAL Image: '.$thumb.'<br>';

The result is

Original Image: images/experiences/14//tmp/phpBR9jsC
MIME type: image/jpeg
New Image: images/experiences/14/0
FINAL Image: 0

Well, what file extension is this? Your code is doing exactly what you told it to do; if you dont know what extension it is, abort and return 0.

Looks more like your problem lies before this point, because the script or server has mangled the uploaded file name.

1 Like

Having that double-slash in the middle of the filename won’t help matters.

1 Like

ok, changed some stuff, heres the function.

function convertImage($originalImage, $outputImage, $quality) {

    switch (exif_imagetype($originalImage)) {
        case IMAGETYPE_PNG:
            $imageTmp=imagecreatefrompng($originalImage);
            break;
        case IMAGETYPE_JPEG:
            $imageTmp=imagecreatefromjpeg($originalImage);
            break;
        case IMAGETYPE_GIF:
            $imageTmp=imagecreatefromgif($originalImage);
            break;
        case IMAGETYPE_BMP:
            $imageTmp=imagecreatefrombmp($originalImage);
            break;
        // Defaults to JPG
        default:
            $imageTmp=imagecreatefromjpeg($originalImage);
            break;
    }

    // quality is a value from 0 (worst) to 100 (best)
    imagejpeg($imageTmp, $outputImage, $quality);
	echo 'New Image: '.$imageTmp.'<br>';
    imagedestroy($imageTmp);
	echo 'New Image: '.$imageTmp.'<br>';

    return 1;
}

The result

I thought that the function is working (a 1 is returned), but what do I have do so that instead the converted image is returned instead?

you’ve converted the file into image data.
Think of image data as a intermediate language.
So now you need to use one of the output functions to render the image data down into a file, because your code doesnt know what sort of file you want out.

    
     $file_name = isset($_FILES['image']['name']) ? $_FILES['image']['name'] : '';
     
    // get file basename
     $file_basename = substr($file_name, 0, strripos($file_name, '.'));
     
     // get file extension
     $file_ext = substr($file_name, strripos($file_name, '.'));
    
    // rename file -- see rename file function I wrote next 
     $newFileName = rename_file(md5(rand(0, 999) . $file_basename)) . $file_ext;
     

// Rename file Function

function rename_file($filename)
{
  return preg_replace('/\s+/', '_', $filename);
}

// Upload your image
uploadPhoto($newFileName);

// Upload Photo Function

function uploadPhoto($file_name)
{
	
	// picture directory
	$upload_path = 'original picture directory';
	$upload_path_thumb =  'your thumb picture directory';
	$file_uploaded = $upload_path . $file_name;
	$file_type = $_FILES['image']['type'];
		
	// upload picture from resources
	
       move_uploaded_file($_FILES['image']['tmp_name'], $file_uploaded);
	
	// checking file type
	$img_source = null;
	
	if ($file_type == "image/jpeg") {
		
		$img_source = imagecreatefromjpeg($file_uploaded);
		
	} elseif ($file_type == "image/png") {
		
		$img_source = imagecreatefrompng($file_uploaded);
		
	} elseif ($file_type == "image/jpg") {
		
		$img_source = imagecreatefromjpeg($file_uploaded);
		
	} elseif ($file_type == "image/gif") {
		
		$img_source = imagecreatefromgif($file_uploaded);
		
	}
	
	$source_width = imagesx($img_source);
	$source_height = imagesy($img_source);
	
	// set picture's size
	$set_width = 320;
	$set_height = ($set_width/$source_width) * $source_height;
	
	// process
	$img_processed = imagecreatetruecolor($set_width, $set_height);
	imagecopyresampled($img_processed, $img_source, 0, 0, 0, 0, $set_width, $set_height, $source_width, $source_height);
	
	// save picture's thumbnail
	if ($_FILES['image']['type'] == "image/jpeg") {
		
	imagejpeg($img_processed, $upload_path_thumb . "thumb_" . $file_name);
		
	} elseif ($_FILES['image']['type'] == "image/png") {
		
	imagepng($img_processed, $upload_path_thumb . "thumb_" . $file_name);
		
	} elseif ($_FILES['image']['type'] == "image/gif") {
		
	imagegif($img_processed, $upload_path_thumb . "thumb_" . $file_name);
		
	} elseif ($_FILES['image']['type'] == "image/jpg") {
		
	imagejpeg($img_processed, $upload_path_thumb . "thumb_" . $file_name);
	
	}
	
	// Delete Picture in computer's memory
	imagedestroy($img_source);
	imagedestroy($img_processed);
	
}

1 Like

Instead of using jpeg as default I would say throw an exception as default, along the lines of “Unknown image type. Only jpeg, gif (etc) images are supported”.

Also, why return 1? :thinking:

The function returns a 1 regardless of what happens within it. As long as it runs to the end of the function, you’ll get a 1 back.

I have to claim ignorance, the function came from…
https://r.search.yahoo.com/_ylt=Az_6wikS7YpbVxYAfzAPxQt.;_ylu=X3oDMTByb2lvbXVuBGNvbG8DZ3ExBHBvcwMxBHZ0aWQDBHNlYwNzcg--/RV=2/RE=1535860115/RO=10/RU=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F14549446%2Fhow-can-i-convert-all-images-to-jpg/RK=2/RS=lCH.p_nHCW4ZU6fq2Dc2QDsGlk8-
(I thought that function uses the output functions)

function convertImage($originalImage, $outputImage, $quality)
{
    // jpg, png, gif or bmp?
    $exploded = explode('.',$originalImage);
    $ext = $exploded[count($exploded) - 1]; 

    if (preg_match('/jpg|jpeg/i',$ext))
        $imageTmp=imagecreatefromjpeg($originalImage);
    else if (preg_match('/png/i',$ext))
        $imageTmp=imagecreatefrompng($originalImage);
    else if (preg_match('/gif/i',$ext))
        $imageTmp=imagecreatefromgif($originalImage);
    else if (preg_match('/bmp/i',$ext))
        $imageTmp=imagecreatefrombmp($originalImage);
    else
        return 0;

    // quality is a value from 0 (worst) to 100 (best)
    imagejpeg($imageTmp, $outputImage, $quality);
    imagedestroy($imageTmp);

    return 1;
}

So when I select an image for upload (which should rename the image to thumb.jpg after the conversion) I get


and when I check the directory to see if the upload was good, I get

So I guess the upload worked, , heres my php to handle the upload stuff (once the image is checked to have the right mime type

					if(in_array($mime, $good_list)) {

					  $upload_directory = 'images/experiences/'.$experienceID.'/'; // Create and append a variable for the upload directory

					  $img_name = explode('.',$fileName);
						
					  $new_name = $img_name[0] . '.' . $img_name[1];
					  
					  echo 'Image: '.$new_name.'<br>';
									
					  $file = $upload_directory . $new_name;
					  
					  echo "Uploading: ".$tmp." => ".$file.'<br>';
						  
						if(move_uploaded_file($tmp, $file)) {
													  
						  $thumb = convertImage($tmp, $upload_directory.'thumb,jpg', 100);
								 
						  echo 'Original Image: '.$tmp.'<br>';
						  echo 'MIME type: '.$mime.'<br>';
						  echo 'New Image: '.$upload_directory.$thumb.'<br>';
						  echo 'FINAL Image: '.$thumb.'<br>';
						  
						  rename($upload_directory.$fileName,$upload_directory.'thumb.jpg') ;
						  echo "Upload Success: ".$tmp." => ".$file;
						  $_SESSION['successful_update'] = 1;
						  header('Location: edit_experience.php?id='.$experienceID.'');
						  die(); 
						
						} else {
						
						  echo "Upload FAIL!: ".$tmp." => ".$file;
						  $_SESSION['failed_update'] = 2;
						  header('Location: edit_experience.php?id='.$experienceID.'');
						  die();													
							
						}
					  
					} else {
					  		
					  $_SESSION['failed_update'] = 2;
					  header('Location: edit_experience.php?id='.$experienceID.'');
					  die(); // Kill anything that happens after this.
					  
					}

Is everything fine?
do I need to do even be using the convertImage() as the file seems to be uploaded & renamed without it?

It doesn’t look fine - all those warnings suggest that things are not fine at all.

ok, trying to do this so its bulletproof (everything works with no warnings), I think I have a problem with the function

function convertImage($originalImage, $outputImage, $quality) {

    switch (exif_imagetype($originalImage)) {
        case IMAGETYPE_PNG:
            $imageTmp=imagecreatefrompng($originalImage);
            break;
        case IMAGETYPE_JPEG:
            $imageTmp=imagecreatefromjpeg($originalImage);
            break;
        case IMAGETYPE_GIF:
            $imageTmp=imagecreatefromgif($originalImage);
            break;
        case IMAGETYPE_BMP:
            $imageTmp=imagecreatefrombmp($originalImage);
            break;
        // Defaults to JPG
        default:
            $imageTmp=imagecreatefromjpeg($originalImage);
            break;
    }

    // quality is a value from 0 (worst) to 100 (best)
    imagejpeg($imageTmp, $outputImage, $quality);
    imagedestroy($imageTmp);

    return $outputImage;
}

I use it like

					if(in_array($mime, $good_list)) {

					  $upload_directory = 'images/experiences/'.$experienceID.'/'; // Create and append a variable for the upload directory

					  $img_name = explode('.',$fileName);
						
					  $new_name = $img_name[0] . '.' . $img_name[1];
					  
					  echo 'Image: '.$new_name.'<br>';
									
					  $file = $upload_directory . $new_name;
					  
					  echo "Uploading: ".$tmp." => ".$file.'<br>';
						  
						if(move_uploaded_file($tmp, $file)) {
													  
						  echo "Image: ".$new_name." => ".$file.'<br>';
						  
						  $thumb = convertImage($tmp, $fileName, 100);
								 
						  //echo 'Original Image: '.$tmp.'<br>';
						  //echo 'MIME type: '.$mime.'<br>';
						  //echo 'New Image: '.$upload_directory.$thumb.'<br>';
						  echo 'FINAL Image: '.$thumb.'<br>';
						  
						  rename($upload_directory.$fileName,$upload_directory.'thumb.jpg') ;
						  echo "Upload Success: ".$tmp." => ".$file;
						  $_SESSION['successful_update'] = 1;
						  header('Location: edit_experience.php?id='.$experienceID.'');
						  die(); 
						
						} else {
						
						  echo "Upload FAIL!: ".$tmp." => ".$file;
						  $_SESSION['failed_update'] = 2;
						  header('Location: edit_experience.php?id='.$experienceID.'');
						  die();													
							
						}


Is that right? Dont I want to only output the converted image?
Here’s my output


the upload works, but when I try and call the function, I get an error
I notice
You must have php_exif extension enabled to use this.
How can I check to see if its enabled?

Remember when I said your filename looked mauled?
You’ve passed the wrong filename to your function. It’s been moved (and renamed in the process) already by the time you call your function, so pass it the location (and filename) it has been moved TO ($file).

1 Like

If you want to do that, I would suggest you’d also need to do some checking inside the function. A lot of your warnings there are because you’re passing in a file that doesn’t exist, but your function doesn’t check that, so it blindly calls various imagecreatefrom*() functions, then a couple more functions, which all throw warnings when there are problems.

The way I would do it would be to check that the files exist before trying to do anything, check the returns from each (I haven’t used any of those image functions, but there’s a trend for returning false in times of trouble) and instead of returning $outputImage regardless, return false if there has been any problem. And check for it in your calling code, too.

You could write the function and presume that the calling code has already checked that the images exist, and make sure all your calling code does just that, but that somehow doesn’t seem “right”.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.