Monday, 3 June 2013

Create Thumbnail Image in asp.net

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

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>
    <div>
    <asp:FileUpload ID="fileupload1" runat="server" /><br />
    <asp:Button ID="btn" runat="server" Text="Save" Width="80" onclick="btn_Click" />
    </div>
    </form>
</body>
</html>
c# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btn_Click(object sender, EventArgs e)
    {
        string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
        string targetPath = Server.MapPath("~/image/" +"small"+ filename);
        Stream strm = fileupload1.PostedFile.InputStream;
        var targetFile = targetPath;
        ConvertThumbnails(0.07, strm, targetFile);
    }
    private void ConvertThumbnails(double scaleFactor, Stream sourcePath, string targetPath)
    {
       
            var image = System.Drawing.Image.FromStream(sourcePath);
            var newWidth = (int)(image.Width * scaleFactor);
            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);
      
    }
}

No comments:

Post a Comment