Advertisements

Archive

Posts Tagged ‘resize images in ASP.Net/C#’

How to crop image using ASP.Net/C# OR Cropping image in C# before upload

May 22, 2012 40 comments

DOWNLOAD SOURCE CODE FOR CROP IMAGE IN ASP.NET

Crop images before upload to the server in C#/ASP.Net

In our previous post we demonstrate how we can re size image using C# or Create thumbnail image using ASP.Net. Here we are demonstrating how we can crop images using ASP.Net application using Jquery and C#. In some applications we need to upload images and we need only some portion of the images to get clear picture on the photo. In this case we need to give an option to users to crop image before they are uploading the image.

Include Jquery file/CSS files to the application. 

First of all we need to include following jquery/CSS files to the application.

1.       jquery.min.js     –    You can download from here

2.       jquery.Jcrop.js   –    You can download from here

3.       jquery.Jcrop.css   –    You can download from here 

Simple steps to crop image using ASP.Net,C#,Jquery

In this application we are having a browse option for selecting an image. Once we selected a image it will display int the screen.

Crop image using ASP.net C#

Select an image to crop using ASP.Net C# Jquery

In the next step we will have the option to select an area to crop the image. Once we selected an area we can click crop button on the screen.

Crop image using ASP.Net C#

Select image area to crop

Then the selected area will be cropped and displayed in the screen.

Crop image using ASP.Net C#

Cropped area of the image

ASPX Page for crop images using Jquery 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CropImage.aspx.cs" 
Inherits="ExperimentLab.CropImage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
 <title>Crop Image</title>
 <link href="Styles/jquery.Jcrop.css" rel="stylesheet" type="text/css" />
 <script type="text/javascript" 
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
 <script type="text/javascript" src="Scripts/jquery.Jcrop.js"></script>
 <script type="text/javascript">
 jQuery(document).ready(function () {
 jQuery('#imgCrop').Jcrop({
 onSelect: storeCoords
 });
 });
function storeCoords(c) {
 jQuery('#X').val(c.x);
 jQuery('#Y').val(c.y);
 jQuery('#W').val(c.w);
 jQuery('#H').val(c.h);
 };
</script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <asp:Panel ID="pnlUpload" runat="server">
 <asp:FileUpload ID="Upload" runat="server" />
 <br />
 <asp:Button ID="btnUpload" runat="server" 
 OnClick="btnUpload_Click" Text="Upload" />
 <asp:Label ID="lblError" runat="server" Visible="false" />
 </asp:Panel>
 <asp:Panel ID="pnlCrop" runat="server" Visible="false">
 <asp:Image ID="imgCrop" runat="server" />
 <br />
 <asp:HiddenField ID="X" runat="server" />
 <asp:HiddenField ID="Y" runat="server" />
 <asp:HiddenField ID="W" runat="server" />
 <asp:HiddenField ID="H" runat="server" />
 <asp:Button ID="btnCrop" runat="server" Text="Crop" 
 OnClick="btnCrop_Click" />
 </asp:Panel>
 <asp:Panel ID="pnlCropped" runat="server" Visible="false">
 <asp:Image ID="imgCropped" runat="server" />
 </asp:Panel>
 </div>
 </form>
</body>
</html>

Code Behind of the ASPX page for Crop image using ASP.Net/C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using SD = System.Drawing;
using System.Drawing.Drawing2D;
namespace ExperimentLab
{
public partial class CropImage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
String path = HttpContext.Current.Request.PhysicalApplicationPath + "images\\";
protected void btnUpload_Click(object sender, EventArgs e)
{
Boolean FileOK = false;
Boolean FileSaved = false; 
if (Upload.HasFile)
{
Session["WorkingImage"] = Upload.FileName;
String FileExtension =
Path.GetExtension(Session["WorkingImage"].ToString()).ToLower();
String[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".gif" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (FileExtension == allowedExtensions[i])
{
 FileOK = true;
}
}
}
if (FileOK)
{
try
{
Upload.PostedFile.SaveAs(path + Session["WorkingImage"]);
FileSaved = true;
}
catch (Exception ex)
{
lblError.Text = "File could not be uploaded." + ex.Message.ToString();
lblError.Visible = true;
FileSaved = false;
}
}
else
{
lblError.Text = "Cannot accept files of this type.";
lblError.Visible = true;
}
if (FileSaved)
{
pnlUpload.Visible = false;
pnlCrop.Visible = true;
imgCrop.ImageUrl = "images/" + Session["WorkingImage"].ToString();
}
}
protected void btnCrop_Click(object sender, EventArgs e)
{
string ImageName = Session["WorkingImage"].ToString();
int w = Convert.ToInt32(W.Value);
int h = Convert.ToInt32(H.Value);
int x = Convert.ToInt32(X.Value);
int y = Convert.ToInt32(Y.Value);
byte[] CropImage = Crop(path + ImageName, w, h, x, y);
using (MemoryStream ms = new MemoryStream(CropImage, 0, CropImage.Length))
{
ms.Write(CropImage, 0, CropImage.Length);
using (SD.Image CroppedImage = SD.Image.FromStream(ms, true))
{
string SaveTo = path + "crop" + ImageName;
CroppedImage.Save(SaveTo, CroppedImage.RawFormat);
pnlCrop.Visible = false;
pnlCropped.Visible = true;
imgCropped.ImageUrl = "images/crop" + ImageName;
}
}
}
static byte[] Crop(string Img, int Width, int Height, int X, int Y)
{
try
{
using (SD.Image OriginalImage = SD.Image.FromFile(Img))
{
using (SD.Bitmap bmp = new SD.Bitmap(Width, Height))
{
 bmp.SetResolution(OriginalImage.HorizontalResolution, 
 OriginalImage.VerticalResolution);
 using (SD.Graphics Graphic = SD.Graphics.FromImage(bmp))
 {
 Graphic.SmoothingMode = SmoothingMode.AntiAlias;
 Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
 Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
 Graphic.DrawImage(OriginalImage, new SD.Rectangle(0, 0, Width, Height),
 X, Y, Width, Height, SD.GraphicsUnit.Pixel);
 MemoryStream ms = new MemoryStream();
 bmp.Save(ms, OriginalImage.RawFormat);
 return ms.GetBuffer();
 }
}
}
}
catch (Exception Ex)
{
throw (Ex);
}
}
}
}


