Buy My Account


Basics
Overview
Video Demos
Pricing & Ordering
Sample Applications
Customers
Free Training
What's New in V10.0
Download Now!

Product Tour
Product Tour
Web Applications
Mobile Applications
SharePoint Applications
Charts and Reports
Security
Architecture & Code
Team Development

Technical Materials
Training Courses
Online Help
Technical Forums
White Papers
One Day Web Apps E-book
System Requirements
Product Roadmap
Version History
Iron Speed Technical Forums

Register New Posts Chat
 
 
 


Reply
 
Author Comment
 
echo4sos

Avatar / Picture

MVP Developer
Registered: 01/20/06
Posts: 609
Reply with quote #1 

Here is some basic code to resize an image upon upload. Since many of us don't want our users uploading HUGE files, we can constrain the size, width and height. This is pretty straight forward. Example is written in VB.
 
For starters, this code goes in your page behind file (yourpage.aspx.vb) ...
***Replace YOUR_IMAGE_FIELD_NAME with the name of your own image upload field***

Code:
 

Public Sub SaveButton_Click(ByVal sender As Object, ByVal args As EventArgs)

' Click handler for SaveButton.

' Customize by adding code before the call or replace the call to the Base function with your own code.

If Not YOUR_IMAGE_FIELD_NAME.HasFile Then

SaveButton_Click_Base(sender, args)

Else

If YOUR_IMAGE_FIELD_NAME.HasFile Then

Dim filepath As String = YOUR_IMAGE_FIELD_NAME.PostedFile.FileName

Dim fileExt As String = LCase(System.IO.Path.GetExtension(YOUR_IMAGE_FIELD_NAME.FileName))

Dim myUpload As HttpPostedFile = YOUR_IMAGE_FIELD_NAME.PostedFile

If (fileExt = ".gif" Or fileExt = ".jpg" Or fileExt = ".bmp") And YOUR_IMAGE_FIELD_NAME.PostedFile.ContentLength < 500000 Then

Try

SaveButton_Click_Base(sender, args)

Catch ex As Exception

YOUR_IMAGE_FIELD_NAME_Label.Text = "ERROR: " & ex.Message.ToString() & ""

End Try

Else

YOUR_IMAGE_FIELD_NAME_Label.Text = "Only .gif, .jpg or .bmp files are allowed!

Also, images must be less than 500kb."

End If

End If

End If

' NOTE: If the Base function redirects to another page, any code here will not be executed.

End Sub


*Replace the amp; with actual & if copying code from here*


Basically, we are letting the user know that the image size cannot exceed 500kb in size, and it can only be .gif, .jpg or .bmp. If the user attempts to upload an image that doesn't comply, we set the image label to notify the user. You can change these values to suit your own application needs.

Next, insert this code in the yourpage.controls.vb file...
***Replace YOUR_IMAGE_FIELD_NAME with the name of your own image upload field***
Code:
 

'This is where we resize the uploaded image before saving to the database

Public Overrides Sub GetUIdata()

MyBase.GetUIData() ' this calls the base apply of the user data 

Const bmpW As Integer = 300 'New image target width

Const bmpH As Integer = 325 'New Image target height 

If YOUR_IMAGE_FIELD_NAME.HasFile Then

Dim newWidth As Integer = bmpW

Dim newHeight As Integer = bmpH

Dim Pic() As Byte = Me.DataSource.YOUR_IMAGE_FIELD_NAME

' Convert to image for resizing

Dim Img As Bitmap = Nothing

Img = CType(Bitmap.FromStream(New MemoryStream(Pic, 0, Pic.Length - 1)), Drawing.Bitmap)

Dim newImg As Bitmap = New Bitmap(newWidth, newHeight, Imaging.PixelFormat.Format24bppRgb)

newImg.SetResolution(72, 72)

'Get the uploaded image width and height 

Dim upWidth As Integer = Img.Width

Dim upHeight As Integer = Img.Height

Dim newX As Integer = 0 'Set the new top left drawing position on the image canvas

Dim newY As Integer = 0

Dim reDuce As Decimal

'Keep the aspect ratio of image the same if not 4:3 and work out the newX and newY positions 

'to ensure the image is always in the center of the canvas vertically and horizontally 

If upWidth > upHeight Then 'Landscape picture 

reDuce = CDec(newWidth / upWidth)

'calculate the width percentage reduction as decimal 

newHeight = CInt(Int(upHeight * reDuce))

'reduce the uploaded image height by the reduce amount 

