Building a Google Plus inspired image gallery

I recently built a Google Plus inspired image Gallery as an extension for the Alfresco ECM product which won first place in Alfresco developer challenge. Now I’d like to share my insights, explain how I built it and give you a starting point to build your own galleries based on the great G+ gallery design.

Screenshot of Alfresco Gallery Plus extension

The G+ image grid disected

The main focus of this article will be on the image grid. Let’s start with a look on the features of the original G+ image grid to find out what it takes to recreate it. To illustrate the features I am using Thomas Hawk’s G+ gallery which has some amazing images (check it out).

  1. Justifed alignment: All images are displayed in rows and aligned to left and right borders. 
  2. Even spacing: All Images are evenly spaced (6px spacing, i.e. 3px margin around each image).  
  3. Natural order: Images don’t have a special ordering to better fit in the grid. I first thought the perfect alignment was solved with some sort of bin packing algorithm, but that is not the case und is not needed. Images are usually sorted by date from latest to oldest.
  4. Cropped thumbnails: To achieve the justified layout some portions of the images are hidden (cropped). When I first checked out the G+ gallery I saw most of the cropping done with HTML but now it looks like Google generates thumbnails in any arbitrary resolution or cropping on the server-side.
      
    Both images have a similar URL which only differs in a part which specifies the resolution. The left image contains the path /w300-h150-n-k/ whereas the right image contains the path /w150-h150-n-k/ and therefore is cropped differently on the server side.
  5. Big title image: There is a “title” image or (album cover image) which spans two rows.  
  6. Comment badges: The number of comments is displayed on each image thumbnail. 
  7. Dynamic resolution: The size of the images depends on the width of the browser window. G+ uses small images for smaller browser windows and larger images for wider browser windows, i.e. the image resolution adapts to the screen size. This is espacially useful for mobile devices which have lower resultion than desktop browsers.  
  8. Window resize: The image sizes change and the grid images are re-aligned dynamically when the browser window is resized.  
  9. Dynamic row height: This is a really subtle feature: Depending on the dimensions of the images in one row (e.g. if a lot of images in portrait format) some rows are rendered bigger in height than others. This helps portrait shots not to become too small.
  10. Popup Preview: When you hover over an image an animated popup appears and displays the image in a larger rendition.
  11. Infinite scroll: When you scroll to the bottom of the page more images are loaded automatically.

As far I have seen G+ servers generate different sizes of thumbnails that are used for the window specific thumbnail size, dynamic row height and the preview popup. At times your browser will load 10-20 differently sized thumbnails of an image.

I bet the feature list above is not even complete but it shows the design and engineering effort that went into this seemingly simple gallery grid.

What if you don’t have Google’s infrastructure and manpower?

For my one man competition contribution I couldn’t possibly implement all those features. I axed the double-row-spanning title image, different thumbnail sizes and the preview popup:

  • Only one thumbnail size (120 pixel height, width depending on image aspect ratio)
  • No server side cropping, only a single static thumbnail for each image. 

Still I came pretty close to the original with all the other features.

How does the cropping in the Browser work?

To better understand how the G+ image grid worked I studied the HTML source, which basically looks like this:

The main insight I took from this is they way the images can be cropped: using a DIV with overflow:hidden and changing margin-left of the image to define the x-offset.

How to align the images?

Once I started experimenting I realized that the image alignment is not that hard to do. Let’s say we have three images and are using a fixed thumbnail height of 120 pixel.

image 1: 200x120
image 2: 180x120
image 3: 120x120

Let’s also assume we want to fit these images in a row with a given width of 460 pixels.

I started to build rows of images by adding image by image until the window width is met or surpassed.

1 image: 200 OK (<460)
2 images: 200 + 180 = 380 OK (<460)
3 images: 380 + 120 = 500 surpassed (break >460, 40 pixels too long)

So putting all three images in a row would make it 40 pixel too long. The only thing that needs to be done now is to crop all the images by overall 40 pixels to perfectly align them with the window width.

My naive approach was to simply devide the excess pixels, so 40 pixel / 3 images = 13 pixels/image You have to be careful with the integer division though. To perfectly distribute the 40 pixels you need to crop one additional pixel from one of the images:

cropped image 1: 200 - 14 = 186x120
cropped image 2: 180 - 13 = 167x120
cropped image 3: 120 - 13 = 107x120

If you sum up the witdh now you get exactly 460 pixel. Combining these values with the cropping method from the previous section we get the following HTML code for the three images.

<div style="overflow:hidden; width:186px; height:120px;">
  <img src="image1.jpg" style="width:200px; height:120px";
      margin-left:-7px"/>
</div>
<div style="overflow:hidden; width:167px; height:120px;">
  <img src="image2.jpg" style="width:180px; height:120px";
      margin-left:-6px"/>
</div>
<div style="overflow:hidden; width:107px; height:120px;">
  <img src="image3.jpg" style="width:120px; height:120px";
      margin-left:-6px"/>
