How to resize an image file on php? - php

I have an image file which is stored onto database as a blob (shown in the code). Once resized to 80*80(thumbnail) I need to store it onto some other database. I have resized and saved it as a file but I couldn't store the resized image onto database. How can I achieve this?
//resize image and save
include('MyImage.php');
$image = new MyImage();
$image->load($tmpName);
$image->resize(80,80);
$image->save('thumbnail.jpg');
//storing original image onto database
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO image_tbl (name, size, type, content )".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
}

The direct question to your answer is
//This goes after the frist block, after "$image->save('thumbnail.jpg');"
$fileSize=filesize('thumbnail.jpg')
$fp = fopen('thumbnail.jpg', 'rb');
$content = fread($fp, $fileSize);
$content = addslashes($content);
fclose($fp);
$query = "INSERT INTO image_tbl (name, size, type, content )".
"VALUES ('thumbnail.jpg', '$fileSize', 'image/jpeg', '$content')";
mysql_query($query) or die('Error, query failed');
You might recognize some elements of that code :-)
But believe me, you do not want this:
Storing BLOBs in the DB, that the DB doesn't understand is a bad idea
using strings and addslashes to achieve it, is very close to the worst case possible: You read the image into a string consisting of ca 50% unprintables, backslash it, transport it to the DB, where it is unbackslashed and parsed. Use prepared statements with parameters (if you really want to save the image in the DB)

Try this:
$file = $path_you_saved_image."/".$your_image_name;
$handle = fopen( $file , "rb" );
$img = fread($handle , filesize($file) );
$img = base64_encode($img);
$query = "insert into images (image) values ('$img')";
mysql_query($query) or die(mysql_error());

you code suggests that you have saved the resized image. Now open this resized image 'thumbnail.jpg' and process it, encode it and save it.

Related

PHP image compression and uploading to mysql

I have a php script, which uploads pictures to a mysql database. The images are taken within the browser. I would like to compress them before uploading, but I'm not quite sure how exactly to compress the uploaded data. What I've got for the moment is this:
if(isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0)
{
//$positiony = $_POST['posy'];
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
$content = imagejpeg($content,null,50);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO upload (team_name, id, display, content) ".
"VALUES ('$team_name', 'null', '1', '$content')";
mysql_query($query) or die('Error, query failed'.mysql_error());
echo "<br>File $fileName uploaded<br>";
}
The image uploading works fine, but the uploaded images are broken. Introducing imagejpeg as a form of compressing has caused the issues. Should I be using it on something else?
Most images are already compressed so there is no need to "compress them further".
Storing them in a database is not a recommended thing to do. Just upload them to a location on the server and save the path to that location.

Issues with saving PNG images to mysql database

I have trouble storing .png images with this script. It stores .jpeg images, but not successfully storing .png. Problem is that with .png only half of the picture is stored. The image field in the database is of type blob.
When testing on my local xampp installation it stores lets say 90% of the picture, but when I try it on a hostgator hosted domain it stores lets say 45% of the picture
Don't think it is about the images are larger than the image column in the database as I have stored larger .jpeg images...
static function save($_FILES) {
$link = mysql_connect("localhost",DBUSER,DBPASS) or die("<b>Error:</b><br>".mysql_error());
mysql_select_db(DBNAME,$link) or die("Cant select db");
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$sql = "INSERT INTO image
(type, image, size, name)
VALUES ('" . mysql_real_escape_string($_FILES['image']['type']) . "', '" . $data . "', '" . $_FILES['image']['size'] . "', '" . mysql_real_escape_string($_FILES['image']['name']) . "')";
mysql_query($sql);
}
Change this line
$fp = fopen($tmpName, 'r');
to
$fp = fopen($tmpName, 'rb');
or try to use
file_get_contents()
and check.

Displaying images from mysql database - php