newY = CInt(Int((bmpH - newHeight) / 2))

'Position the image centrally down the canvas 

newX = 0 'Picture will be full width 

ElseIf upWidth < upHeight Then 'Portrait picture 

reDuce = CDec(newHeight / upHeight)

'calculate the height percentage reduction as decimal 

newWidth = CInt(Int(upWidth * reDuce))

'reduce the uploaded image height by the reduce amount 

newX = CInt(Int((bmpW - newWidth) / 2))

'Position the image centrally across the canvas 

newY = 0 'Picture will be full hieght 

ElseIf upWidth = upHeight Then 'square picture 

reDuce = CDec(newHeight / upHeight)

'calculate the height percentage reduction as decimal 

newWidth = CInt(Int(upWidth * reDuce))

'reduce the uploaded image height by the reduce amount 

newX = CInt(Int((bmpW - newWidth) / 2)) 'Position the image centrally across the canvas 

newY = CInt(Int((bmpH - newHeight) / 2)) 'Position the image centrally down the canvas 

End If

'Create a new image from the uploaded picture using the Graphics class 

'Clear the graphic and set the background color to white 

'Use Antialias and High Quality Bicubic to maintain a good quality picture 

'Save the new bitmap image using 'jpg' picture format and the calculated canvas positioning 

Dim newGraphic As Graphics = Graphics.FromImage(newImg)

newGraphic.Clear(Color.White)

newGraphic.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias

newGraphic.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic

newGraphic.DrawImage(Img, newX, newY, newWidth, newHeight)

Dim stream As MemoryStream = New MemoryStream

newImg.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg)

Me.DataSource.YOUR_IMAGE_FIELD_NAME = stream.ToArray ' assign back to picture

stream.Close()

Img.Dispose()

newImg.Dispose()

newGraphic.Dispose()

End If



This is where we are actually resizing the image before posting to the database. If the user uploads a picture larger than 300x325 it will automatically downsize accordingly. If the user uploads a picture smaller than 300x325 it will automatically upsize accordingly. This will also adjust the values based on orientation (portrait or landscape). It will also keep all aspect ratio, so as not to distort the image. You can change the constants (width and height) figures to suit your own application needs.

***IMPORTANT - You MUST have the System.IO and System.Drawing Imports Statements on BOTH pages***
 
Hope this helps many of you fellow IS developers!

-Bill



__________________
-Bill
JimiJ

Avatar / Picture

MVP Developer
Registered: 03/31/05
Posts: 4,808
Reply with quote #2 
Bill,

Have you tried this in the table details?

Thanks

__________________
Jaime Jegonia
JimiTron Software
JimiTron.Net | JimiTron.Com

"...and whoever sows generously will
also reap generously"
2 Cor 9:6
echo4sos

Avatar / Picture

MVP Developer
Registered: 01/20/06
Posts: 609
Reply with quote #3 
Hey Jimi,

Not yet. I have only used this for a "one-time" upload. It would be interesting to revisit this with multiple uploads. I'll have to find the time to do so though!



__________________
-Bill
JamesWhistler

Avatar / Picture

MVP Consultant
Registered: 08/07/07
Posts: 251
Reply with quote #4 
Bill,

A supremely helpful utility.  I use it by default for all image uploads now!

Sincere thanks - this has helped me enormously.

James

__________________
James Whistler
+44 (0) 870 067 7601
james@acidyellow.com
http://www.acidyellow.com
jtejada

Registered: 02/19/09
Posts: 1
Reply with quote #5 
Can you Help me?
I have an erro using this magnific code.
When i insert the resizing code i get an compialtion error in the first line
"Public Overrides Sub GetUIdata()"
The instruction is not valid in a namespace
 
I've insert this code in the mypage.controls.vb in "section 1: Place your customizations here"
 
Thanks
miles

Avatar / Picture

MVP Consultant
Registered: 10/15/03
Posts: 3,231
Reply with quote #6 
your subroutine must be contained within a class definition in order to work.  Look a little farther into Section 1, and you should see class definitions for each of your panels etc..

HTH,

__________________
Miles Gibson, I.S.P., ITCP
Iron Speed MVP
Senior Consultant, Principal,
Milestone Software
http://www.ironspeedmvp.com
Email: miles@milestone.ca
Coming Soon: Full Localization for your Iron Speed Applications!
pieterdebeer

Registered: 07/01/09
Posts: 35
Reply with quote #7 

Do you a C# sample for resize image before uploading a image.

JimiJ

Avatar / Picture

MVP Developer
Registered: 03/31/05
Posts: 4,808
Reply with quote #8 
You can convert VB.Net to C#  here.

Hope that helps,


Jimi



__________________
Jaime Jegonia
JimiTron Software
JimiTron.Net | JimiTron.Com

"...and whoever sows generously will
also reap generously"
2 Cor 9:6
pieterdebeer

Registered: 07/01/09
Posts: 35
Reply with quote #9 

Thanks, will test it.

pieterdebeer

Registered: 07/01/09
Posts: 35
Reply with quote #10 

I have tried the generator without success. I did however find a converter that gives me the following code.




// This is where we resize the uploaded image before saving to the database
    
public override void GetUIdata() {
        
base.GetUIData();
        
//  this calls the base apply of the user data 
        
const int bmpW 300;
        
// New image target width
        
const int bmpH 325;
        
// New Image target height 
        
if (YOUR_IMAGE_FIELD_NAME.HasFile) {
            
int newWidth bmpW;
            int 
newHeight bmpH;
            byte
[] Pic = this.DataSource.YOUR_IMAGE_FIELD_NAME;
            
//  Convert to image for resizing
            
Bitmap Img = null;
            
Img ((Drawing.Bitmap)(Bitmap.FromStream(new MemoryStream(Pic, 0, (Pic.Length - 1)))));
            
Bitmap newImg = new Bitmap(newWidth, newHeight, Imaging.PixelFormat.Format24bppRgb);
            
newImg.SetResolution(7272);
            
// Get the uploaded image width and height 
            
int upWidth Img.Width;
            int 
upHeight Img.Height;
            int 
newX 0;
            
// Set the new top left drawing position on the image canvas
            
int newY 0;
            
Decimal reDuce;
            
// Keep the aspect ratio of image the same if not 4:3 and work out the newX and newY positions 
            // to ensure the image is always in the center of the canvas vertically and horizontally 
            
if ((upWidth > upHeight)) {
                
// Landscape picture 
                
reDuce Decimal.Parse((newWidth / upWidth));
                
newHeight = int.Parse(Int((upHeight * reDuce)));
                
newY = int.Parse(Int(((bmpH - newHeight) 
                                    / 
2)));
                
newX 0;
                
// Picture will be full width 
            
}
            
else if ((upWidth < upHeight)) {
                
// Portrait picture 
                
reDuce Decimal.Parse((newHeight / upHeight));
                
newWidth = int.Parse(Int((upWidth * reDuce)));
                
newX = int.Parse(Int(((bmpW - newWidth) 
                                    / 
2)));
                
newY 0;
                
// Picture will be full hieght 
            
}
            
else if ((upWidth == upHeight)) {
                
// square picture 
                
reDuce Decimal.Parse((newHeight / upHeight));
                
newWidth = int.Parse(Int((upWidth * reDuce)));
                
newX = int.Parse(Int(((bmpW - newWidth) 
                                    / 
2)));
                
newY = int.Parse(Int(((bmpH - newHeight) 
                                    / 
2)));
            
}
            
// Create a new image from the uploaded picture using the Graphics class 
            // Clear the graphic and set the background color to white 
            // Use Antialias and High Quality Bicubic to maintain a good quality picture 
            // Save the new bitmap image using 'jpg' picture format and the calculated canvas positioning 
            
Graphics newGraphic Graphics.FromImage(newImg);
            
newGraphic.Clear(Color.White);
            
newGraphic.SmoothingMode Drawing2D.SmoothingMode.AntiAlias;
            
newGraphic.InterpolationMode Drawing2D.InterpolationMode.HighQualityBicubic;
            
newGraphic.DrawImage(Img, newX, newY, newWidth, newHeight);
            
MemoryStream stream = new MemoryStream();
            
newImg.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
            this
.DataSource.YOUR_IMAGE_FIELD_NAME stream.ToArray;
            
//  assign back to picture
            
stream.Close();
            
Img.Dispose();
            
newImg.Dispose();
            
newGraphic.Dispose();
        
}
    }

timt

Avatar / Picture

Iron Speed MVP
The software house that trust built

Registered: 08/06/05
Posts: 1,440
Reply with quote #11 
Great stuff!

Graphics objects and handles are in short supply so as a small improvement to the code I would always wrap in a try catch block with a finally that release the resources otherwise you run the risk of running out of memory/handles etc if the cleanup does not happen due to an earlier error.



