Click here to Skip to main content
Click here to Skip to main content

Facebook Style Photo Tag

, 20 Jun 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
Facebook Style Photo Tag

Introduction

You know how in Facebook, you can Tag images like this:

fbTag.jpg

How can this be done in .NET ?

BreakDown

We'll have to divide this feature into a number of components:

  1. Select an area
  2. A list of friends is shown
  3. After selecting a friend, a label with friends name is added
  4. Friend name is removed from list (step 2)
  5. Image is now marked with the friends name where you selected
  6. On hovering the label with friend name, area from step(1) is selected

For steps (1) and (6), we will use Michal Wojciechowski's imgAreaSelect.

We'll get into that shortly, first let's examine the database.

ERD

ERD.jpg

vTags.jpg

tPhoto 

Nothing special here, holds the photo name, id and path.

tFriend

we need a boolean to tell us whether the friend has been tagged already or not, so he won't be shown again in the list (step number 2).

tTag

Holds the data about areas position in the photo, and Id of tagged person.

In real life the tables are more complex, where a friend can be tagged in more than one photo and a photo can have more than one friend tagged, this is simplified for the sake of demonstration.

vTag
The view displaying the tagged friends, the special field here is Coords, which is areas' positions(from tTag,x1,y1,x2,y2) concatenated together ,we'll need that later 

How to Use the Code

This is the JavaScript function imgAreaSelect(), notice it's bound to our asp:Image control, Image1, it magically frames the area we selected based on image name.

our image control name in run-time is MainContent_Image1 , that's the one we'll use. 

$(function () {
            $('#MainContent_Image1').imgAreaSelect({ aspectRatio: '1:1', handles: true,
                fadeSpeed: 200, onSelectChange: Select, onSelectEnd: DisplayFriends
            });
        });        

We have 4 hidden fields in the page, we need those to store the positions of area selected.

Now, this function fires the onSelectEnd event, which calls the function Select(), it simply populates the hidden fields.

function Select(img, selection) {
if (!selection.width || !selection.height)
return;
document.getElementById('<%=x1.ClientID %>').value = selection.x1;
document.getElementById('<%=y1.ClientID %>').value = selection.y1;
document.getElementById('<%=x2.ClientID %>').value = selection.x2;
document.getElementById('<%=y2.ClientID %>').value = selection.y2;
}  

... and on the onSelectEnd event, we'll call our DisplayFriends() method.

dvFriends is a div containing a datalist populated with our untagged friends (initially hidden of course).

function DisplayFriends(img, selection) {
if (!selection.width || !selection.height || 
	document.getElementById('<%=HFShowFriends.ClientID %>').value == "0")
return;
document.getElementById('<%=dvFriends.ClientID %>').style.display = "block";
}    

When user selects a friend, it will fire the function SelectEnd() which ends the selection process.

function SelectEnd() {
$('#MainContent_Image1').imgAreaSelect({ hide: true });
}  

Nice, now we need to actually tag the image (where you hover on photo and see a tool tip displaying the friend's name).

To do this, we'll use an HTML map.

AddNewArea() function takes the newly created tTag object and adds a new area to the map.

private void AddNewArea(tTag t)
{
    HtmlGenericControl gcArea = new HtmlGenericControl("area");
    gcArea.Attributes.Add("shape", "rect");
    gcArea.Attributes.Add("href", "#");
    string strFriendName = Friends.GetFriendName(t.nFriendId);
    gcArea.Attributes.Add("id", "a" + t.nFriendId.ToString());
    gcArea.Attributes.Add("title", strFriendName);
    gcArea.Attributes.Add("alt", strFriendName);
    gcArea.Attributes.Add("coords", GenerateCoordiantes(t));
    mapPhoto.Controls.Add(gcArea);
}

(Note: In case of using Mozilla Firefox 5.0 or Safari 5.0.3, the tagging effect does not work until after refreshing the whole page.)

Very good, now we need the area to be selected again on hovering the links, which are actually ItemTemplates inside a datalist. 

<asp:DataList ID="dlTaggedFriends" runat="server" RepeatDirection="Horizontal" 
DataSourceID="sdsTags"
ViewStateMode="Disabled">
<ItemTemplate>
<asp:LinkButton ID="lbName" runat="server" onmouseout="SelectEnd()" 
onmouseover='<%#Eval("Coords","preview(\"{0}\");")%>'
Text='<%# Eval("sName") %>'></asp:LinkButton>
(<asp:LinkButton ID="lbRemoveTag" runat="server" 
CommandArgument='<%# Eval("nFriendId") %>'
OnCommand="lbRemoveTag_Command1">remove</asp:LinkButton>)
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</ItemTemplate>
</asp:DataList>

The DatasourceId of datalist dlTaggedFriends , is SqlDataSource sdsTags , which is bound to the view vTag  

vTagsData.jpg 

That's why we concatenated the positions, to pass them as one parameter to the javascript function  preview() on  onmouseover event, where they'll be spitted again . 

function preview(Coords) {
            var arrResult = Coords.split(",");
            var nx1 = arrResult[0];
            var ny1 = arrResult[1];
            var nx2 = arrResult[2];
            var ny2 = arrResult[3];
            var ias = $('#MainContent_Image1').imgAreaSelect({ instance: true });
            ias.setSelection(nx1, ny1, nx2, ny2, true);
            ias.setOptions({ show: true });
            ias.update();
} 

Output

Example.jpg

Drawbacks

  • The tagging effect does not work until after refreshing the whole page when using Mozilla Firefox 5.0 or Safari 5.0.3.

Future Work

  • Free hand selection (instead of rectangle)

Conclusion

  • Tested on Internet Explorer 8, Google Chrome 10.0.6, Mozilla Firefox 5.0 and Safari 5.0.3
  • Feel free to post any questions, modifications, comments

History

  • 20th March, 2011: Initial post 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Omar Gameel Salem
Software Developer
Australia Australia
Enthusiastic programmer/researcher, passionate to learn new technologies, interested in problem solving, data structures, algorithms, AI, machine learning and nlp.
 
Amateur guitarist/ keyboardist, squash player.
 
If you have a question\suggestion about one of my articles, or you want an algorithm implemented in C#, feel free to contact me.
Follow on   LinkedIn

Comments and Discussions

 
QuestionGood!! PinmemberPrimillo21-Feb-13 21:51 
Very helpfull
Questionshowing error [modified] Pinmembernephy k7-Sep-12 7:16 
QuestionHow to do Friends.TagFriend(nFriendId, true); method? Pinmembersudhakar mr23-Apr-12 23:14 
GeneralMy vote of 3 PinmemberNileshKRathod5-Mar-12 19:27 
GeneralRe: My vote of 3 PinmemberOmar Gamil9-Mar-12 2:46 
GeneralRe: My vote of 3 Pinmembernephy k7-Sep-12 7:09 
QuestionNice one PinmemberAhmed_Said23-Sep-11 13:32 
GeneralMy vote of 4 PinmemberSChristmas8-Jul-11 8:06 
GeneralMy vote of 4 Pinmemberkoolprasad200321-Jun-11 4:37 
GeneralNot working with Chrome and Pinmemberbayonian16-May-11 5:37 
GeneralRe: Not working with Chrome and Pinmembereasyese26-May-12 16:36 
QuestionOld database notation? PinmemberBerggreenDK20-Mar-11 8:41 
AnswerRe: Old database notation? PinmemberOmar Gamil20-Mar-11 9:15 
GeneralRe: Old database notation? PinmemberBerggreenDK21-Mar-11 3:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 21 Jun 2011
Article Copyright 2011 by Omar Gameel Salem
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid