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 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>
var source = "photo.ashx";
var image = new Image();
image.src = source;
$(document).ready(function () {
$(".load").addClass('load-gif');image.onload = function () {
$(".photo").css({
"width": "50px",
"height": "50px",
"background-image": "url('" + image.src + "')",
"background-repeat": "no-repeat"
});
$(".load").hide(); }
});
</script>
</head>
<body>
<form id="form2" runat="server">
<asp:Literal ID="table" runat="server"></asp:Literal>
</form>
</body>
</html>
public class DB
{
public DB()
{
}
public string getTable(int indexPage)
{
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); cn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.Read())
counterRows = dr.GetInt32(0);
dr.NextResult();
int step = 0; int heightPhoto = 50; int widthPhoto = 50;
string css = string.Empty; string div = string.Empty; string tr = string.Empty; string table = string.Empty;StringBuilder sbTr = new StringBuilder();
List<byte[]> photos = new List<byte[]>();
while (dr.Read())
{
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());
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; }
}
<%@ 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
{
public void ProcessRequest (HttpContext context) {
HttpResponse r = context.Response;
if (context.Session != null && context.Session["send-photos"] != null)
{
SettingsPhotos set = (SettingsPhotos)context.Session["send-photos"];
MemoryStream msUnion = mergeImages
(set, System.Drawing.Imaging.ImageFormat.Jpeg);
if ((msUnion == null))
return;
using (msUnion)
{
r.ContentType = "image/jpeg";
msUnion.WriteTo(r.OutputStream);
}
}
}
public bool IsReusable {
get {
return false;
}
}
private MemoryStream mergeImages
(SettingsPhotos set, System.Drawing.Imaging.ImageFormat formato)
{
int height = set.height * set.count; System.Drawing.Image img = null; Bitmap merge = new Bitmap(set.width, height); Graphics gr = Graphics.FromImage(merge); gr.Clear(Color.White);
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.