__________________
Tim Titchmarsh
Dot Net Architect
UK Iron Speed Consultant MVP
+44 (0)1621 835002
http://www.dotnetarchitect.co.uk
timt@dotnetarchitect.co.uk
notcon

Registered: 03/08/11
Posts: 12
Reply with quote #12 
Hi All,

I have manged to port the resize on upload code accross into C# as detailed below (Ironspeed v8) .  However, the images are just blank rather than resized versions of the upload.  Can anyone advise please? 

It would be great if this functionality was built into Ironspeed along with the ability to choose file system or database storage of the images.

Thanks in advance.

Nathan

====================== CODE BELOW ================

public void SaveButton_Click(object sender, EventArgs args)
        {
           
             //  Click handler for SaveButton.
            //  Customize by adding code before the call or replace the call to the Base function with your own code.
            if (!CategoryImage.HasFile) {
                //original call
                SaveButton_Click_Base(sender, args);
                //original call end
            }
            else if (CategoryImage.HasFile)
            {
               
                string filepath = CategoryImage.PostedFile.FileName;
                string fileExt = System.IO.Path.GetExtension(CategoryImage.FileName).ToLower();
                HttpPostedFile myUpload = CategoryImage.PostedFile;
                if ((fileExt == ".gif")
                            || (fileExt == ".jpg")
                            || (fileExt == ".png")
                            || (fileExt == ".bmp")
                            && (CategoryImage.PostedFile.ContentLength < 500000))
                {
                    try {
                        SaveButton_Click_Base(sender, args);
                    }
                    catch (Exception ex) {
                        CategoryImageLabel.Text = ("ERROR: " + ex.Message.ToString() + "");
                    }
                }
                else {
                    CategoryImageLabel.Text = "Only .gif, .jpg, .png or .bmp files are allowed! Also, images must be less than 500kb.";

                }
           
              // NOTE: If the Base function redirects to another page, any code here will not be executed.
            }
        }


public override void GetUIData() {
        base.GetUIData();
        //  this calls the base apply of the user data
        const int bmpW = 300;
        // New image target width
        const int bmpH = 325;
        // New Image target height
        if (CategoryImage.HasFile) {
            int newWidth = bmpW;
            int newHeight = bmpH;
            byte[] Pic = this.DataSource.CategoryImage;
            //  Convert to image for resizing
            Bitmap Img = null;
            Img = ((Bitmap)(Bitmap.FromStream(new MemoryStream(Pic, 0, (Pic.Length - 1)))));
            Bitmap newImg = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            newImg.SetResolution(72, 72);
            // Get the uploaded image width and height
            int upWidth = Img.Width;
            int upHeight = Img.Height;
            int newX = 0;
            // Set the new top left drawing position on the image canvas
            int newY = 0;
            Decimal reDuce;
            // Keep the aspect ratio of image the same if not 4:3 and work out the newX and newY positions
            // to ensure the image is always in the center of the canvas vertically and horizontally
            if ((upWidth > upHeight)) {
                // Landscape picture
                reDuce = ((newWidth / upWidth));
                newHeight = Convert.ToInt32(upHeight * reDuce);
                newY = Convert.ToInt32((bmpH - newHeight) / 2);
                newX = 0;
                // Picture will be full width
            }
            else if ((upWidth < upHeight)) {
                // Portrait picture
                reDuce = ((newHeight / upHeight));
                newWidth = Convert.ToInt32(upWidth * reDuce);
                newX = Convert.ToInt32((bmpW - newWidth)/2);
                newY = 0;
                // Picture will be full hieght
            }
            else if ((upWidth == upHeight)) {
                // square picture
                reDuce = ((newHeight / upHeight));
                newWidth = Convert.ToInt32(upWidth * reDuce);
                newX = Convert.ToInt32((bmpW - newWidth) / 2);
                newY = Convert.ToInt32((bmpH - newHeight) / 2);
            }
            // Create a new image from the uploaded picture using the Graphics class
            // Clear the graphic and set the background color to white
            // Use Antialias and High Quality Bicubic to maintain a good quality picture
            // Save the new bitmap image using 'jpg' picture format and the calculated canvas positioning
            Graphics newGraphic = Graphics.FromImage(newImg);
            newGraphic.Clear(Color.Beige);
            newGraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            newGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            newGraphic.DrawImage(Img, newX, newY, newWidth, newHeight);
            MemoryStream stream = new MemoryStream();
            newImg.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
            this.DataSource.CategoryImage = stream.ToArray();
             //  assign back to picture
            stream.Close();
            Img.Dispose();
            newImg.Dispose();
            newGraphic.Dispose();
        }
    }


