PHP - How to crop a image? - php

I am making a social media and I'm echoing profile pictures this way (code beneath), but I need to rescale the images that the users upload before echoing them. Either that or resize them before they get uploaded to the server.
Does anyone have some suggestions?
$stmt = $conn->prepare("SELECT ID, fname, profilePicture from users");
$stmt->execute();
$out = "";
while($row = $stmt->fetch()){
$picture = "<img src='profilePictures/$row[2]'>";
$out .="<a href='profile.php?user=$row[0]'> $picture $row[1] </a> <br/>";
}
echo $out;

The most common PHP library for this type of thing is imagemagick https://www.imagemagick.org/script/index.php. It should be fairly easy to do the manipulations with that.
When the users upload the photos you can save a smaller version as a thumbnail or profile pic (as well as the original if you'll need it later).

There's a nice library called Intervention Image, which can both utilize PHP's ImageMagick- and GD-extensions as drivers. Here's a very basic example:
Image::make('path/to/image.jpg')
->resize(320, 240)
->save('path/to/ouput/image.jpg');

Related

Php images display from database

i created a form which store clients passports in my database. i want to retrive the images but its has not been giving me the images on the screen. instead , it write long alphabeth of different symbols .
below is my codes , pls help me out. thanks
$sql = "SELECT * FROM `file` WHERE id = 8";
$mq = mysqli_query($dbconnect, $sql) or die ("not working query");
$row = mysqli_fetch_array($mq) or die("line 44 not working");
$s=$row['data'];
echo $row['data'];
echo '<img src="'.$s.'" alt="HTML5 Icon" style="width:128px;height:128px">';
what is wrong with my codes please.
thanks
Because you say you see lots of characters instead of the filename, I assume that you don't store a path to that image (then you could use src as you tried to use), but the image content itself and that it is jpg (you can change to png or whatever type you have there). If so, use data URI syntax for src:
$src = "data:image/jpg;base64,".base64_encode($row['data']);
echo '<img src="'.$src.'" alt="HTML5 Icon" style="width:128px;height:128px">';
It is called data URI - you can read more about it for example here: https://en.wikipedia.org/wiki/Data_URI_scheme

php - Unable to display image

I'm very new to development, and I'm trying to retrieve an image from an SQL server over an odbc connection using the below:
<?php
require ('connect.inc.php');
$sql = "SELECt image FROM test.dbo.clients WHERE id = 1";
$sql_exec = odbc_exec($con, $sql);
if($sql_array = odbc_fetch_array($sql_exec)){
$image = base64_encode($sql_array['image']);
header('Content-type: image/jpeg');
echo "<img src=".$image."/>";
}
?>
The issue is that I'm getting an icon showing a broken image.
The query is correct as when I change it to the code below, it returns this string instead of the image:
Q2hyeXNhbnRoZW11bS5qcGc=
<?php
require ('connect.inc.php');
$sql = "SELECt image FROM test.dbo.clients WHERE id = 1";
$sql_exec = odbc_exec($con, $sql);
if($sql_array = odbc_fetch_array($sql_exec)){
$image = base64_encode($sql_array['image']);
echo $image;
}
?>
I know the code is not correct and might be vulenrable to SQL injection, however I'd appreciate if you can help me retrieve the image.
Many thanks in advance,
J
If you decode the base64 string you get, then you'll see that the decoded data is Chrysanthemum.jpg. This is just the filename of the image, not the image data.
You need to either store the image in the database (not the filename) or add some code to read the image from the filesystem.
BTW, Content-Type image/jpeg requires that the data is the raw image, but your content (<img src=...> ...</img>) is an HTML fragment.

How to display through php an image stored in a folder considering that my image's link is stored in MySQL database

As good practice, I'm only storing my image's link in my database, the questios are:
How should I store my image's link? (let's say it's on c:)
c://image.jpg?
Which peace of PHP code should I use to display that image?
I'm only displaying the path, what should I do to display the image?
Can I use this:
$query = "SELECT ImageURL from WhateverTable";
$result = mysql_query($query) or die(mysql_error());
$Image = mysql_fetch_row($result);
echo "<img src='$Image[0]' alt='This is an image'>";
Thank you all lads
You only want to store the relative path, not the absolute path, as linking to something like
<img src="/var/www/vhosts/website.com/images/file.jpg">
would return a 404 on any real website. store your files in the database via a relative path (/images/file.jpg) or by only the filename if they are all in the same directory.
alternatively, you can learn MongoDB and it allows you to actually store files in the database itself.
I would strongly suggest that you use PDO instead.
Use relative URLs to your image folder in case you need to move them one day.
Here is an example.
// relative to your public webroot
$publicImageUrl = '/images/in/here';
// Pull up some record, maybe of a product
$select = 'SELECT imageFilename FROM products WHERE id = 2332';
$results = mysql_query($select);
if(!$results) {
// issue with query. deal with it here
} else {
if( mysql_num_rows($result) ) {
// record not found. deal with it here
}
$row = mysql_fetch_array($result);
$imageSrc = $publicImageUrl . '/' . $row['imageFilename'];
}
And then your HTML would be as follows
<img src="<?php echo $imageSrc; ?>" />
use PDO for php <-> mysql connection
post mysql query output

Inserting Thumbnail into Database

I have successfully added the original image into my imgs/ folder and also onto the server. But I'm wanting to add the thumbnail into the database. I've added it into the imgs/ folder but can't seem to find away to insert it into the database.
This is the final bit of code that is used to crop the img and insert it to the folder.
I need to insert it into the database also so I can call on it for the $_SESSION User and the Users friend as I have profiles.
if (isset($_POST["upload_thumbnail"]) && strlen($large_photo_exists)>0) {
//Get the new coordinates to crop the image.
$x1 = $_POST["x1"];
$y1 = $_POST["y1"];
$x2 = $_POST["x2"];
$y2 = $_POST["y2"];
$w = $_POST["w"];
$h = $_POST["h"];
//Scale the image to the thumb_width set above
$scale = $thumb_width/$w;
$cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
//Reload the page again to view the thumbnail
header("location:".$_SERVER["PHP_SELF"]);
exit();
}
if(isset($_GET['a'])){
if ($_GET['a']=="delete"){
if (file_exists($large_image_location)) {
unlink($large_image_location);
}
if (file_exists($thumb_image_location)) {
unlink($thumb_image_location);
$creator_id = $_SESSION['id'];
$sql = "UPDATE users SET user_pic_small='".$img."' WHERE id=$creator_id";
$sql2 = "INSERT INTO userphotos(photo_ownerid,photo_ispublic, photo_name, photo_caption, photo_imagedata) VALUES ($creator_id,1,'Profile Picture','Profile Picture','$img')";
// insert the image
if(!mysql_query($sql)) {
echo "Fail. It broke.";
}else{
$c=mysql_query($sql2);
echo "<script> parent.alert('Image Uploaded','',1000);</script>";
}
}
}
}
Hope someone can help. Thanks.
If you want to add in your database the path of thumbnail ($thumb_image_location), just add the code that inserts the path before unlink().
If you want to store the whole image into database, you need the column to be MEDIUMBLOB type, then, before unlink() read the code of the file that contains the image, for example with:
$img = file_get_contents($thumb_image_location);
Then, INSERT data stored in $img into your database.
Ideally, you don't want to be adding the thumbnail itself to the database, just a reference (filepath) to the file. So, while I don't know what your database looks like, you need to go through the following steps:
Create a field in your table called 'thumbnail' or similar. This will hold the name which the thumbnail file is saved as.
Add the filepath to the database immediately after you crop the large image (ie between the lines '$cropped = ...' and 'header("location....' in your code)
Whenever a user or user's friend is logged in, check this field and pull any thumbnail images referenced in the table.
And that is basically it.
If you want to store only the path of the Image into Database ,than it's fine to insert only the path and serve it with HTML.
Otherwise if you want to store the raw data of the image into Database than you have to encode the Image into base64 String .
Sending/Displaying a base64 encoded Image - Here is how you encode and image at base64.
And store this huge string into a Blob Field Type into databse.
You can use this:
// Read the file
$fp = fopen($file, 'r');
$data = fread($fp, filesize($file));
$data = addslashes($data);
fclose($fp);
// Create the query and insert into our database.
// image is an BLOB field type
$query = "INSERT INTO tbl_images ";
$query .= "(image) VALUES ('$data')";
$results = mysql_query($query, $link);

Oracle Blob as img src in PHP page

I have a site that currently uses images on a file server. The images appear on a page where the user can drag and drop each as is needed. This is done with jQuery and the images are enclosed in a list. Each image is pretty standard:
<img src='//network_path/image.png' height='80px'>
Now however I need to reference images stored as a BLOB in an Oracle database (no choice on this, so not a merit discussion). I have no problem retrieving the BLOB and displaying on it's own using:
$sql = "SELECT image FROM images WHERE image_id = 123";
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
$img = $row['IMAGE']->load();
header("Content-type: image/jpeg");
print $img;
But I need to [efficiently] get that image as the src attribute of the img tag. I tried imagecreatefromstring() but that just returns the image in the browser, ignoring the other html. I looked at data uri, but the IE8 size limit rules that out.
So now I am kind of stuck. My searches keep coming up with using a src attribute that loads another page that contains the image. But I need the image itself to actually show on the page. (Note: I say image, meaning at least one image but as many as eight on a page).
Any help would be greatly appreciated.
Well, you can do a few things. You can either make a page that will render the image
<img src="image.php?id=123" />
That image.php page would have this:
$sql = "SELECT image FROM images WHERE image_id = " . (int) $_GET['id'];
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
if (!$row) {
header('Status: 404 Not Found');
} else {
$img = $row['IMAGE']->load();
header("Content-type: image/jpeg");
print $img;
}
Or, you could base64 encode it into the src (note, not all browsers handle this well):
<img src="data:image/jpeg;base64,<?php echo base64_encode($img); ?>" />
But I need to [efficiently] get that image as the src attribute of the img tag
As Byron already says, the accepted and right way is to output the blob in an independent image resource, and to embed that using an img tag. It's the only good way. You can use data: URIs but they
fatten your HTML code
don't work in IE < 8 and are limited to 32 KB in IE 8,
expand the data volume by 33%, and
take away the brower's possibility to cache the image resource.
Almost never a good option.
The normal way to do this is with a <img src=/path/to/script?id=32> field. It will show up on the page not as a link. What is the problem with this? Do you want to embed the image data into HTML?
To make it more efficient, you can implement some type of caching ie, write the image data to a file and do a header(location...) if you find it instead of querying the db again. Also the browser caching headers should be set so the browser doesn't download the image if it has it cached locally.
You may try this :
$img = $row['IMAGE']->load();
print('<img src="data:image/png;base64,'.base64_encode($img).'" />');
<?php
if(isset($_POST['']))//get the id
$roll_no=$_POST[''];
$conn = oci_connect("", "", "");//DB connection
$query = 'SELECT image FROM TABLE where id=:id';
$stmt = oci_parse ($conn, $query);
oci_bind_by_name($stmt, ':id', $id);
oci_execute($stmt);
$arr = oci_fetch_array($stmt, OCI_ASSOC);
$result = $arr['image']->load();
header("Content-type: image/JPEG");
echo $result;
oci_close($conn);
?>

Categories