Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

List with Images for Composition

0.00/5 (No votes)
15 Dec 2013 3  
This example shows how you can get a set of images Thumb together into one and display them using CSS sprites technique.

Introduction

This example shows how you can get a set of images Thumb together into one and display them using CSS sprites technique. Sorry for my poor English. The code is simple and good for images Thumb is truly fast.

Using the Code

//
// Page start for display images
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class start : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DB d = new DB();
int indexPag = 0;
if (Request.QueryString["id"] != null)
indexPag = int.Parse(Request.QueryString["id"]);
table.Text = d.getTable(indexPag);
}
}   
// 
//
// Html the page to present the list and images 
//  
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<style type="text/css">
  .load-gif {
  width: 36px;
  height: 36px;
  background-image: url('img/loading.gif');
  background-repeat: no-repeat;
}
</style>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" 
type="text/javascript"></script>
<script>
/* Display gif loading */
var source = "photo.ashx";
var image = new Image();
image.src = source;

$(document).ready(function () {
$(".load").addClass('load-gif');// show gif
image.onload = function () {
$(".photo").css({
"width": "50px",
"height": "50px",
"background-image": "url('" + image.src + "')",
"background-repeat": "no-repeat"
});
$(".load").hide(); // hidden gif
}
});
</script>
</head>
<body>
<form id="form2" runat="server">
<asp:Literal ID="table" runat="server"></asp:Literal>
</form>
</body>
</html> 
 //
// The class return table html string and object setting photos in session
//  
public class DB
{
public DB()
{
}
public string getTable(int indexPage)
{
// Build table
string formatTable = "<table width='100%' border='1'cellpadding='0' 
cellspacing='1' bordercolor='#000000' style='border-collapse: collapse;'>" +
"<tr>" +
"<td>ProductPhotoID</td>" +
"<td>ProductNumber</td>" +
"<td>Name</td>" +
"<td>SafetyStockLevel</td>" +
"<td>ModifiedDate</td>" +
"<td>ThumbnailPhotoFileName</td>" +
"<td>ThumbNailPhoto</td>" +
"</tr>" +
"{0}" +
"</table>";
int counterRows = 0;
SqlCommand cmd = null;
string formatCss = "background-position: -0px -{0}px;";
string formatDiv = "<div class='photo' id='img{0}' 
style='{1}'><div class='load'></div></div>";
string formatTr = "<tr><td>{0}</td><td>{1}</td><td>
{2}</td><td>{3}</td><td>{4}</td><td>
{5}</td><td>{6}</td></tr>";

using (SqlConnection cn = new SqlConnection
(WebConfigurationManager.ConnectionStrings["conection"].ConnectionString))
{
cmd = new SqlCommand("getProducts", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("id", indexPage); // actual: 
//quitamos uno para que empiece en cero 0 | antes: (anchoPagina * pagina)
cn.Open();

SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

if (dr.Read())
counterRows = dr.GetInt32(0); // get counter rows

dr.NextResult();

int step = 0; // for the location of each image
int heightPhoto = 50; // size Thumbnail Photo
int widthPhoto = 50;
string css = string.Empty; // css for div image
string div = string.Empty; // div image
string tr = string.Empty; // tr for div
string table = string.Empty;// table html
StringBuilder sbTr = new StringBuilder();
List<byte[]> photos = new List<byte[]>(); // photos array

while (dr.Read())
{
// create
css = string.Format(formatCss, step * heightPhoto);
div = string.Format(formatDiv, step, css);
tr = string.Format(formatTr, dr["ProductPhotoID"],
dr["ProductNumber"],
dr["Name"],
dr["SafetyStockLevel"],
DateTime.Parse(dr["ModifiedDate"].ToString()).ToString("dd/MM/yyyy"),
dr["ThumbnailPhotoFileName"],
div);
sbTr.Append(tr);
photos.Add((byte[])dr["ThumbNailPhoto"]);
step++;
}
dr.Close();
cn.Close();
table = string.Format(formatTable, sbTr.ToString());

// save photos retrieve database in session
SettingsPhotos en = new SettingsPhotos();
en.height = heightPhoto;
en.width = widthPhoto;
en.count = counterRows;
en.photos = photos;
HttpContext.Current.Session["send-photos"] = en;

return table;
}
} 
 //
// The class save information the images and array byte image list
//  
public class SettingsPhotos
{
public SettingsPhotos()
{
}
public int count { get; set; }
public int width { get; set; }
public int height { get; set; }
public List<byte[]> photos { get; set; }
} 
 //
// The page handler to create and deliver the composition  
// 
<%@ WebHandler Language="C#" Class="photo" %>
using System;
using System.Web;
using System.IO;
using System.Collections.Generic;
using System.Drawing;

public class photo : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
/* Retrieve images */
public void ProcessRequest (HttpContext context) {
HttpResponse r = context.Response;
// System.Threading.Thread.Sleep(2000); // if you want to delay the process to see the loading gif
if (context.Session != null && context.Session["send-photos"] != null)
{
SettingsPhotos set = (SettingsPhotos)context.Session["send-photos"];
// context.Session["send-photos"] = null;
MemoryStream msUnion = mergeImages
(set, System.Drawing.Imaging.ImageFormat.Jpeg); // PNG JPEG GIF etc

if ((msUnion == null))
return;

using (msUnion)
{
r.ContentType = "image/jpeg";
msUnion.WriteTo(r.OutputStream);
}
}
}

public bool IsReusable {
get {
return false;
}
}

/* Create compoticion the images with array list byte[]
----------------------------------------------------
The pictures of vertically stacked, 
but can implementase both vertical and horizontal
*/
private MemoryStream mergeImages
	(SettingsPhotos set, System.Drawing.Imaging.ImageFormat formato)
{
int height = set.height * set.count; // calculate the number 
		// of high end with photos, imagens stacked vertically
System.Drawing.Image img = null; // image
Bitmap merge = new Bitmap(set.width, height); // composition the images
Graphics gr = Graphics.FromImage(merge); // draw image in merge bitmap
gr.Clear(Color.White); // background color for PNG convert to JPEG, white for transparent

int newHeight = 0;
foreach (byte[] foto in set.photos)
{
   img = System.Drawing.Image.FromStream(new MemoryStream(foto));
   gr.DrawImage(img, new Rectangle(0, newHeight, 
   set.width, set.height), 0, 0, img.Width, img.Height,    GraphicsUnit.Pixel);
   newHeight += set.height;
}
  MemoryStream ms = new MemoryStream();
  merge.Save(ms, formato);
  img.Dispose();
  merge.Dispose();
  gr.Dispose();
  return ms;
}
}  

The method mergeImages generates the next composition:

 i.cubeupload.com/mYzuRb.jpg 

(Copy paste in browser)

Why ask for a picture at a time if you can bring all.

Recall that if we want to paginate or filter list. The table must send the call to the handler for one query string is updated just the composition: 

Example:

"photo.ashx?id=" + numberPag; 

I hope this code will be helpful to you.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here