debeerac

Registered: 08/10/10
Posts: 39
Reply with quote #13 
I use IS7 and have this code that works:

//Resize the images to 400x400
                const int bmpW = 400;
                // New image target width
                const int bmpH = 400;
                // New Image target height 
                
                if (Image1.HasFile)
                {
                    int newWidth = bmpW;
                    int newHeight = bmpH;
                    byte[] Pic = this.DataSource.Image1;
                    //  Convert to image for resizing
                    Bitmap Img = null;
                    Img = ((System.Drawing.Bitmap)(Bitmap.FromStream(new MemoryStream(Pic, 0, (Pic.Length - 1)))));
                    Bitmap newImg = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    newImg.SetResolution(72, 72);
                                        //newImg.SetResolution(400, 400);
                    // Get the uploaded image width and height 
                    int upWidth = Img.Width;
                    int upHeight = Img.Height;
                    int newX = 0;
                    // Set the new top left drawing position on the image canvas
                    int newY = 0;
                    Decimal reDuce;
                    // Keep the aspect ratio of image the same if not 4:3 and work out the newX and newY positions 
                    // to ensure the image is always in the center of the canvas vertically and horizontally 
                    if ((upWidth > upHeight))
                    {
                        // Landscape picture 
                        reDuce = Convert.ToDecimal(Convert.ToDecimal(newWidth) / Convert.ToDecimal(upWidth));
                        newHeight = Convert.ToInt32(upHeight * reDuce);
                        //newWidth = 400;
                        newY = Convert.ToInt32((bmpH - newHeight) / 2);
                        newX = 0;
                        // Picture will be full width 
                    }
                    else if ((upWidth < upHeight))
                    {
                        // Portrait picture 
                        reDuce = Convert.ToDecimal(Convert.ToDecimal(newHeight) / Convert.ToDecimal(upHeight));
                        //newHeight = 400;
                        newWidth = Convert.ToInt32(upWidth * reDuce);
                        newX = Convert.ToInt32((bmpW - newWidth) / 2);
                        newY = 0;
                        // Picture will be full hieght 
                    }
                    else if ((upWidth == upHeight))
                    {
                        // square picture 
                        reDuce = Convert.ToDecimal(Convert.ToDecimal(newHeight) / Convert.ToDecimal(upHeight));
                        newWidth = Convert.ToInt32(upWidth * reDuce);
                        newX = Convert.ToInt32((bmpW - newWidth) / 2);
                        newY = Convert.ToInt32((bmpH - newHeight) / 2);
                    }
                    // Create a new image from the uploaded picture using the Graphics class 
                    // Clear the graphic and set the background color to white 
                    // Use Antialias and High Quality Bicubic to maintain a good quality picture 
                    // Save the new bitmap image using 'jpg' picture format and the calculated canvas positioning 
                    Graphics newGraphic = Graphics.FromImage(newImg);
                    newGraphic.Clear(Color.White);
                    newGraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    newGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    newGraphic.DrawImage(Img, newX, newY, newWidth, newHeight);
                    MemoryStream stream = new MemoryStream();
                    newImg.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                    this.DataSource.Image1 = stream.ToArray();
                    //  assign back to picture
                    stream.Close();
                    Img.Dispose();
                    newImg.Dispose();
                    newGraphic.Dispose();
                }

The code published on the other replies in this tread have a problem when calculating the value of reDuce, e.g.  reDuce = Convert.ToDecimal(Convert.ToDecimal(newWidth) / Convert.ToDecimal(upWidth));
The problem seems to be with dividing integers that must result in a decimal.  I changed that bit and it now works fine.

Amanda
notcon

Registered: 03/08/11
Posts: 12
Reply with quote #14 
Thanks Amanda.

I'll try it now.

Nathan

notcon

Registered: 03/08/11
Posts: 12
Reply with quote #15 
Amanda....you star!!  Thanks so much.

So how do we go about turning this into some sort of control that can be applied to any selected image upload field on any page?

I really think that this facility should be built into Ironspeed.  Along with the ability to specify hieghts/widths, image quality, whether the image is stored in the database or the file system, thumbnail creation if file system etc.  I have posted a request.

Thanks again.

Nathan
Previous Topic | Next Topic
Print
Reply

Quick Navigation:

Download Iron Speed Designer
  Support   Company Info  
 

Privacy Statement
Powered by Website Toolbox - Create a Website Forum Hosting, Guestbook Hosting, or Website Chat Room for your website.