How to add image tagging the facebook way !
Updated post here
Today I want to show you how to make a image tagging function on your website.
It works about the same way than facebook does (or a least the way it worked some times ago because I deleted my facebook account)
Basicly you take an image and you “tag” people or stuff in it by marking what you want to tag with a rectangle.
This example is just a proof of concept and will give you a good idea on how to make it better for your website.
This script requires jquery and jquery-ui with draggable and resizable function(it’s included in the source).
note : I didnt have time to test it on IE so let me know if it works for you…
Here is the Demo and the Source.
Ok so first let’s explain the basics of this demo.
The script has two modes
- The edit mode where you can add tags to a picture (there is no delete function but there should be one).
- The view mode where you can view the tag on the picture.
I also use a simple database to store tags and pictures.
pictures table
CREATE TABLE IF NOT EXISTS `pictures` ( `id` int(11) NOT NULL auto_increment, `title` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM;
We will supose that every pictures are jpgs and that there name is [id].jpg but you can change that of course
tag tables
CREATE TABLE IF NOT EXISTS `tags` ( `id` int(11) NOT NULL auto_increment, `pictureid` int(11) NOT NULL, `top` int(11) NOT NULL, `left` int(11) NOT NULL, `width` int(11) NOT NULL, `height` int(11) NOT NULL, `description` varchar(50) NOT NULL, PRIMARY KEY (`id`), KEY `pictureid` (`pictureid`) ) ENGINE=MyISAM;
now let’s see what will need
- A div where the picture will be displayed and the draggable “tagger” div will be stuck.
- The actual picture we want to tagg or display
- the tagger div, it will be 100×100 but will be resizable and draggable at will.
- A form to add the tag
- A info div per tag
Here is a simplified view of our html
<div id=taggingArea> <img src="./$pic.jpg" /> <div id=drag> </div> </div> <div id=formArea> <form> </form> </div>
and the CSS
#taggingArea{
position:relative;
width:auto;
float:left;
}
#formArea{
float:left;
}
#drag{
position:absolute;
top:0px;
width:100px;
height:100px;
border:5px solid black;
background:url('blank.gif');
}
Let’s make our form now so we know what to store in the db
To be able to store all the info we need 5 variables.
- The width
- The height
- The “top” position
- The “left” position
- The description to be added
The user will only have to input the description field of course.
<form method=post> <input type=hidden name=width id=width> <input type=hidden name=height id=height> <input type=hidden name=top id=top> <input type=hidden name=left id=left> Description : <input type=text name=description> <input type=submit value=save> </form>
and now the JS
function updateForm(){
$("#width").val($("#drag").attr("offsetWidth"));
$("#height").val($("#drag").attr("offsetHeight"));
$("#top").val($("#drag").attr("offsetTop"));
$("#left").val($("#drag").attr("offsetLeft"));
}
$(document).ready(function(){
updateForm();
$("#drag").resizable({
stop: function() {
updateForm();
}
});
$("#drag").draggable({
containment: 'parent',
stop: function() {
updateForm();
}
});
});
This little code makes the “drag” div draggable and resizable and call up the function updateForm() everytime a drag or resize action is stopped.
The updateForm as for only purpose to update the hidden field of the form we created earlier.
once you have those values you can store it on your Db using a simple POST form handling ( if you don’t know how you can find an example in the sourcecode )
At this point you should be able to do all the tagging you want but now we need a way to display it on the image.
This can be done with adding a Div with the right style for each tag on the image.
Here is some example PHP
<div id="taggingArea">
<img src="<?php echo $pic;?>.jpg" />
<?php
$getTags = mysql_query("select * from tags where pictureid = $pic");
if(mysql_num_rows($getTags)>0){
while($resTags = mysql_fetch_array($getTags)){
?>
<div class=tag style="position:absolute;width:<?php echo $resTags['width'];?>px;height:<?php echo $resTags['height'];?>px;top:<?php echo $resTags['top'];?>;left:<?php echo $resTags['left'];?>;">
<?php echo $resTags['description'];?>
</div>
<?php
}
} ?>
</div>
To tweak things up a bit you can add a simple hover effect that will add a border on the tag.
.tagOn{
border:1px solid black;
}
$(".tag").hover(
function () {
$(this).addClass("tagOn");
},
function () {
$(this).removeClass("tagOn");
}
);
Here is a complete example of a full php file to edit and view.
<?php
mysql_connect("localhost","root","**");
mysql_select_db("imageTagging");
if(isset($_GET[del])){
mysql_query("delete from tags where id = ".addslashes($_GET[del]));
}
if(!isset($_GET[pic])){
$pic = 1;
} else {
$pic = addslashes($_GET[pic]);
}
if($_POST){
if($_POST[description]!=""){
foreach($_POST as $id => $val){
$$id = addslashes($val);
}
mysql_query("
insert into tags (pictureid,top,`left`,width,height,description)
values ($pic,$top,$left,$width,$height,'$description')") or die(mysql_error());
header("location:demo.php");
}
}
?>
<html>
<head>
<script src="./js/jquery.js" language="JavaScript" type="text/javascript"></script>
<script src="./js/jquery-ui.js" language="JavaScript" type="text/javascript"></script>
<link type="text/css" href="./css/jquery-ui.css" rel="stylesheet" />
<script>
function updateForm(){
$("#width").val($("#drag").attr("offsetWidth"));
$("#height").val($("#drag").attr("offsetHeight"));
$("#top").val($("#drag").attr("offsetTop"));
$("#left").val($("#drag").attr("offsetLeft"));
}
$(document).ready(function(){
updateForm();
$("#drag").resizable({
stop: function() {
updateForm();
}
});
$("#drag").draggable({
containment: 'parent',
stop: function() {
updateForm();
}
});
$(".tag").hover(
function () {
$(this).addClass("tagOn");
},
function () {
$(this).removeClass("tagOn");
}
);
});
</script>
<style>
.tagOn{
border:1px solid black;
}
#taggingArea{
position:relative;
width:auto;
float:left;
}
#formArea{
width:50%;
float:left;
}
#drag{
position:absolute;
top:0px;
width:100px;
height:100px;
border:2px solid black;
background:url('blank.gif');
}
</style>
</head>
<body>
<div id="taggingArea">
<img src="<?php echo $pic;?>.jpg" />
<?php if($_GET[mode]=="edit"){
?><div id="drag" class="ui-widget-content"></div><?
} else {
$getTags = mysql_query("select * from tags where pictureid = $pic");
if(mysql_num_rows($getTags)>0){
while($resTags = mysql_fetch_array($getTags)){
?>
<div class=tag style="position:absolute;width:<?php echo $resTags['width'];?>px;height:<?php echo $resTags['height'];?>px;top:<?php echo $resTags['top'];?>;left:<?php echo $resTags['left'];?>;">
<?php echo $resTags['description'];?>
</div>
<?php
}
}
} ?>
</div>
<?php if($_GET[mode]=="edit"){ ?>
<div id="formArea">
<form method=post>
<input type=hidden name=pic value="<?php echo $pic;?>">
<input type=hidden name=width id=width>
<input type=hidden name=height id=height>
<input type=hidden name=top id=top>
<input type=hidden name=left id=left>
Description : <input type=text name=description>
<input type=submit value=save>
</form>
<?php
$getTags = mysql_query("select * from tags where pictureid = $pic");
if(mysql_num_rows($getTags)>0){
while($resTags = mysql_fetch_array($getTags)){
echo "Tag #$resTags[id] $resTags[description] <a href=\"demo.php?del=$resTags[id]\">Delete</a><br />";
}
}
?>
<a href="demo.php">Go to view mode</a>
</div>
<?php } else { ?>
<div id="formArea">
<a href="demo.php?mode=edit">Go to edit mode</a>
</div>
<?php } ?>
</body>
</html>
This is a pretty long tutorial for me and I’m not sure I was clear enough so let me know if you need any additional info !