DOWNLOAD SOURCE CODE FOR CROP IMAGE IN ASP.NET
Advertisements

How to create thumbnail image in ASP.Net/C# OR resize the image before upload in ASP.Net/C#

July 7, 2011 18 comments

How to reduce the size of image before uploaded to the server in ASP.Net/C#

In most of the ASP.Net application with uploaded image facility will face the performance issue while loading uploaded images to display for the user. We can limited the maximum size of the image that a user can upload but it may not be a good solution because a user has to facing very difficult situation for uploading a large image. He has to reduce the image from other tools and upload again.

The better approach to solve this issue, we are not going to giving any maximum size limit for uploading image. Instead we are internally reducing the size of the image that a user going to upload by checking whether it is exceeds affordable size.  Then there is no constraints are given to user so that he doesn’t care about the size and quality of the image.

Image Size 764 KB

Simple steps to reduce the size of image before upload in ASP.Net/C#

 Here we are going to demonstrate a very simple and best approach to reduce the size of the image before uploaded to the server. In some application we need to show thumbnail image with uploaded images. In that case there is no need to store very large image in the server. So before going to uploading to the server, we are going to create thumbnail image or reduce the size of image as we wish using C#/ASP.net. This is very simple sample of reducing image and can be easily understand by beginners also.

Step by Step process to create an application for reducing size of image before uploaded to the server in ASP.Net/C#

 Step 1 . Create a ASP.Net project and create a web page.

Step 2.  Drag a file uploader, button and Datalist(for display uploaded images)

ASPX Page

 <asp:Panel runat="server">
<asp:FileUpload ID="fileupload1" runat="server" />
<asp:Button ID="btnsave" runat="server" Text="Upload" OnClick="btnsave_Click" />
</div>
<div>
<asp:DataList ID="dtlist" runat="server" RepeatColumns="3" CellPadding="5">
<ItemTemplate>
<asp:Image ID="Image1" ImageUrl='<%# Bind("Name", "~/Images1/{0}") %>' runat="server" />
<br />
<asp:HyperLink ID="HyperLink1" Text='<%# Bind("Name") %>'
NavigateUrl='<%# Bind("Name", "~/Images1/{0}") %>'
runat="server" />
</ItemTemplate>
<ItemStyle BorderColor="Brown" BorderStyle="dotted" BorderWidth="3px"
HorizontalAlign="Center"
VerticalAlign="Bottom" />
</asp:DataList>
</asp:Panel>

 

Step 3 .  In page load call function ‘BindDataList’ to display uploaded images

Step 4.   On Save button click event, call function ‘GenerateThumbnails’ for reduce of image.

Code Behind Page 

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDataList();
}
}
protected void BindDataList()
{
DirectoryInfo dir = new DirectoryInfo(MapPath("Images1"));
FileInfo[] files = dir.GetFiles();
ArrayList listItems = new ArrayList();
foreach (FileInfo info in files)
{
listItems.Add(info);
}
dtlist.DataSource = listItems;
dtlist.DataBind();
}
protected void btnsave_Click(object sender, EventArgs e)
{
string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
string targetPath = Server.MapPath("Images1/" + filename);
Stream strm = fileupload1.PostedFile.InputStream;
var targetFile = targetPath;
//Based on scalefactor image size will vary
GenerateThumbnails(0.5, strm, targetFile);
BindDataList();
}
private void GenerateThumbnails(double scaleFactor, Stream sourcePath,
string targetPath)
{
using (var image = Image.FromStream(sourcePath))
{
// can given width of image as we want
var newWidth = (int)(image.Width * scaleFactor); 
// can given height of image as we want
var newHeight = (int)(image.Height * scaleFactor);
var thumbnailImg = new Bitmap(newWidth, newHeight);
var thumbGraph = Graphics.FromImage(thumbnailImg);
thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
thumbGraph.DrawImage(image, imageRectangle);
thumbnailImg.Save(targetPath, image.RawFormat);
}           
}
 

Image Size 36 KB

By using above application, we can reduce the size of images before uploaded to the server. If we check the size of the image that we uploaded, that will be less than the size of image that having in the local folder. We can implement this mechanism in most of the shopping site and photo gallery sites so that we can store large amount of images with small size and it will help the performance of the application. We can identify that even reducing the size of image there is no variation in quality or clarity of the image.  So we can easily reduce the resolution of the image using above code in ASP.Net/C# application.

%d bloggers like this: