Monday, June 2, 2014

How to upload resize images?

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>

<!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">

<script src="Scripts/jquery-2.1.0.min.js"></script>

<head runat="server">

<script type="text/javascript">

function readURL(input) {

if (input.files && input.files[0]) {

var reader = new FileReader();

reader.onload = function(e) {

$("#<%= this.ImgPhoto.ClientID %>").attr('src', e.target.result);



};

reader.readAsDataURL(input.files[0]);

}

}

$("#<%= this.UploadPhoto.ClientID %>").change(function () {

readURL(this);



});

</script>





</head>

<body>

<form id="form1" runat="server">

<img id="ImgPhoto" alt="Preview" width="206" height="240" runat="server" src="~/Images/NoPhoto.jpg" />

<br/>

<asp:FileUpload ID="UploadPhoto" runat="server" onchange="readURL(this)" />

<asp:Button runat="server" ID="btnsubmit" Text="Submit" OnClick="btnsubmit_Click"/>

</form>

</body>

</html>

====================

using System;

using System.IO;

using System.Data;

using System.Configuration;

using System.Globalization;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Drawing;

public partial class Default : System.Web.UI.Page



{
 
protected void Page_Load(object sender, EventArgs e)



{

}
 
public static Bitmap ResizePassportSize(FileUpload fp, int lnWidth, int lnHeight)



{
 
Bitmap bmpOut = null;

try



{
 
Bitmap loBmp = new Bitmap(fp.FileContent, true);

decimal lnRatio;

int lnNewWidth = 0;

int lnNewHeight = 0;

//*** If the image is smaller than a thumbnail just return it

if (loBmp.Width < lnWidth && loBmp.Height < lnHeight)

return loBmp;

if (loBmp.Width > loBmp.Height)



{
 
lnRatio = (decimal) lnWidth/loBmp.Width;



lnNewWidth = lnWidth;
 
decimal lnTemp = loBmp.Height*lnRatio;

lnNewHeight = (int) lnTemp;



}
 
else



{
 
lnRatio = (decimal) lnHeight/loBmp.Height;



lnNewHeight = lnHeight;
 
decimal lnTemp = loBmp.Width*lnRatio;

lnNewWidth = (int) lnTemp;



}
 
bmpOut = new Bitmap(lnNewWidth, lnNewHeight);

Graphics g = Graphics.FromImage(bmpOut);

g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);



g.DrawImage(loBmp, 0, 0, lnNewWidth, lnNewHeight);

loBmp.Dispose();

}
 
catch



{
 
return null;



}
 
return bmpOut;



}
 
protected void btnsubmit_Click(object sender, EventArgs e)



{
 
if (UploadPhoto.HasFile)



{
 
Bitmap bitmpPhoto = ResizePassportSize(this.UploadPhoto, 206, 240);

bitmpPhoto.Save(Server.MapPath("images/abc.jpg"));



}

}

}
 
 

No comments:

Post a Comment