Monday, July 1, 2013

How to Resize image without losing quality in Asp.net

Introduction: In this article I will explain how we can Resizes the image, Validate fileupload control in Asp.net.

Description:
In the previous article I have explained How to Validate theFileupload in Asp.net.
Add a webform to project. Keep the below given script between Head Tag:
<script type="text/javascript">
         function validatefileupload() {
             var arrayExt = ['png', 'PNG', 'jpg', 'JPG', 'JPEG', 'gif', 'GIF', 'jpeg'];
             var FilesVale = document.getElementById("uploadimg");
             var Ext = FilesVale.value.substring(FilesVale.value.lastIndexOf('.') + 1).toLowerCase();
             if (arrayExt.indexOf(Ext) <= -1) {
                 alert("Upload Only png,jpg,gif files");
                 return false;
             }
             else {
                 alert("File Upload Successfully..")
             }
         }
    </script>

Drag and drop the Fileupload control from Toolbox. Here I create a Folder Upload_Images and its sub folder Thumb and Small to save Resized Images.
<table border="1px solid">
       <tr><b>Upload,Validate and Resize the Images in Asp.net</b></tr>
       <tr><td>Upload Images</td><td> <asp:FileUpload ID="uploadimg" runat="server" /></td></tr>
    <tr><td>&nbsp;</td><td><asp:Button ID="Button1" runat="server"
            Text="Upload" onclick="Button1_Click"  OnClientClick="return validatefileupload();"/></td></tr>
    </table>

Now on button click write the below mention code (.aspx.cs):
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Design;
using System.IO;

protected void Button1_Click(object sender, EventArgs e)
    {
        if (uploadimg.HasFile)
        {
            string imgThumb = string.Empty;
            string imgSmall = string.Empty;           
            Bitmap bmpThumb = null;
            Bitmap bmpSmall = null;
            try
            {
                bmpThumb = Resize_Images(uploadimg.PostedFile.InputStream, 100, 67);
                bmpSmall = Resize_Images(uploadimg.PostedFile.InputStream, 411, 270);
                imgThumb = Server.MapPath("Upload_Images/Thumb/") + Guid.NewGuid().ToString() + ".png";
                imgSmall = Server.MapPath("Upload_Images/Small/") + Guid.NewGuid().ToString() + ".png";                
                bmpThumb.Save(imgThumb, ImageFormat.Jpeg);
                bmpSmall.Save(imgSmall, ImageFormat.Jpeg);               
            }
            catch (Exception ex)
            {
               
            }
            finally
            {
                imgThumb = string.Empty;
                imgSmall = string.Empty;
                bmpThumb.Dispose();
                bmpSmall.Dispose();
            }
    }
    }
    private Bitmap Resize_Images(Stream StreamImage,int Maxwidth, int Maxheight)
    {
        Bitmap originalImage = new Bitmap(StreamImage);
        int newWidth = originalImage.Width;
        int newHeight = originalImage.Height;
        double aspectRatio = Convert.ToDouble(originalImage.Width) / Convert.ToDouble(originalImage.Height);

        if (aspectRatio <= 1 && originalImage.Width > Maxwidth)
        {
            newWidth = Maxwidth;
            newHeight = Convert.ToInt32(Math.Round(newWidth / aspectRatio));
        }
        else if (aspectRatio > 1 && originalImage.Height > Maxheight)
        {
            newHeight = Maxheight;
            newWidth = Convert.ToInt32(Math.Round(newHeight * aspectRatio));
        }
        return new Bitmap(originalImage, newWidth, newHeight);
    }

In VB (.aspx.vb)
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Drawing.Imaging
Imports System.Drawing.Design
Imports System.IO
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        If uploadimg.HasFile Then
            Dim imgThumb As String = String.Empty
            Dim imgSmall As String = String.Empty
            Dim bmpThumb As Bitmap = Nothing
            Dim bmpSmall As Bitmap = Nothing
            Try
                bmpThumb = Resize_Images(uploadimg.PostedFile.InputStream, 100, 67)
                bmpSmall = Resize_Images(uploadimg.PostedFile.InputStream, 411, 270)
                imgThumb = Server.MapPath("Upload_Images/Thumb/") + Guid.NewGuid().ToString() + ".png"
                imgSmall = Server.MapPath("Upload_Images/Small/") + Guid.NewGuid().ToString() + ".png"
                bmpThumb.Save(imgThumb, ImageFormat.Jpeg)
                bmpSmall.Save(imgSmall, ImageFormat.Jpeg)

            Catch ex As Exception
            Finally
                imgThumb = String.Empty
                imgSmall = String.Empty
                bmpThumb.Dispose()
                bmpSmall.Dispose()
            End Try
        End If
    End Sub
    Private Function Resize_Images(ByVal StreamImage As Stream, ByVal Maxwidth As Integer, ByVal Maxheight As Integer) As Bitmap
        Dim originalImage As New Bitmap(StreamImage)
        Dim newWidth As Integer = originalImage.Width
        Dim newHeight As Integer = originalImage.Height
        Dim aspectRatio As Double = Convert.ToDouble(originalImage.Width) / Convert.ToDouble(originalImage.Height)

        If aspectRatio <= 1 AndAlso originalImage.Width > Maxwidth Then
            newWidth = Maxwidth
            newHeight = Convert.ToInt32(Math.Round(newWidth / aspectRatio))
        ElseIf aspectRatio > 1 AndAlso originalImage.Height > Maxheight Then
            newHeight = Maxheight
            newWidth = Convert.ToInt32(Math.Round(newHeight * aspectRatio))
        End If
        Return New Bitmap(originalImage, newWidth, newHeight)
    End Function


Build and check the result.

Is it helpful?

If yes post your comment to admire my work. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.

No comments:

Post a Comment