</div>

As you can see the negative margin-left is used to center the cropped area horizontally. On thing I left out here is the spacing between images. We have 6 pixels of spacing between each image that have to be added in the inital sum.

This naive approch worked pretty well even with only a single thumbnail size (120 pixels height). In a later iteration I changed the distribution of the crop-pixels though, because when equally distributing the excess pixels, portrait images tend to get too small in width. That’s why I based the crop amount on the image width, with the result that wider images are cropped more than narrow ones.

The server side

As you see above the image layout algorithm needs the widths of the individual images to do it’s mojo. In my Alfresco extension I leveraged the metadata extraction capabilties to get to the thumbnail resolution. The resulting JSON data that is finally generated on the server side is a simple array with all the image data (here is a single image as an example):

{ "thumbs" : [
  {
    "thumbUrl" : "api/node/workspace/SpacesStore/c2f5e06f-ee15-4b0f-9e6c-1f734b4db45f/content/thumbnails/galpThumb120",
    "title" : "2010-05-02, 2 images, IMG_2173 - IMG_2174 - 5096x2320 - SCUL-Smartblend.jpg",
    "twidth" : 300,
    "theight" : 120,
    "description" : "",
    "author" : "Administrator",
    "nodeRef" : "workspace://SpacesStore/c2f5e06f-ee15-4b0f-9e6c-1f734b4db45f",
    "name" : "2010-05-02, 2 images, IMG_2173 - IMG_2174 - 5096x2320 - SCUL-Smartblend.jpg"
  }
]}

The most important information here are the thumbnail dimensions and the thumbUrl that are used for the gallery grid. If you are interested in the details of the server side code in my Gallery+ extension you can have a look in the webscript.

Standalone JQuery demo version

To demonstrate the grid rendering independently of the full the Alfresco extension I moved the grid generation code to a standalone website with the Javascript logic based on jQuery (the original extension is based on YUI). You can see the example in action at the following URL: http://fmaul.de/gallery-grid-example/

If you try it out, make sure to resize your browser to see the dynamic resizing in action. This is not a full jQuery gallery component, sorry – it is just meant to demonstrate the rendering but you are welcome to further extend the code to a full blown jQuery gallery.

Note that the example gallery is not backed by a REST or thumbnail server, it uses this static JSON file as image source for the purpose of demonstration. The page is built using html5 boilerplate and therefore my complete implementation can be found in the scripts.js file.

 