Good Script! Keep continue to share such a nice info.
Very nice.
Its really super nice script.can you use write a ajax demo.thanks
your source include one db(ajax.php).but i think post img’s src ,how can i do ?
when i use your demo,but when view ,show some errors on the page: 0){ while($resTags = mysql_fetch_array($getTags)){ ?>
please help us.thanks
This is great post. it will help lot. thanks for the post. i hope to see more examples .
I was also looking for the same.
I just have found smart tagger javascript library at http://www.thesmarttagger.com.
This allows to have similar to facebook image tagging feature
Thanks…I have purchased the Smart tagger. Thanks for sharing the info. It is simply great. My client is very happy. It has all the same feature like facebook image tagging. Also, it is very easy to integrate.
this is exactly what i was looking for …thank you so much for sharing
I was looking for such type of informative news and i am thankful to your for sharing that. Keep Posting and sharing with us.
Hi
Have tried this tutorial and the updated one and I can’t get either of them to work,
take a look at http://79.170.44.152/trade-bidz.co.uk/tagging.php or http://79.170.44.152/trade-bidz.co.uk/demo.php
I am unable to tag the photos when clicked.
What am I doing wrong?
can you please provide the link to refer?
Well to do this in Ajax would be pretty simple, you’ll just have to catch the submit button, then add a div with the proper attributes to the taggingArea (something like $(“#taggingArea”).append(…) and just send the coordinates to a ajax page to save it to your db.
For the friend selection it would be a bit harder to customize but It’s not very complicated
Hi, how difficult would it be to change the demo.php to use ajax, so everything is done on one page? So if you want to add a tag you click a button and the tag box appears without loading the dit div page if you see what I mean.
Also what steps would I need to know to have the tags selectable from a database (ie, select friend like facebook?) I am using php and mysql
Hello its works fine, saving the coordinates in database using appropriate information, but there is a problem with view mode of image, its not showing anything except image, not blocks which are already tagged,
i mean my image is without tags in view mode.
i want exact like
http://djpate.com/portfolio/imageTagging/demo.php
Help will be appreciate.
Thanks
Yogesh
Maybe you have a link I can look at ?
This is great, good work!
Howdy -
Nevermind the last post. The issue had to do with permission on the linux box. It did not like the css file being writable by the group.
Nice bit of scripting. I have adapted it to my needs and it works great. The only thing that I cannot get to function is the re-sizing the select. Even using the generic demo.php file I cannot get the marque to resize.
Any ideas? Works nicely for me on your demo site, so I think the issue is with my server or setup, not my browser.
hi! i find this code very useful but once i execute the code, it shows me an error which says
Parse error: parse error in C:\wamp\www\sample codes\imagetagging\demo.php on line 103
hope you could help me because i really need this code
thanks!
Actually i have this traced to
without that line it works, once i include it, it breaks, unfortunately for me I have to have it
My tags are showing up under the image rather than on top of them, the div style=”position:absolute; measurements are fine but they all showing up on top of each other even though the top left figures are different for each div
Thanks
There is an error in demo.php at line no. 92 , php open tag is only <? instead of <?php which is giving error on my server
Parse error: syntax error, unexpected '}' in demo.php on line 103
To remove this error use, <?php
Hey.. thanks a lot.. it helped me.. I am very new to jQuery and jQuery-ui..
But i am getting problem while running the code..
1.I can see only image and the box for tagging.. it is not draggable or resizable.. DO i need any support to run jquery and jqueryui?.. I am using wamp server to run the code..
2.On running the code, it shows me notice of undefined symbol for each line where the $_GET[mode] is used.. What does that mean?..do i need to make any other file?..
probably you are trying to select a database that does not exist
try to change this line
mysql_select_db(“imageTagging”);
to
mysql_select_db(“imageTagging”) or die(mysql_error());
to see what’s going on…
No database selected
that problem i have
Well I can’t help you with that because I don’t use ASP nor MSSQL.
But basicly the “hard part” of an image tagging script is the Javascript.
So try to strip down the Js from here and do your magic in ASP.
Everything around it is just some querys…
exactly like in facebook so you can type user name and list redused if there is a match if no user in the list that it should be posibility to enter email to send him notification. I forget to mention I need it in ASP.net/MSSQL
Basicly you want to load up a friends list so that you can just select a friend right away ?
actually I’m looking for facebook script with friends and user managment like this example http://taghim.com/taghim/v251users/
@Anony
Why don’t you ask for help ? If your willing to pay 200$ for a script that will do the same thing as mine go ahead…
Anyway I can help you if you have questions…
I try to implement it but I have so many problems to make it work as I need, I cant modify any function.
Somebody use TagHim this one http://taghim.com/taghim-demo/ ? any feedback?
@Sam
Sure, you can leave the website adresse where it’s not working here or you can send it to my email djpate[at]gmail[dot]com.
I’ll try to look into it to see what’s going wrong.
Its really nice script.. It worked for me at one place fine… but I am not able to get the co-ordinates properly on other sites. Can i get help from you?
Содержание блога хорошо продуманное, много интересного для себя прочитал.