Viewing image in browser from database PHP - php

I am trying to create a form that uploads an image to a database and displays the image on the webpage. When I upload an image, the image is added to the database, however it is not displayed on the webpage. It only displays an image icon. I am not receiving any error messages. Here is the uploadpage.php code:
$file = $_FILES['image']['tmp_name'];
if(!isset($file))
echo "That is not an image.";
else
{
$image = mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"]));
$imageName = mysql_real_escape_string($_FILES["image"]["name"]);
$imageSize = #getimagesize($_FILES['image']['tmp_name']);
if ($imageSize==FALSE)
echo "That is not an image.";
else
{
if (!$insert = mysql_query("INSERT INTO storeImage VALUES('','$imageName','$image')"))
echo "Problem Uploading Image";
else
{
$lastid = mysql_insert_id();
echo "Image Uploaded.<p/>Your image:<p/><img src=get.php?id=$lastid>";
}
}
}
And the get.php code:
$id = mysql_real_escape_string($_REQUEST['id']);
$image = mysql_query("SELECT * FROM 'storeImage' WHERE 'id'=$id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];
header("Content-type: image/jpeg");
echo $image;
Thanks so much!

you can upload your image to project folder like "Upload" and image name send to database, then you can get image name from database and you can give path to web page with image name
see https://www.formget.com/upload-images-using-php-and-jquery-via-form/

How about you store the image in the filesystem and save the url to the image in the database instead? Because, from my POV (though I am not well versed in saving binary data to databases), whatever you're doing seems confusing to me. I would rather save the image's location after it's uploaded in the filesystem and store it into the database.
You can then pull it from the database using <img src="<?php echo $image['image_url'];?>">.

Your database might not support images so I suggest you store the uploaded images into a folder like /images and name each one with an id like 176379.png then storing its path in a database. Then when you need to display it, you can use something like something like echo '<img src="{$image}"'>

Related

How do I overwrite old img uploads with new img uploads if they have different extensions

I am working on a profile image upload system. The user is allowed to upload any type image file extension type they want. When the user uploads a jpeg, and then a png, both images are stored inside the uploads folder I made. I want to overwrite the old profile image and only use their latest upload. My code is kind of specific and I've been having trouble finding similar solutions online. Does anyone know what I should do? Thank you.
if (isset($_SESSION['userID'])) {
$id = $_SESSION['userID'];
$userid = "SELECT userid FROM users WHERE username='$id'";
$pictureExist = "SELECT status FROM profileimg WHERE userid='$userid'";
if ($pictureExist == 0) {
echo "<div class='userPicture'><img src='uploads/profile".$id.".jpg?'".mt_rand()."></div>";
}
else {
echo "<div class='userPicture'><img src='uploads/noUser.png'></div>";
}
The Line in question is the profile img source line
I need .jpg? to be something like $fileActualExt but that didnt work when I tried it. :(
if ($pictureExist == 0) {
$filename = "uploads/profile".$id."*";
$fileinfo = glob($filename);
$fileext = explode(".", $fileinfo[0]);
$fileactualext = $fileext[1];
echo "<div class=userPicture><img src='uploads/profile".$id.".".$fileactualext."?".mt_rand()."'></div>";
}

PHP 7 Imagick writeimage() path issue

I'm trying to create a simple thumbnail image and upload to server using imagick. The image is being selected via a form and I am able to get the thumb created via Imagick, however it is not saving to the right location.
When I use the below code, the image saves to the same directory as the page the code is on and includes the file path within the image name. For example "\images\myuploaded.jpg" as the file name.
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$errors = array();
if(preg_match("!image!", $_FILES['image']['type'])){
$image = $_FILES['image']['tmp_name'];
$imagethumb = new Imagick("$image");
$imagethumb->setImageFormat("jpg");
$imagethumb->thumbnailImage(100, 0);
$imgpath = "\images\\".$_FILES['image']['name'];
$imagethumb->writeImage($imgpath);
$_SESSION['message']=$image;
}else{
$errors['image'] = "You must select a .png, .jpg, or .gif images file.";
$_SESSION['message']=$errors['image'];
}
}
Thanks for any help.
_t

php move_uploaded_file() image permission issue

my code is successfully working for upload images. but problem is it fails to display uploaded images. i checked image path output is correct in html source view but image till not displaying. i think its a file permission issue. how can i upload these images with read write full permission so images can display properly.
if(isset($_POST["submit_img"])) {
$target_dir = "../assets/img/temp_img/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$randstr = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 3);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],$target_dir.$randstr))
{
$q =mysqli_query($conn,"INSERT INTO temp_img (product_img_url) VALUES ('$randstr')");
if ($q>0) {
echo "<br>The file has been uploaded.";
}
} else {echo "<br>Error uploading your file.";}
}
//show all uploaded images
$q2 = mysqli_query($conn,"SELECT product_img_url FROM temp_img");
while ($row = mysqli_fetch_array($q2)) {
$product_img_url = $row['product_img_url'];
$img_format = ".jpg";
$broken_url = "assets/img/temp_img/";
echo '<img src="'.$main_url.$broken_url.$product_img_url.$img_format.'" class="img-rounded" alt="Cinque Terre" width="304" height="236">';
}
image missing picture
I think the following link will help you change permissions of your file.
http://php.net/manual/en/function.chmod.php
Note:
1.check whether the uploaded file is in specified folder.
2.try setting the path without "../" in the variable targetdir

Cannot convert blob to image

I have a database where images are saved as blob. Now, I want to convert this blob data into image files.
So I have made this code, but its not giving any result
$sql_icon = "SELECT $off_table.icon,$off_table.id
FROM $off_table,$cnt_table,$ctg_table
WHERE $off_table.id = $cnt_table.id
AND $off_table.id = $ctg_table.id
AND ".$cond_api."
AND ".$cond_nt."
AND ".$cond_cnt."
AND ".$cond_ctg;
$result_icon = mysql_query($sql_icon);
while($row = mysql_fetch_array($result_icon))
{
$image = $row["icon"];
$id = $row["id"];
$file = fopen("./image/".$id.".jpg","w");
fwrite($file, base64_decode($image));
fclose($file);
}
The issue is, I am getting files but no extensions and if I rename them to ".jpg" extension, then its displaying "no preview available"
NOTE:
The images are saved into database by this method
$sql = "INSERT INTO aw_offers_v2
(
id,name,description,payout_type,
payout,expiration_date,creation_date,preview_url,
tracking_url,categories,countries,countries_short,
api_key,network_id, icon,icon_size)
VALUES
('$id','$name','$description','$payout_type',
'$payout','$expiration_time','$creation_time','$preview_url',
'$tracking_url','$categories','$countries','$countries_short',
'$api','$api_url','".mysql_real_escape_string(file_get_contents($cover_image_src))."','".strlen(file_get_contents($cover_image_src))."')";
If I write this code
echo '<img src="data:image/jpeg;base64,'. base64_encode($image).'" />';
then I can see the images properly. That means the images are successfully saved.
But I can't store them in folder as files.
By looking at your code, you don't base64_encode your image.
So you can just do:
fwrite($file, $image);
You only need base64_encode when you display the image putting the data inside the src attribute of <img tag.
Also note that you can simplify this:
$file = fopen(...);
fwrite($file, $image);
fclose($file);
with a single line:
file_put_contents("./image/{$id}.jpg", $image);

resize width and compress images on upload php mysql

I have a client that sends me text messages from his iPhone with images for me to upload into his gallery. I'm trying to create a admin system so I can simply take the images from the texts, go to the admin page on my iPhone and upload the images straight to the gallery.
This would save me tons of time in my day to day work schedule.
Using the provided code. How can I add the following functions:
I would like to compress the file size down to a smaller size if possible, similar to the save to web jpg function in Photoshop. (Most images I get are around 1-3 MB. I would like to get them down to around 150-500kb max)
I would like to automatically change the width to 760px, but keep the aspect ratio so the images are not squished. He sends me landscape and portrait images.
Beings they are iPhone images. They have an extension .JPG (all caps) I would like this to change to .jpg (all lower case.) This is not a deal breaker I would just like to know how to do this for future use.
Either one of these functions would be very helpful, but all 3 would be ideal for my situation.
Here is the code I'm working with?
THIS IS THE FINAL CORRECT CODE FOR UPLOADING AND RESIZING IMAGES PROVIDED By #tman
Make sure you have imagick installed in your php.ini file. Check with your hosting provider to install it.
<?php
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
for($i=0;$i<count($_FILES["image"]["name"]);$i++){
if($_FILES["image"]["name"][$i] != ''){ // don't insert if file name empty
$dataType = mysql_real_escape_string($_POST["dataType"][$i]);
$title = mysql_real_escape_string($_POST["title"][$i]);
$fileData = pathinfo($_FILES["image"]["name"][$i]);
$fileName = uniqid() . '.' . $fileData['extension'];
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $fileName;
if (move_uploaded_file($_FILES["image"]["tmp_name"][$i], $target_path)){ // The file is in the images/gallery folder.
// Insert record into database by executing the following query:
$sql="INSERT INTO images (data_type, title, file_name) "."VALUES('$dataType','$title','$fileName')";
$retval = mysql_query($sql);
///NEW
$size = getimagesize($target_path);
$width=$size[0];
$height=$size[1];
$newwidth = 760;
$newheight = $height*($newwidth/$width);
$pic = new Imagick($target_path);//specify name
$pic->resizeImage($newwidth,$newhight,Imagick::FILTER_LANCZOS,1);
unlink($target_path);
$pic->writeImage($target_path);
$pic->destroy();
///NEW
echo "The image {$_FILES['image']['name'][$i]} was successfully uploaded and added to the gallery<br />
<a href='index.php'>Add another image</a><br />";
}
else
{
echo "There was an error uploading the file {$_FILES['image']['name'][$i]}, please try again!<br />";
}
}
} // close your foreach
?>
uploader.php Original code. Allows me to upload 4 images at once. WORKS!!!
<?php
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
for($i=0;$i<count($_FILES["image"]["name"]);$i++){
if($_FILES["image"]["name"][$i] != ''){ // don't insert if file name empty
$dataType = mysql_real_escape_string($_POST["dataType"][$i]);
$title = mysql_real_escape_string($_POST["title"][$i]);
$fileData = pathinfo($_FILES["image"]["name"][$i]);
$fileName = uniqid() . '.' . $fileData['extension'];
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $fileName;
if (move_uploaded_file($_FILES["image"]["tmp_name"][$i], $target_path)){ // The file is in the images/gallery folder.
// Insert record into database by executing the following query:
$sql="INSERT INTO images (data_type, title, file_name) "."VALUES('$dataType','$title','$fileName')";
$retval = mysql_query($sql);
echo "The image {$_FILES['image']['name'][$i]} was successfully uploaded and added to the gallery<br />
<a href='index.php'>Add another image</a><br />";
}
else
{
echo "There was an error uploading the file {$_FILES['image']['name'][$i]}, please try again!<br />";
}
}
} // close your foreach
?>
FYI, This will allow you to give a unique names to your images, resize the width, but keep the correct aspect ratio and upload multiple file at the same time.
Awesome Stuff!
Like this:
$filelocation='http://help.com/images/help.jpg';
$newfilelocation='http://help.com/images/help1.jpg';
$size = getimagesize($filelocation);
$width=$size[0];//might need to be ['1'] im tired .. :)
$height=$size[1];
// Plz note im not sure of units pixles? & i could have the width and height confused
//just had some knee surgery so im kinda loopy :)
$newwidth = 760;
$newheight = $height*($newwidth/$width)
$pic = new Imagick( $filelocation);//specify name
$pic->resizeImage($newwidth,$newhight,Imagick::FILTER_LANCZOS,1);
//again might have width and heing confused
$pic->writeImage($newfilelocation);//output name
$pic->destroy();
unlink($filelocation);//deletes image
Here is something kind of similar, lets check the size and compress if the image seems that it is too big. I didn't resize it which just requires that you get the dimensions and resize based on desire.
All this is doing is if the file is greater than 250KB compress it to 85% ..
$bytes = filesize($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
//$maxSizeInBytes = 26400; //is 250KB? No? compress it.
if ($bytes > 26400) {
$img = new Imagick($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
$img->setImageCompression(imagick::COMPRESSION_JPEG);
$img->stripImage();
$img->setImageCompressionQuality(85);
$img->writeImage($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
}
OR:
// resize with imagejpeg ($image, $destination, $quality); if greater than byte size KB
// Assume only supported file formats on website are jpg,jpeg,png, and gif. (any others will not be compressed)
$bytes = filesize($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
//$maxSizeInBytes = 26400; //is gtr than 250KB? No? compress it.
if ($bytes > 26400) {
$info = getimagesize($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
$quality = 85; //(1-100), 85-92 produces 75% quality
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
imagejpeg($image,$inventory_path.DIRECTORY_SEPARATOR.$this->uploadName,$quality);
} elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
imagejpeg($image,$inventory_path.DIRECTORY_SEPARATOR.$this->uploadName,$quality);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName
imagejpeg($image,$inventory_path.DIRECTORY_SEPARATOR.$this->uploadName,$quality);
}
}

Categories