92 thoughts on “Building a Google Plus inspired image gallery

  1. There are a variety of styles and types to cater to different needs.
    It’s all right — it can still be saved and made into cute luggage.
    If you’re hungry, then why not have something
    to eat at the airport.

  2. Spot on with this write-up, I actually feel this web site needs much
    more attention. I’ll probably be back again to read through more, thanks for the information!

  3. Otros, no obstante, lograrán continuar la dieta hasta descubrir, meses después, que no sólo
    no les ha funcionado sino además han ganado peso.

  4. Bei Fragen dazu konnte mir die zuständige Heilpraktikerin nicht viel weiter helfen, als mir den Tipp zu geben die
    Portionen zu verdoppeln, was aber auch nicht weiter half.

  5. Praised by users as offering lightning fast gameplay and easy to use, simplistic controls, it has remained a
    highly popular mod, six years after its initial release, with xfire.
    There are 4 different gametypes available to play in Medal
    of Honor multiplayer. Sniping frequently is the
    best way to do this, and chances are when you finally accomplish it,
    it’ll be luck.

  6. No dejes escapar a los mejores fotógrafos de boda en Sevilla y obtén un maravilloso documental con los grandes momentos
    de un día tan especial.

  7. En esta oportunidad hemos traído una colección de 10 portales para bajar libros gratis
    de todo tipo y género de forma legal, sin tener
    que infringir ninguna regla, y sobre todo, disponible en múltiples idiomas.

  8. Good post. I learn something totally new and challenging on sites I stumbleupon everyday.
    It will always be useful to read articles
    from other authors and use something from their web sites.

  9. Thanks a bunch for sharing this with all of us you really recognise
    what you’re speaking approximately! Bookmarked. Kindly also talk
    over wityh mmy ssite =). We may hhave a link trade agreement between us

  10. naturally like your website but you need to take
    a look at the spelling on several of your posts. A number of them are rife
    wuth spelling problejs and I in finding it very bothersome
    to tell the reality then again I’ll certainly come back again.

  11. Otro ejemplo: si confrontamos estas obras con la
    de fotógrafos reconocidos artísticamente como puede ser Bill
    Owens y su tan jaleada trilogía Suburbia – Working – Leisure,
    vemos que el lenguaje utilizado resulta copiado” del de los fotógrafos locales
    (profesionales amateurs).

  12. I think this is one oof the most important info for me.
    And i’m glad reading your article.But should remark on some general things, The site style is wonderful, the articles is really great : D.
    Goodd job, cheers

  13. Joyerías Y Obras De Arte
    Adquirir una póliza de vida , ciertamente, es un enorme compromiso, de por vida, pues la idea
    es que consiga acompañar a los beneficiarios el resto de sus
    vidas. Mas para componer nuestro seguro, hay que conocer cuáles son las garantías
    que las empresas de seguros suelen ofrecer.
    De esta forma, con toda la información tienes mejores armas
    para seleccionar el seguro con las coberturas que necesitas para tu hogar.

    Hay algunos seguros veterinarios que solo cubren los accidentes y no
    las enfermedades, suelen llamarse Seguro de Accidentes para mascotas.
    El seguro para hogar cubre daños que ocurren en tu vivienda de forma eventual,
    súbita y también imprevista. Sin lugar a dudas, el seguro para hogar automóvil conveniente constituye en todo sentido la mejor
    manera de que esté protegido.

    No obstante, si se incendia, solo recibiré indemnización con lo que verdaderamente vale, los cincuenta.000€, por ende he estado pagando el doble de prima
    para nada. Las garantías que ofrecen son muy similares a las de los seguros del turismo mas poseen ligeras diferencias debido a
    que no tienen los mismos riesgos un vehículo u otro.

    En Adaix queremos que los clientes del servicio obtén la mejor póliza para su casa, , por esta razón les ofrecemos la información más completa para que puedan decidir la opción que mejor
    se ajuste a sus circunstancias. La compleja situación que vivía el mundo del seguro de motocicletas en los
    noventa creó la coyuntura.

    Y si pensamos en un bonito gato siamés tampoco hay duda, mas si tenemos a un tigre de bengala,
    por muy apasionante que resulte, el seguro indudablemente
    no lo contemplaría en ningún caso. La mayor parte de los trabajadores de Eurolloyd somos aficionados al mundo del motor, y la posibilidad de picarnos” entre nosotros en un entorno seguro, da
    para pasar un muy buen rato.

    Es importante contratar los seguros que se ajusten a nuestras necesidades y para ello,
    debemos comprobar de forma continua nuestros contratos e intentar reducir el precio en aquello que no necesitamos,
    pero siempre y en todo momento buscando aquel que tenga una mejor relación calidad/precio; el costo por si solo nos dice poco en un contrato de seguros.
    Con este caso de ejemplo se quiere mostrar que hay que valorar lo que verdaderamente precisamos y lo que no
    y personalizar el seguro a nuestro gusto. En lo asistimos
    a encontrar el seguro adecuado para usted y su familia — ¡sin agobio y en sus
    manos!

    Además de esto, los trabajadores que se han ido incorporando a lo largo de todos estos años, estamos, de un modo o
    bien otro, relacionados con el mundo de la moto. En la página web oficial de
    Clínica Dental Adeslas Moratalaz en Adeslas Dental, puedes hallar toda la información sobre pólizas de seguro y coberturas, aparte
    de los costos detallados por tratamiento. Contrata tu seguro online con exactamente la misma seguridad y confianza que en una
    oficina. Desde ahí, el negocio ha ido medrando, siempre basado en el seguro de
    moto como núcleo duro.

  14. Una de las primordiales peculiaridades de nuestro estudio, y de nuestro trabajo es que usamos
    técnicas amplísimas y diferentes, adaptando cada trabajo, cada reportaje, a cada una de las parejas que se ponen delante de nuestro objetivo, puesto que no debemos olvidar que los novios son los auténticos protagonistas y
    lo que deseamos es que sus recuerdos sean únicos y también indelebles.

  15. This is the right site for anybody who would like to
    undferstand this topic. You know so mch its almost tough to argue with you
    (not that I actually will need to…HaHa). You dfinitely put a
    new spin on a subject which haas been witten about for decades.

    Wonderful stuff, just great!

  16. I’m really loving the theme/design of your site. Do you ever run into any browser compatibility issues?
    A few of my blog visitors have complained about my blog not operating
    correctly in Explorer but looks great in Opera. Do you have any advice
    to help fix this problem?

  17. When I originally left a comment I seem to have clihked
    the -Notify me when new comments are added- checkbox and now every time a comment is added I recieve Channel 4 emais with the same comment.
    Perhaps here is an easy method you can remove me from that service?
    Thanks a lot!

  18. An intriguing discussion is worth comment. I think that you ought to
    publish more about this subject, it may not be a taboo matter but usually folks don’t discuss such topics.

    To the next! Kind regards!!

  19. eah time i used to read smaller articles orr reviews that
    as ell clear their motive, aand that is also happening with this paragraph which I am reading now.

  20. Pretty portion of content. I just stumbled upon your blog and in accession captal too say that I acquire in act enjoyed account your weblog posts.
    Anny way I will be subscribing to your augment and even I
    success you get right of entry to consistently fast.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>