Resize Images

How do I resize images with ASP.NET 2.0 and using C#??

thanks in advance

Andrew
LVL 20
REA_ANDREWAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

SwapnilSoftware ArchitectCommented:
Hi REA_ANDREW,

Following will help you.

True Image Resizing
http://aspnet.4guysfromrolla.com/articles/012203-1.aspx

Regards,
NetSwap
0
Ramesh SrinivasTechnical ConsultantCommented:
Hi,

Create a page with the code below, and then use the code below that to use the resizing function.

*note: This code will resize the image so that it does not exceed a specific width. You can optionally pass in parameters to set the size that you want.

========================================================
Imports System.Drawing.Imaging
Imports System.Net
Imports System.IO

Public Class sizer
    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region


    Function GetImageFromURL(ByVal url As String) As Byte()
        Dim wr As HttpWebRequest = _
           DirectCast(WebRequest.Create(url), HttpWebRequest)
        Dim wresponse As HttpWebResponse = _
           DirectCast(wr.GetResponse, HttpWebResponse)
        Dim responseStream As Stream = wresponse.GetResponseStream
        Dim br As BinaryReader = New BinaryReader(responseStream)
        Dim bytesize As Long = wresponse.ContentLength
        Return br.ReadBytes(bytesize)
    End Function

    Private Sub ErrorResult()
        Response.Clear()
        Response.StatusCode = 404
        Response.End()
    End Sub 'ErrorResult

    Public Shared Function CreateThumbnail(ByVal lcFilename As MemoryStream, ByVal lnWidth As Integer, ByVal lnHeight As Integer) As Bitmap
        Dim bmpOut As System.Drawing.Bitmap = Nothing
        Try
            Dim loBMP As New Bitmap(lcFilename)
            Dim loFormat As ImageFormat = loBMP.RawFormat
            Dim lnRatio As Decimal
            Dim lnNewWidth As Integer = 0
            Dim lnNewHeight As Integer = 0

            '*** If the image is smaller than a thumbnail just return it
            If loBMP.Width < lnWidth And loBMP.Height < lnHeight Then
                Return loBMP
            End If

            If loBMP.Width > loBMP.Height Then
                lnRatio = CDec(lnWidth) / loBMP.Width
                lnNewWidth = lnWidth

                Dim lnTemp As Decimal = loBMP.Height * lnRatio
                lnNewHeight = CInt(lnTemp)
            Else
                lnRatio = CDec(lnHeight) / loBMP.Height
                lnNewHeight = lnHeight

                Dim lnTemp As Decimal = loBMP.Width * lnRatio
                lnNewWidth = CInt(lnTemp)
            End If

            ' System.Drawing.Image imgOut =
            '      loBMP.GetThumbnailImage(lnNewWidth,lnNewHeight,
            '                              null,IntPtr.Zero);


            ' *** This code creates cleaner (though bigger) thumbnails and properly
            ' *** and handles GIF files better by generating a white background for
            ' *** transparent images (as opposed to black)
            bmpOut = New Bitmap(lnNewWidth, lnNewHeight)

            Dim g As Graphics = 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 Nothing
        End Try

        Return bmpOut
    End Function 'CreateThumbnail

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        Dim rLink = Request.QueryString("vLink") <------- link to image - u can optionally  pass in width & height

        Dim sSize As String = 745
        Dim Size As Integer = 120

        If Not (sSize Is Nothing) Then
            Size = Int32.Parse(sSize)
        End If

        Dim Path
        Try
            Path = New MemoryStream(GetImageFromURL(Server.UrlDecode(rLink)))
        Catch er As Exception
            Path = New MemoryStream(GetImageFromURL("http://www.mydomain.com/img/NotAvailable.gif"))
        End Try
        Dim bmp As Bitmap = CreateThumbnail(Path, Size, Size)

        Response.ContentType = "image/jpeg"
        bmp.Save(Response.OutputStream, ImageFormat.Jpeg)
    End Sub

End Class
========================================================

To create the resized image using the code above, just set an ordinary image tag like so:

<img src="sizer.aspx?vLink=http://www.myDomain.com/img/myImage.jpg">


all the best,

KS
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ramesh SrinivasTechnical ConsultantCommented:
Also, you must modify this line, if you want to let the width be variable without limits:

Dim bmp As Bitmap = CreateThumbnail(Path, Size, Size)

replace it with:

Dim bmp As Bitmap = CreateThumbnail(Path, Size, sSize)


To give u an example of this, use the code below also:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        Dim rLink = Request.QueryString("vLink")
        Dim rWidth = Request.QueryString("w")
        Dim rHeight = Request.QueryString("h")

        Dim sSize As String = rWidth
        Dim Size As Integer = rHeight


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

Now change the image tag to:

<img src="sizer.aspx?vLink=http://www.myDomain.com/img/myImage.jpg&w=500&h=300">

This will resize the image to 500 by 300.

regards,

KS
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

REA_ANDREWAuthor Commented:
When I pasted the code into. It gave me these errors in the error window

Error      1      Type 'Bitmap' is not defined.      C:\Inetpub\wwwroot\frag\sizer.aspx.vb      46      134      C:\...\frag\
Error      2      Type 'Bitmap' is not defined.      C:\Inetpub\wwwroot\frag\sizer.aspx.vb      49      30      C:\...\frag\
Error      3      Type 'Bitmap' is not defined.      C:\Inetpub\wwwroot\frag\sizer.aspx.vb      82      26      C:\...\frag\
Error      4      Type 'Graphics' is not defined.      C:\Inetpub\wwwroot\frag\sizer.aspx.vb      84      22      C:\...\frag\
Error      5      Name 'Brushes' is not declared.      C:\Inetpub\wwwroot\frag\sizer.aspx.vb      86      29      C:\...\frag\
Error      6      End of statement expected.      C:\Inetpub\wwwroot\frag\sizer.aspx.vb      99      64      C:\...\frag\
Error      7      Name 'rLink' is not declared.      C:\Inetpub\wwwroot\frag\sizer.aspx.vb      110      70      C:\...\frag\
Error      8      Type 'Bitmap' is not defined.      C:\Inetpub\wwwroot\frag\sizer.aspx.vb      114      20      C:\...\frag\
0
SystemExpertCommented:
hi
 
this link  has sample project what you want



http://www.codeproject.com/aspnet/pnguploader.asp

Thanks
0
Ramesh SrinivasTechnical ConsultantCommented:
Andrew,

You need to include the following lines at the very top:

Imports System.Drawing.Imaging
Imports System.Net
Imports System.IO



0
REA_ANDREWAuthor Commented:
ok I have narrowed the rrors down to 2

Error      1      Type 'ImageFormat' is not defined.      C:\Inetpub\wwwroot\frag\sizer.aspx.vb      50      29      C:\...\frag\
Error      2      Name 'ImageFormat' is not declared.      C:\Inetpub\wwwroot\frag\sizer.aspx.vb      117      41      C:\...\frag\


I am designing with ASP.NET 2.0
0
REA_ANDREWAuthor Commented:
I have.  but in asp.net 2.0 the first one is now

Imports System.Drawing
0
REA_ANDREWAuthor Commented:
I fixed it using this at the top

Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Net
Imports System.IO
0
Ramesh SrinivasTechnical ConsultantCommented:
Yes, I just looked it up and saw that the namespaces had slightly been changed, so you had to include Drawing as well.

All the best.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.