This article is basically for how to resize or cropping the images. How you can
handle your images when you want to upload on website where the images
container or dimensions are in fixed size. In this article we will learn
step by step how to resize images on the basis of heightwise and widthwise. First
of all we need to find out the image orientation (It is a landscape
image or portrait image) and then start resizing process.
Note 1:- We need to calculate aspect ratio of origianl image.
eg. original image Height=3456, Width=5184
aspect ratio=1.5
Note 2:- Calculate aspect ratio of fixed size whatever you mention.
eg. height=160,width=255
aspect ratio= 1.5
Formula for clculate aspect ratio (double aspect = (double)srcWidth / (double)srcHeight;)
How to crope image file?
I have used Jquery.Jcrop.min.js file for cropping process.
<link href="~/Content/cssNew/jquery.Jcrop.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="~/Scripts/jquery.Jcrop.min.js"></script>
Step 1:- Html
--------------------HTML for cropping image -------------
<div>
<input class="ImageClassBanner" type="file" name="ImageClassBanner" id="HeaderBannerImageFile" />
</div>
<div id="divCropBannerImage" style="text-align:center; float:left;width:100%; display:none;">
<img id="imgBannerForCrop" style="text-align:center; margin-
top:20px;" />
<p style="margin-top:10px;">
<a id="pCropBannerImageButton" onclick="cropImage
('imgBannerForCrop');" class="btn btn-default btn-sm hide_element">Crop Image</a>
</p>
</div>
<div>
<img id="CroppedImage"/>
</div>
Step 2:- Upload image file by using the jquery code.
In this code i have applied the validation check
upload only(jpg,jpeg,png,gif,bmp) files. After
uploaded the file then applied jcrop functionality on
recently upload image file.
-------- Jquery code for upload image file and applied validation check....
<script type="text/javascript">
$(document).on("change", ".ImageClassBanner", function (event) {
var UploadImage = "/Home/Image";
var flag = false;
var file = getNameFromPath($(this).val());
if (file != null) {
var extension = file.substr((file.lastIndexOf('.') + 1));
switch (extension.toLowerCase()) {
case 'jpg':
case 'jpeg':
case 'png':
case 'gif':
case 'bmp':
flag = true;
break;
default:
flag = false;
}
}
if (flag == false) {
alert(popupAlertUploadOnlyImage);
return false;
}
if (flag == true) {
files = event.target.files;
if (10 > (event.target.files[0].size / 1048576)) {
var reader = new FileReader();
//Read the contents of Image File.
reader.readAsDataURL(files[0]);
reader.onload = function (e) {
//Initiate the JavaScript Image object.
var image = new Image();
//Set the Base64 string return from FileReader as source.
image.src = e.target.result;
image.onload = function () {
//Determine the Height and Width.
var height = this.height;
var width = this.width;
var imageType = 2;
var contentType = "multipart/form-data";
var fd = new FormData();
var URL = UploadImage;
fd.append("Image", files[0]);
fd.append("ImageName", "");
fd.append("ImageType", imageType);
fd.append("ImageHeight", height);
fd.append("ImageWidth", width);
$.ajax({
url: URL,
type: "post",
data: fd, processData: false, contentType: false,
success: function (response) {
if (response.IsSuccess) {
$('#divCropBannerImage').show();
// destroy Jcrop if it is existed
if (typeof jcrop_api != 'undefined') {
jcrop_api.destroy();
jcrop_api = null;
$('#imgBannerForCrop').attr({ 'src':
response.OriginalImagePath + response.ImagePath + "?t=" + new Date().getTime(), 'width':
response.ImageHeightWidth.Width, 'height': response.ImageHeightWidth.Height }).css({ 'height':
response.ImageHeightWidth.Height, 'width': response.ImageHeightWidth.Width })
}
else {
$('#imgBannerForCrop').attr({ 'src':
response.OriginalImagePath + response.ImagePath + "?t=" + new Date().getTime(), 'width':
response.ImageHeightWidth.Width, 'height': response.ImageHeightWidth.Height }).css({ 'height':
response.ImageHeightWidth.Height, 'width': response.ImageHeightWidth.Width })
}
$('#imgBannerForCrop').attr('ImageName', response.ImagePath);
$('#pCropBannerImageButton').show();
initCrop('imgBannerForCrop',255, 160, 255, 160);
//end Jcrop
}
else {
alert(response.Message);
}
},
error: function (data) {
}
});
};
}
}
else {
alert(imageSizeAlertMessage);
}
}
});
Step 3:- Below mentioned functions or variables are used for crop the image file.
// Jquery croping variables and functions
var imageCropWidth = 155;
var imageCropHeight = 65;
var cropPointX = 0;
var cropPointY = 0;
var jcrop_api;
//initialize jcrop on selected image file.
function initCrop(imageId,minWidth, minHeight, maxWidth, maxHeight) {
$('#' + imageId).Jcrop({
setSelect: [0, 0, maxWidth, maxHeight],
onChange: setCoordsAndImgSize,
bgOpacity: .5,
sideHandles: false,
minSize: [minWidth, minHeight],
maxSize: [maxWidth, maxHeight]
}, function () {
jcrop_api = this;
});
}
function setCoordsAndImgSize(e) {
cropPointX = e.x;
cropPointY = e.y;
imageCropWidth = e.w;
imageCropHeight = e.h;
}
// This function is used to save the croped image file and display it on the page.
function cropImage(imageId) {
var cropImage = "/Home/CropImage";
if (imageCropWidth == 0 && imageCropHeight == 0) {
alert("Please select crop area.");
return;
}
var data2 = JSON.stringify({
imageName: $("#" + imageId).attr("ImageName"), cropPointX: cropPointX, cropPointY:
cropPointY,
imageCropWidth: imageCropWidth, imageCropHeight: imageCropHeight
});
$.ajax({
url: cropImage,
type: 'POST',
data: data2,
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success: function (data) {
//Saved and set article crop image
$('#divCropBannerImage').hide();
$('#CroppedImage').attr('src', data.photoPath + '?t=' + new Date().getTime
()).show();
//End article image upload
},
error: function (data) {
}
});
}
</script>
MVC action method code for save original image file
and resige image on the basis of height wise
and width wise.
[HttpPost]
public ActionResult Image(HttpPostedFileWrapper Image, string ImageName,short ImageType, int
ImageHeight, int ImageWidth)
{
int imgHeight = 0, imgWidth = 0;
int[] imageDimension;
string logoImageBase64 = "", fileName = "";
if (Image == null || Image.ContentLength == 0)
{
return Json(new
{
Messsage = "No Image",
IsSuccess = false
}, JsonRequestBehavior.AllowGet);
}
fileName = String.Format("{0}.png", Guid.NewGuid().ToString());
string TemplateImagesPath = "/Content/UploadedImages/";
string TemplateImagesPathThumb="/Content/UploadedImages/Thumb";
var templateImagesPath = Path.Combine(Server.MapPath(Url.Content(TemplateImagesPath)),
fileName);
var templateThumbPath = Path.Combine(Server.MapPath(Url.Content(TemplateImagesPathThumb)),
fileName);
Image i = Bitmap.FromStream(Image.InputStream);
i.Save(templateImagesPath);
//Get image dimensions on the basis of image orientation.
imageDimension = Helper.ImageHelper.GetImageDimensions(i, ImageWidth, ImageHeight);
if (imageDimension.Length > 0)
{
//Get calculated height and width of image file.
int[] heightWidth = Helper.ImageHelper.CalculateImageDimension(imageDimension[0],
imageDimension[1], 255, 160);
if (heightWidth.Length > 0)
{
// Resize the image file.
var newsletterContentTemplateImage = Helper.ImageHelper.FixedSize(i,
Convert.ToInt32(heightWidth[0]), Convert.ToInt32 (heightWidth[1]));
newsletterContentTemplateImage.Save(templateThumbPath);
imgWidth = Convert.ToInt32(heightWidth[0]);
imgHeight = Convert.ToInt32(heightWidth[1]);
}
}
return Json(new
{
BaseImagePath = TemplateImagesPath + "thumb/",
ImagePath = Url.Content(String.Format("{0}", fileName)),
IsSuccess = true,
OriginalImagePath = GetSiteRoot() + TemplateImagesPathThumb,
ImageHeightWidth = new { Height = imgHeight, Width = imgWidth },
}, JsonRequestBehavior.AllowGet);
}
// This method is used for get the base path of the website.
private string GetSiteRoot()
{
string port = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
if (port == null || port == "80" || port == "443")
port = "";
else
port = ":" + port;
string protocol = System.Web.HttpContext.Current.Request.ServerVariables
["SERVER_PORT_SECURE"];
if (protocol == null || protocol == "0")
protocol = "http://";
else
protocol = "https://";
string sOut = protocol + System.Web.HttpContext.Current.Request.ServerVariables
["SERVER_NAME"] + port + System.Web.HttpContext.Current.Request.ApplicationPath;
if (sOut.EndsWith("/"))
{
sOut = sOut.Substring(0, sOut.Length - 1);
}
return sOut;
}
--------------------------------End---------------------------------------------------
-------------------------------Crope image file--------------------------------------------
This action method is used for save the cropped image and return the cropped image file path result in
json format.
[HttpPost]
public ActionResult CropImage(string imageName, int? cropPointX, int? cropPointY, int?
imageCropWidth, int? imageCropHeight)
{
if (string.IsNullOrEmpty(imageName) || !cropPointX.HasValue || !cropPointY.HasValue || !
imageCropWidth.HasValue || !imageCropHeight.HasValue)
{
return new HttpStatusCodeResult((int)System.Net.HttpStatusCode.BadRequest);
}
byte[] imageBytes = System.IO.File.ReadAllBytes(Server.MapPath("~/Content/UploadedImages/" +
imageName));
byte[] croppedImage = Helper.ImageHelper.CropImage(imageBytes, cropPointX.Value,
cropPointY.Value, imageCropWidth.Value, imageCropHeight.Value);
string tempFolderName = Server.MapPath("~/Content/UploadedImages/CroppedImages/");
string fileName = imageName;//Path.GetFileName(imagePath);
try
{
Helper.FileHelper.SaveFile(croppedImage, Path.Combine(tempFolderName, fileName));
}
catch (Exception ex)
{
//Log an error
return new HttpStatusCodeResult((int)System.Net.HttpStatusCode.InternalServerError);
}
string photoPath = string.Concat("/Content/UploadedImages/CroppedImages/", "/", fileName);
return Json(new { photoPath = photoPath }, JsonRequestBehavior.AllowGet);
}
------------------------------------------------------------------------
---------------------------Helper class--------------------------------
namespace Application.Helper
{
public static class FileHelper
{
public static void SaveFile(byte[] content, string path)
{
string filePath = GetFileFullPath(path);
if (!Directory.Exists(Path.GetDirectoryName(filePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
}
//Save file
using (FileStream str = File.Create(filePath))
{
str.Write(content, 0, content.Length);
}
}
public static string GetFileFullPath(string path)
{
string relName = path.StartsWith("~") ? path : path.StartsWith("/") ? string.Concat("~",
path) : path;
string filePath = relName.StartsWith("~") ? HostingEnvironment.MapPath(relName) : relName;
return filePath;
}
}
public static class ImageHelper
{
public static byte[] CropImage(byte[] content, int x, int y, int width, int height)
{
using (MemoryStream stream = new MemoryStream(content))
{
return CropImage(stream, x, y, width, height);
}
}
public static byte[] CropImage(Stream content, int x, int y, int width, int height)
{
//Parsing stream to bitmap
using (Bitmap sourceBitmap = new Bitmap(content))
{
//Get new dimensions
double sourceWidth = Convert.ToDouble(sourceBitmap.Size.Width);
double sourceHeight = Convert.ToDouble(sourceBitmap.Size.Height);
Rectangle cropRect = new Rectangle(x, y, width, height);
//Creating new bitmap with valid dimensions
using (Bitmap newBitMap = new Bitmap(cropRect.Width, cropRect.Height))
{
using (Graphics g = Graphics.FromImage(newBitMap))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.CompositingQuality = CompositingQuality.HighQuality;
g.DrawImage(sourceBitmap, new Rectangle(0, 0, newBitMap.Width, newBitMap.Height),
cropRect, GraphicsUnit.Pixel);
return GetBitmapBytes(newBitMap);
}
}
}
}
public static byte[] GetBitmapBytes(Bitmap source)
{
//Settings to increase quality of the image
ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders()[4];
EncoderParameters parameters = new EncoderParameters(1);
parameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
//Temporary stream to save the bitmap
using (MemoryStream tmpStream = new MemoryStream())
{
source.Save(tmpStream, codec, parameters);
//Get image bytes from temporary stream
byte[] result = new byte[tmpStream.Length];
tmpStream.Seek(0, SeekOrigin.Begin);
tmpStream.Read(result, 0, (int)tmpStream.Length);
return result;
}
}
This method is used for calcualte the aspect ratio of the original image file. Moreover it also
calculate the aspect ratio of user defined dimensions (eg. maxWidth=255 and maxHeight=160) and calcuate
the expected height and width of the image and return that dimension back to the calling method.
public static int[] CalculateImageDimension(int srcWidth, int srcHeight, int maxWidth, int
maxHeight)
{
double resizeWidth = 0.00, resizeHeight = 0.00;
double maxAspect = (double)maxWidth / (double)maxHeight;
double aspect = (double)srcWidth / (double)srcHeight;
if (maxAspect > aspect && srcWidth > maxWidth)
{
//Width is the bigger dimension relative to max bounds
resizeWidth = maxWidth;
resizeHeight = maxWidth / aspect;
}
else if (maxAspect <= aspect && srcHeight > maxHeight)
{
//Height is the bigger dimension
resizeHeight = maxHeight;
resizeWidth = maxHeight * aspect;
}
else
{
resizeHeight = maxHeight;
resizeWidth = maxWidth;
}
int[] heightWidth = new[] { Convert.ToInt32(resizeWidth), Convert.ToInt32(resizeHeight) };
return heightWidth;
}
This method is used to get the orientation of the image.
eg. You have taken image from your mobile and image orientation is landscape wise, portrait wise etc.
Sometimes if you upload very big size portrait image and you find the height of image convert it into
width and width into height in that situation you have to maintain original orientatio then use below
mentioned code. It will provide you the original orientation of image.
public static int[] GetImageDimensions(Image imgPhoto, int Width, int Height)
{
#region Check Orientaion
if (imgPhoto.PropertyIdList.Contains(0x112)) //0x112 = Orientation
{
var prop = imgPhoto.GetPropertyItem(0x112);
if (prop.Type == 3 && prop.Len == 2)
{
UInt16 orientationExif = BitConverter.ToUInt16(imgPhoto.GetPropertyItem(0x112).Value,
0);
if (orientationExif == 8)
{ //Swaping the Width with Height as Required
int var = Width;
Width = Height;
Height = var;
}
else if (orientationExif == 3)
{
//Swaping the Width with Height as Required
int var = Width;
Width = Height;
Height = var;
}
else if (orientationExif == 6)
{
//Swaping the Width with Height as Required
int temp = Width;
Width = Height;
Height = temp;
}
}
}
#endregion
#region Return and Free Memory
int[] heightWidth = new[] { Width, Height };
return heightWidth;
#endregion
}
This method is used to resize the image file. I have passed fixed size of image dimensions and this
method will resize the image on the basis of fixed height and width.
public static Image FixedSize(Image imgPhoto, int Width, int Height)
{
#region Check Orientaion
int isRorated = 0;
if (imgPhoto.PropertyIdList.Contains(0x112)) //0x112 = Orientation
{
var prop = imgPhoto.GetPropertyItem(0x112);
if (prop.Type == 3 && prop.Len == 2)
{
UInt16 orientationExif = BitConverter.ToUInt16(imgPhoto.GetPropertyItem(0x112).Value,
0);
if (orientationExif == 8)
{ //Swaping the Width with Height as Required
isRorated = 8;
int var = Width;
Width = Height;
Height = var;
}
else if (orientationExif == 3)
{
//Swaping the Width with Height as Required
isRorated = 3;
int var = Width;
Width = Height;
Height = var;
}
else if (orientationExif == 6)
{
//Swaping the Width with Height as Required
isRorated = 6;
int temp = Width;
Width = Height;
Height = temp;
}
}
}
#endregion
#region Generate Thumbnail
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)Width / (float)sourceWidth);
nPercentH = ((float)Height / (float)sourceHeight);
if (nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = System.Convert.ToInt16((Width -
(sourceWidth * nPercent)) / 2);
}
else
{
nPercent = nPercentW;
destY = System.Convert.ToInt16((Height -
(sourceHeight * nPercent)) / 2);
}
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap bmPhoto = new Bitmap(Width, Height,
PixelFormat.Format32bppArgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
imgPhoto.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.Clear(System.Drawing.Color.Transparent);
grPhoto.InterpolationMode =
InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);
switch (isRorated)
{
case 8:
bmPhoto.RotateFlip(RotateFlipType.Rotate270FlipNone);
break;
case 6:
bmPhoto.RotateFlip(RotateFlipType.Rotate90FlipNone);
break;
case 3:
bmPhoto.RotateFlip(RotateFlipType.Rotate180FlipNone);
break;
default:
break;
}
#endregion
#region Return and Free Memory
grPhoto.Dispose();
return bmPhoto;
#endregion
}
}
}
This is the complete solution for resizing, cropping and
upload images.
Thanks.