Solved

How to enlarge Thumbnail pictures in php?

Posted on 2013-11-27
4
822 Views
Last Modified: 2014-04-30
Hi,

I am working on a Photo Album, where user will be uploaded photos and after review of Moderator, the same will be published for public.

In the moderator view, I am displaying all the uploaded pictures as a Thumbnail and would like to give the option to Moderator to enlarge, before publishing the same.
Can you let me know how to enlarge the pictures on Mouseover or click.

=====

<tr>
      <td><input type="checkbox" name="hioddenid<?php echo $i; ?>" value="<?php echo $row['id']; ?>" /></td>
      <td><?php echo $row['name']; ?></td>
      <td><?php echo $row['email']; ?></td>
      <td><img src="images/<?php echo $row['picture'];?>" height="80" width="100"/></td>
      <input type="hidden" name="image<?php echo $i; ?>" value="<?php echo $row['picture'];?>" />
</tr>

====

The entire code is attached as a file.

Thank you for your help.

Regards,
imageview.php
0
Comment
Question by:AmitavaCh
  • 2
4 Comments
 
LVL 7

Expert Comment

by:dimmergeek
ID: 39680879
Rather than enlarging a current image, why not save two versions of the image during the time of initial upload?
You can upload the file and save one version to a directory called large, and reduce the size to your desired dimensions and save it to a directory called thumbs.
Ray_Paseur provided a great script for doing just that.
It is great and eliminates image degradation as you try to enlarge an existing image.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39680894
Here is the code, posted in the code snippet.  It is a technically incompetent piece of code and probably should be discarded for obsolescence and security reasons.  But that aside, you do not want to enlarge a thumbnail if there is any way to avoid it.  Instead you want to work from the original image.  The thumbnail has lost some of the image information and no amount of guesswork is likely to recover the lost data.

I would design this application as follows:

1. Upload the image and move it to an "originals" folder
2. Prepare the (thumbnail) view for the moderator
3. Upon the moderator's signal, go back to the "originals" version of the image for any further processing before public display.