I am currently having problems with displaying image from mysql database. I am able to upload an image to mysql database, however if i want to retrieve it from the database, it is displayed in Gibberish text.
Here is upload.php
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
$filename = mysqli_real_escape_string($mysqli,$_FILES['image']['name']);
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$query = "INSERT INTO `TABLES` (`image`)
VALUES( NULL,'$data')";
$result = $mysqli->query($query);
}
View.php
$mysqlquery = "SELECT * FROM TABLE";
$results = $mysqli->query($mysqlquery);
if($results->num_rows > 0){
while ($row = $results ->fetch_assoc()){
echo '<div align = "center">';
echo "<b>".$row["image"]. "<br></b>";
header("Content-type: image/jpeg");
}
}
Try this and do not forget to give image path before source
echo "<img src='your image location directory/". $row['image'] .'" >";
Oooooh... I just wish I had the answer to this one...
Some thoughts, though.
First, from personal experience I urge against storing images in the database. For one thing, your database backups will quickly become ridiculous. A more common, and better, approach is to store the images in the file system and store only the location (e.g. /img/pic03.jpg ) of the image in the database.
Next, I see you are modifying the received binary data:
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
Perhaps you know something that I don't (it's not difficult), but generally, if you gerfingerpoke with binary image data you get ... um... gibberish. Try disabling those lines and see what happens.

Files are corrupted when they are retrieved from database

In my website, I want to allow the user to upload files (they will be stored in a database) and then allow them to download the uploaded files after that. The uploading process is done without errors and they are saved in binary.
The downloading process also works but the downloaded files are corrupted !
Any idea why?
The uploading code:
<?php require_once('Connections/databasestudents.php'); ?>
<?php
$fileName = $_FILES['file']['name'];
$tmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileType = $_FILES['file']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
$studentId = $_POST['studentId'];
fclose($fp);
$query = "INSERT INTO file (studentId, fileName, fileType, fileContent ) ".
"VALUES ('$studentId', '$fileName', '$fileType', '$content')";
mysql_select_db($database_databasestudents, $databasestudents);
mysql_query($query) or die('Error, query failed');
header("Location: students.php");
die();
?>
The download code:
<?php require_once('Connections/databasestudents.php'); ?>
<?php
mysql_select_db($database_databasestudents, $databasestudents);
$query = 'SELECT fileName, fileContent, fileType, LENGTH(fileContent) as fileSize from file WHERE id="'. $_GET ['id'].'";';
$Recordset1 = mysql_query($query, $databasestudents) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$result = mysql_query($query);
$row = mysql_fetch_array($result, MYSQL_BOTH);
$size = $row['fileSize'];
$type = $row['fileType'];
$name =$row['fileName'];
$fileContent = $row['fileContent'];
echo $size . "". $type . " ". $name;
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $fileContent;
mysql_close();
?>
Use PDOs and prepared statements. This may fix the issue, and it will fix the SQL injection vulnerability in the download code (which currently allows people to hack your database).
PDO has "large objects" (LOBs) support meant for exactly what you are doing. It will be much more efficient than what you are currently doing. The documentation provides excellent example code which does more or less exactly what you want.
I've figured it out .. jus removing this line from the download code:
echo $size . "". $type . " ". $name;

How to make users able to upload images in a form?

I have a classifieds website where users must fill in a form in order to put a ad. The form consists of name, password, category, specifications etc etc.
Now, I need to add a image upload function into this form, which must have the following:
1- Upload up to 5 images.
2- A 'remove image link' beneath each image if the user wants another image instead.
How would you do this?
Thanks
Best would be if there was a plugin or something to Jquery which is easy to modify...
jQuery Multiple File Upload
You can limit the number of uploads using the max option or passing a number as the only parameter. More info on the Examples tab.
If you want to upload it as a file to an SQL database, have something like this in the form (in php echo format):
echo "<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"2000000\">
<input name=\"userfile\" type=\"file\" id=\"userfile\">";
Then in your form's receiving php page put something like this:
if ($_FILES['userfile']['size'] > 0) {
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO files (name, size, type, content ) VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
$thisq = mysql_query("SELECT * FROM `files` WHERE 1 ORDER BY `id` DESC LIMIT 1");
$fileidnumber= mysql_fetch_array($thisq);
}
That will store the file to a database and then return the key for you to save or use however you'd like. You can then create a page to download the files like this:
<?php
import_request_variables(gp);
if(isset($_GET['id'])) {
// if id is set then get the file with the id from database
$id = $_GET['id'];
$query = "SELECT name, type, size, content " .
"FROM `files` WHERE id = '$id'";
$result = mysql_query($query) or die('Error, query failed');
list($name, $type, $size, $content) = mysql_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $content;
exit;
}
?>

Categories