Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Resizing images
Message
From
02/04/2014 13:55:14
 
 
To
All
General information
Forum:
ASP.NET
Category:
Other
Title:
Resizing images
Environment versions
Environment:
VB 9.0
OS:
Windows 7
Network:
Windows 2003 Server
Database:
MS SQL Server
Application:
Web
Miscellaneous
Thread ID:
01597952
Message ID:
01597952
Views:
46
Here is a short version of an Image class I have which serves for resizing JPG images. Feel free to use as needed. The constructor makes use of a framework implementation but that is easily adjustable to fit your own needs. I have another method in it that I did not include to remove the border of an image. Feel free to ask if you wish to use it.
Imports System.Drawing

Public Class Image

    Public nCropHeight As Integer = 0
    Public nCropWidth As Integer = 0
    Public cFile As String = ""
    Public cFileDestination As String = ""
    Public cMessage As String = ""
    Public lImageHasBeenPreserved As Boolean = False
    Public lResizeButNoCrop As Boolean = False
    Public lVerifyForWidthAndHeight As Boolean = False
    Public nHeight As Integer = 0
    Public nStartXPoint As Integer = 0
    Public nStartYPoint As Integer = 0
    Public nWidth As Integer = 0
    Private cCannotSaveHightQuality As String = ""
    Private cFileDoesNotExist As String = ""
    Private cPixelFormatNotSupported As String = ""
    Private cThisFileIsNotSupported As String = ""
    Private nLanguage As Integer = 0
    Private oApp As Framework.App = Nothing
    Private oImage As System.Drawing.Bitmap = Nothing
    Private oProcess As Framework.LXProcess = Nothing

    ' This is when we access the class in a desktop mode
    Sub New(ByVal toApplication As Framework.App)
        oApp = toApplication
        nLanguage = oApp.nLanguage
        Init()
    End Sub

    ' This is when we access the class in a Web or Web Service mode
    Public Sub New(ByVal toProcess As Framework.LXProcess)
        oProcess = toProcess
        oApp = oProcess.oApp
        nLanguage = oProcess.nLanguage
        Init()
    End Sub

    Private Function Init() As Boolean

        ' Based on the language
        Select Case nLanguage

            ' English
            Case 1
                cCannotSaveHightQuality = "Cannot save in high quality."
                cDirectoryDoesNotExist = "The directory does not exist."
                cFileDoesNotExist = "The file does not exist."
                cPixelFormatNotSupported = "Pixel format of the image is not supported."
                cThisFileIsNotSupported = "The file ""##File##"" is not supported to be used in this application. It might be corrupted. You " + _
                 "may send this file to support if you think it is valid."

                ' French
            Case 2
                cCannotSaveHightQuality = "Ne peut faire sauver en haute résolution."
                cDirectoryDoesNotExist = "Le répertoire n'existe pas."
                cFileDoesNotExist = "Le fichier n'existe pas."
                cPixelFormatNotSupported = "Le format pixel de cette image n'est pas supporté."
                cThisFileIsNotSupported = "Le fichier ""##File##"" n'est pas supporté pour être utilisé dans cette application. " + _
                 "Il se peut qu'il soit corrompu. Vous pouvez l'envoyer au support si vous pensez qu'il est valide."

                ' Spanish
            Case 3
                cCannotSaveHightQuality = "Cannot save in high quality."
                cDirectoryDoesNotExist = "The directory does not exist."
                cFileDoesNotExist = "The file does not exist"
                cPixelFormatNotSupported = "Pixel format of the image is not supported."
                cThisFileIsNotSupported = "The file ""##File##"" is not supported to be used in this application. It might be corrupted. You " + _
                 "may send this file to support if you think it is valid."

                ' Portuguese
            Case 4
                cCannotSaveHightQuality = "Cannot save in high quality."
                cDirectoryDoesNotExist = "The directory does not exist."
                cFileDoesNotExist = "The file does not exist"
                cPixelFormatNotSupported = "Pixel format of the image is not supported."
                cThisFileIsNotSupported = "The file ""##File##"" is not supported to be used in this application. It might be corrupted. You " + _
                 "may send this file to support if you think it is valid."

        End Select

        Return True
    End Function

    ' Resize an image
    Public Function ImageResize() As Boolean
        Dim lcFile As String = ""
        Dim lnHeightRatio As Integer = 0
        Dim lnRatio As Double = 0
        Dim lnRatioImage As Double = 0
        Dim lnWidthRatio As Integer = 0
        Dim loFinalImage As Bitmap = Nothing
        Dim loGraphics As System.Drawing.Graphics = Nothing
        Dim loImage As System.Drawing.Bitmap = Nothing
        Dim loImage2 As System.Drawing.Bitmap = Nothing

        ' Reset the values
        lImageHasBeenPreserved = False
        oImage = Nothing

        ' Initialization
        lcFile = Trim(cFile)
        lVerifyForWidthAndHeight = True

        ' If the file does not exist
        If Not oApp.FileExist(lcFile) Then
            cMessage = cFileDoesNotExist
            Return False
        End If

        ' Try to negotiate with the image
        Try
            loImage = New System.Drawing.Bitmap(lcFile)
        Catch loError As Exception
            cMessage = oApp.StrTran(cThisFileIsNotSupported, "##File##", lcFile)
            Return False
        End Try

        ' If we can resize with no crop
        If lResizeButNoCrop Then

            ' Calculate the proper ratio as per the width
            lnHeightRatio = nWidth * loImage.Height / loImage.Width

            ' If the height is greater than the targeted resize height
            If lnHeightRatio > nHeight Then

                ' Adjust the width in regards to that
                nWidth = nHeight * loImage.Width / loImage.Height

                ' Use this flag to bypass the validation when the width and height is defined
                lVerifyForWidthAndHeight = False

            Else

                ' Calculate the proper ratio as per the height
                lnWidthRatio = nHeight * loImage.Width / loImage.Height

                ' If the height is greater than the targeted resize height
                If lnWidthRatio > nWidth Then

                    ' Adjust the height in regards to that
                    nHeight = nWidth * loImage.Height / loImage.Width

                    ' Use this flag to bypass the validation when the width and height is defined
                    lVerifyForWidthAndHeight = False

                End If

            End If

        End If

        ' If the image is already with the proper dimensions
        If nWidth = loImage.Width And nHeight = loImage.Height Then
            lImageHasBeenPreserved = True

            ' This is necessary as the image would remain locked
            loImage.Dispose()

            Return True
        End If

        ' If the width calculated is bigger than the original width or if the height calculated if bigger than the original width
        ' This is in the case the original image is 250x250 and that we would want to resize it to 600x900
        ' In such situation, we preserve the original image otherwise it would be deformed
        If nWidth > loImage.Width Or nHeight > loImage.Height Then
            nWidth = loImage.Width
            nHeight = loImage.Height
        End If

        ' Initialize a new image object on the required dimensions
        loImage2 = New System.Drawing.Bitmap(nWidth, nHeight, loImage.PixelFormat)

        ' If we can resize
        If loImage2.PixelFormat = Drawing.Imaging.PixelFormat.Format1bppIndexed Or _
            loImage2.PixelFormat = Drawing.Imaging.PixelFormat.Format4bppIndexed Or _
            loImage2.PixelFormat = Drawing.Imaging.PixelFormat.Format8bppIndexed Or _
            loImage2.PixelFormat = Drawing.Imaging.PixelFormat.Undefined Or _
            loImage2.PixelFormat = Drawing.Imaging.PixelFormat.DontCare Or _
            loImage2.PixelFormat = Drawing.Imaging.PixelFormat.Format16bppArgb1555 Or _
            loImage2.PixelFormat = Drawing.Imaging.PixelFormat.Format16bppGrayScale Then
            cMessage = cPixelFormatNotSupported

            ' This is necessary as the image would remain locked
            loImage.Dispose()

            Return False
        End If

        ' Initialization
        lnRatio = nWidth / nHeight
        lnRatioImage = loImage.Width / loImage.Height

        ' If the ratio of the image is smaller than the calculcated ratio
        If lnRatioImage < lnRatio Then
            nCropWidth = loImage.Width
            nCropHeight = loImage.Width / lnRatio
        Else
            nCropWidth = loImage.Height * lnRatio
            nCropHeight = loImage.Height
        End If

        ' Crop needs it
        oImage = loImage

        ' If we cannot crop
        If Not Crop() Then

            ' This is necessary as the image would remain locked
            loImage.Dispose()

            Return False
        End If

        ' Create the placeholder
        loFinalImage = New Bitmap(nWidth, nHeight)

        ' Assign the placeholder into the graphic converter
        loGraphics = System.Drawing.Graphics.FromImage(loFinalImage)

        ' Set the parameters
        loGraphics.SmoothingMode = Drawing.Drawing2D.SmoothingMode.HighQuality
        loGraphics.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
        loGraphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality
        loGraphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality

        ' Resize the image
        loGraphics.DrawImage(loImage, 0, 0, nWidth, nHeight)

        ' Release the image
        loGraphics.Dispose()

        ' The oImage property can now be assigned to the resized version
        oImage = loFinalImage

        ' If the image has not been altered by the Image class
        If lImageHasBeenPreserved Then
        Else

            ' If we cannot save the image
            If Not SaveAsHighQualityJpegFile() Then

            End If

        End If

        ' Remove this object from memory
        loImage.Dispose()

        ' Reset the values
        cFile = ""
        cFileDestination = ""
        lResizeButNoCrop = False

        Return True
    End Function

    ' Crop an image
    Public Function Crop() As Boolean
        Dim loGraphics As System.Drawing.Graphics = Nothing
        Dim loImage As System.Drawing.Bitmap = Nothing

        ' This is a placeholder
        loImage = New System.Drawing.Bitmap(nCropWidth, nCropHeight)
        loGraphics = System.Drawing.Graphics.FromImage(loImage)

        ' This will use oImage and obtain the new result into loImage
        loGraphics.DrawImage(oImage, New System.Drawing.Rectangle(0, 0, nCropWidth, nCropHeight), _
         nStartXPoint, nStartYPoint, nCropWidth, nCropHeight, System.Drawing.GraphicsUnit.Pixel)

        ' Release this object
        loGraphics.Dispose()

        ' Take the new result and dump it back to oImage
        oImage = loImage

        Return True
    End Function

    ' Save an image into a JPG format
    Public Function SaveAsHighQualityJpegFile() As Boolean
        Dim loEncoderParameters As System.Drawing.Imaging.EncoderParameters = Nothing
        Dim loImageCodecInfo As System.Drawing.Imaging.ImageCodecInfo = Nothing

        ' Set Image codec of JPEG type, the index of JPEG codec is "1"       
        loImageCodecInfo = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()(1)

        ' Set the parameters for defining the quality of the thumbnail... here it is set to 100%
        loEncoderParameters = New System.Drawing.Imaging.EncoderParameters(1)

        loEncoderParameters.Param(0) = New System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 95)

        oImage.Save(cFileDestination, loImageCodecInfo, loEncoderParameters)

        Return True
    End Function

End Class
How to call it:
        Dim loImage As Framework.Image = New Framework.Image(oApp)

            ' Resize the image
            loImage.cFile = "d:\Temp.jpg"
            loImage.cFileDestination = "d:\iis\Level Extreme\Store2\00000067.jpg
            loImage.nWidth = 170
            loImage.nHeight = 128
            If Not loImage.ImageResize() Then
                MessageBox.Show(loImage.cMessage, oApp.cTitle, MessageBoxButtons.OK, MessageBoxIcon.Stop)
                Exit Sub
            End If
Michel Fournier
Level Extreme Inc.
Designer, architect, owner of the Level Extreme Platform
Subscribe to the site at https://www.levelextreme.com/Home/DataEntry?Activator=55&NoStore=303
Subscription benefits https://www.levelextreme.com/Home/ViewPage?Activator=7&ID=52
Reply
Map
View

Click here to load this message in the networking platform