<?
session_start();
if(!session_is_registered(myusername)){
header("location:mediatorlogin.php");
session_destroy();
}
?>
<?php
include 'config.php';
error_reporting(E_ALL ^ E_NOTICE);
$select = mysql_query("SELECT * from myimages");
if(isset($_POST['submit']))
{
	for($i=1;$i<=$_POST['hidden'];$i++)
	{
		
		$query2 = mysql_query("SELECT picture from myimages WHERE id = ' ".$_POST["hioddenid$i"]." ' ");
		
		while($file = mysql_fetch_array($query2))
		{
		$unlink = unlink('images/'.$file['picture']);
		$unlink1 = unlink('images/'.$file['picture'].'.txt');
		if($unlink)
		{
		$query1 = mysql_query("DELETE from myimages WHERE id = ' ".$_POST["hioddenid$i"]." ' ");
		//echo 'Deleted , You Will be Redirect';
		//header("refresh : 3 imageview.php");
		header('Location: imageview.php');
		}
		else
		{
		echo 'Not deleted';
		}
		}
	}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
    history.forward();
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>View Images</title>
</head>

<body>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<table align="center" cellspacing="15">
<tr><a href="MediatorLogout.php">Logout</a></tr>
<tr>
	<th align="left">Action</th>
	<th align="left">Uploder Name</th>
	<th align="left">Caption</th>
	<th align="left">Picture</th>
</tr>
<?php
$i = 0;
while($row = mysql_fetch_array($select))
{
$i = $i + 1;
?>
<tr>
	<td><input type="checkbox" name="hioddenid<?php echo $i; ?>" value="<?php echo $row['id']; ?>" /></td>
	<td><?php echo $row['name']; ?></td>
	<td><?php echo $row['email']; ?></td>
	<td><img src="images/<?php echo $row['picture'];?>" height="80" width="100"/></td>
	<input type="hidden" name="image<?php echo $i; ?>" value="<?php echo $row['picture'];?>" />
</tr>
<?php
}
?>
<tr>
	<input type="hidden" name="hidden" value="<?php echo $i; ?>" />
	<td colspan="3" align="center"><input type="submit" name="submit" value="Delete"/></td>
</tr>
</table>
</form>
</body>
</html>

<?
/*
//to create text file for description

$text1=$_POST['email'];

$filename = $_FILES["file"]["name"].".txt" ;
$Content = $text1;
 
//echo "open";
$handle = fopen("images/" .$filename, 'x+');
//echo " write";
fwrite($handle, $Content);
//echo " close";
fclose($handle);
*/
?>

Open in new window

0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 39680907
To help you move forward, here are some ideas and guidance.  You must get off MySQL because PHP is doing away with that data base extension.  An explanation of why and what you must do is in this article.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

This article will show how to make a thumbnail from an image.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_6554-Use-PHP-to-Make-an-Image-Thumbnail.html

This code snippet will show how to upload files safely.
<?php // RAY_upload_example.php
error_reporting(E_ALL);


// MANUAL REFERENCE PAGES YOU MUST UNDERSTAND TO UPLOAD FILES
// http://php.net/manual/en/reserved.variables.files.php
// http://php.net/manual/en/features.file-upload.php
// http://php.net/manual/en/features.file-upload.common-pitfalls.php
// http://php.net/manual/en/function.move-uploaded-file.php
// http://php.net/manual/en/function.getimagesize.php

// MANUAL PAGES THAT ARE IMPORTANT IF YOU ARE DEALING WITH LARGE FILES
// http://php.net/manual/en/ini.core.php#ini.upload-max-filesize
// http://php.net/manual/en/ini.core.php#ini.post-max-size
// http://php.net/manual/en/info.configuration.php#ini.max-input-time


// PHP 5.1+  SEE http://php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set('America/Chicago');

// ESTABLISH THE NAME OF THE DESTINATION FOLDER ('uploads' DIRECTORY)
$uploads = 'RAY_junk';
if (!is_dir($uploads))
{
    mkdir($uploads);
}

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 8 MB
$max_file_size = '8000000';

// ESTABLISH THE MAXIMUM NUMBER OF FILES WE CAN UPLOAD
$nf = 3;

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array
( 'jpg'
, 'gif'
, 'png'
, 'txt'
, 'pdf'
)
;

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED ERROR"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;




// IF THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT
if (empty($_POST))
{
    ?>
    <h2>Upload <?php echo $nf; ?> file(s)</h2>

    <!--
        SOME THINGS TO NOTE ABOUT THIS FORM...
        ENCTYPE IN THE HTML <FORM> STATEMENT
        MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD
        INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN $_FILES ARRAY
        ABSENCE OF ACTION= ATTRIBUTE IN FORM TAG CAUSES POST TO SAME URL
    -->

    <form name="UploadForm" enctype="multipart/form-data" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" />
    <p>
    Find the file(s) you want to upload and click the "Upload" button below.
    </p>

    <?php // CREATE INPUT STATEMENTS FOR UP TO $n FILE NAMES
    for ($n = 0; $n < $nf; $n++)
    {
        echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>\n";
    }
    ?>

    <br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <strong>overwrite</strong> existing files.
    <input type="submit" value="Upload" />
    </form>
    <?php
    die();
}
// END OF THE FORM SCRIPT



// WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
else
{
    // THERE IS POST DATA - PROCESS IT
    echo "<h2>Results: File Upload</h2>\n";

    // ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
    // echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>\n";

    // ITERATE OVER THE CONTENTS OF $_FILES
    foreach ($_FILES as $my_uploaded_file)
    {
        // SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
        $error_code = $my_uploaded_file["error"];
        if ($error_code == 4) continue;

        // SYNTHESIZE THE NEW FILE NAME
        $f_type    = trim(strtolower(end    (explode( '.', basename($my_uploaded_file['name'] )))));
        $f_name    = trim(strtolower(current(explode( '.', basename($my_uploaded_file['name'] )))));
        $my_new_file
        = getcwd()
        . DIRECTORY_SEPARATOR
        . $uploads
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type
        ;
        $my_file
        = $uploads
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type;

        // OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
        if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");

        // IF THERE ARE ERRORS
        if ($error_code != 0)
        {
            $error_message = $errors[$error_code];
            die("Sorry, Upload Error Code: $error_code: $error_message");
        }

        // GET THE FILE SIZE
        $file_size = number_format($my_uploaded_file["size"]);

        // IF THE FILE IS NEW (DOES NOT EXIST)
        if (!file_exists($my_new_file))
        {
            // IF THE MOVE FUNCTION WORKED CORRECTLY
            if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
            {
                $upload_success = 1;
            }
            // IF THE MOVE FUNCTION FAILED
            else
            {
                $upload_success = -1;
            }
        }

        // IF THE FILE ALREADY EXISTS
        else
        {
            echo "<br/><b><i>$my_file</i></b> already exists.\n";

            // SHOULD WE OVERWRITE THE FILE? IF NOT
            if (empty($_POST["overwrite"]))
            {
                $upload_success = 0;
            }
            // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
            else
            {
                $now    = date('Y-m-d');
                $my_bak = $my_new_file . '.' . $now . '.bak';
                if (!copy($my_new_file, $my_bak))
                {
                    echo "<br/><strong>Attempted Backup Failed!</strong>\n";
                }
                if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
                {
                    $upload_success = 2;
                }
                else
                {
                    $upload_success = -1;
                }
            }
        }

        // REPORT OUR SUCCESS OR FAILURE
        if ($upload_success == 2) { echo "<br/>It has been overwritten.\n"; }
        if ($upload_success == 1) { echo "<br/><strong>$my_file</strong> has been saved.\n"; }
        if ($upload_success == 0) { echo "<br/><strong>It was NOT overwritten.</strong>\n"; }
        if ($upload_success < 0)  { echo "<br/><strong>ERROR: $my_file NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</strong>\n"; }
        if ($upload_success > 0)
        {
            echo "$file_size bytes uploaded.\n";
            if (!chmod ($my_new_file, 0755))
            {
                echo "<br/>chmod(0755) FAILED: fileperms() = ";
                echo substr(sprintf('%o', fileperms($my_new_file)), -4);
            }
            echo "<br/><a target=\"_blank\" href=\"$my_file\">See the file $my_file</a>\n";
        }
    // END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
    }
}

Open in new window

HTH, ~Ray
0
 

Author Closing Comment

by:AmitavaCh
ID: 40031968
Thank you
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
These days socially coordinated efforts have turned into a critical requirement for enterprises.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now