Question

Image resizing

Asked by: jorgemgonzalez

I'm in serious need of advise on this one.

I have a code that resizes jpeg images to 200px wide or 150px high depending on portrait or landscape attributes, that I have accomplished without problems, now, obviously the target size should be 200px wide by 150px high. Therefore I need some space around the images to accomplish that requirement, meaning that I need every resulting image to be 200px wide by 150px high without cropping or distorting the originals.

It would be great if the space around the image could be of a color of choice.

Please help.

Thanks in advance.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-07-04 at 11:48:22ID24544111
Tags

Visual Studio

Topic

Microsoft Visual Basic.Net

Participating Experts
3
Points
500
Comments
10

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Free JPEG/GIF resize, crop and compress component
    Hi Is there any free activeX component that can be used from asp to resize, crop and compress images? Regards Claus Elmann
  2. Resize/Crop jpeg image
    Hi! I have a TImage that uses LoadFromFile() to load a jpeg image. I have a method for checking the size of the image (e.g. max 640x480) and want to change the the image size to the max size and then use SaveToFile() to save that image again. The reason for this is to make th...
  3. Image crop and resize on upload
    Hello, Searching in experts-exhange answers I found the php part of the following code(and modify it a bit): $tpath = "C:/AppServ/www/personal_website/03/resize/uploads";//thumbnails path //check for uploaded file from form if ($_FILES['image1'] !...
  4. Error in Cropping & Resize Image
    We have an GDI Error when Cropping and resizing an image. All permissions in the folder have been granted including the ASP.NET user. When We run it the first time it works just fine; however when we try it again it will not work. Any ideas. Thanks in Advance

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: AfricansPosted on 2009-07-04 at 13:36:29ID: 24777929

In ASP.NET or VB.NET Windows Application?

 

by: abelPosted on 2009-07-04 at 13:41:20ID: 24777945

In the code below (I know, it is C#, I'll come to that) that I just created and tested, it does exactly what you want. The key is the PicureBox_Paint event and the drawScaledImage. The background color is done by the eraseImage method.

To make this work, create a form, place a button, a picturebox and a openfiledialog on it. On the buttonclick event you assign the filename of the image to a field, m_image_filename. The picturebox will be redrawn (.Invalidate()) and the drawScaledImage is called. The method DrawImage does the scaling for you, the hard part is actually the calculation of the various rectangles. I kept the code clean and simple as far as I could, the result is that it is not very optimized. But it should do for this basic task.

In my next post I'll give an update in VB code of the same.

-- Abel --

public partial class ResizeKeepRatio : Form
{
    private string m_image_filename = null;
 
    public ResizeKeepRatio()
    {
        InitializeComponent();
    }
 
    private void button1_Click(object sender, EventArgs e)
    {
        openFileDialog1.ShowDialog();
        m_image_filename = openFileDialog1.FileName;
        pictureBox1.Invalidate();
    }
 
    private void eraseImage(Graphics graph)
    {
        Rectangle rect = new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height);
        graph.DrawRectangle(new Pen(Brushes.Orange, (float) rect.Width), rect);
    }
 
    private void drawScaledImage(Graphics graph)
    {
        if(m_image_filename == null)
            return;
 
        Bitmap bmp = new Bitmap(m_image_filename);
        Rectangle sourceRect = new Rectangle(0, 0, bmp.Width, bmp.Height);
        Rectangle drawAreaRect = new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height);
        Rectangle targetRect;
 
        // determine whether to resize horizontally or vertically
        // based on the ratio width/height of source image and target rectangle
        double sourceRatio = (double)sourceRect.Height / (double)sourceRect.Width;
        double targetRatio = (double)drawAreaRect.Height / (double)drawAreaRect.Width;
        double drawRatio;
        if (sourceRatio > targetRatio)
            drawRatio = (double) drawAreaRect.Height / (double) sourceRect.Height;
        else
            drawRatio = (double) drawAreaRect.Width / (double) sourceRect.Width;
 
        // calculate target rectangle and center
        targetRect = new Rectangle(
            (int) ((drawAreaRect.Width - drawRatio * sourceRect.Width) / 2), 
            (int) ((drawAreaRect.Height - drawRatio * sourceRect.Height) / 2), 
            (int) (drawRatio * sourceRect.Width), 
            (int) (drawRatio * sourceRect.Height));
 
        // draw the image
        graph.DrawImage(bmp, targetRect);
    }
 
    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        eraseImage(e.Graphics);
        drawScaledImage(e.Graphics);
    }
 
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:

Select allOpen in new window

 

by: abelPosted on 2009-07-04 at 13:43:52ID: 24777957

The VB code is a bit less readable, as is often with calculation code (matter of taste, of course), but here you go (courtesy to http://www.developerfusion.com/tools/convert/csharp-to-vb/):

Public Partial Class ResizeKeepRatio
    Inherits Form
    Private m_image_filename As String = Nothing
    
    Public Sub New()
        InitializeComponent()
    End Sub
    
    Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
        openFileDialog1.ShowDialog()
        m_image_filename = openFileDialog1.FileName
        pictureBox1.Invalidate()
    End Sub
    
    Private Sub eraseImage(ByVal graph As Graphics)
        Dim rect As New Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height)
        graph.DrawRectangle(New Pen(Brushes.Orange, CSng(rect.Width)), rect)
    End Sub
    
    Private Sub drawScaledImage(ByVal graph As Graphics)
        If m_image_filename Is Nothing Then
            Exit Sub
        End If
        
        Dim bmp As New Bitmap(m_image_filename)
        Dim sourceRect As New Rectangle(0, 0, bmp.Width, bmp.Height)
        Dim drawAreaRect As New Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height)
        Dim targetRect As Rectangle
        
        ' determine whether to resize horizontally or vertically '
        ' based on the ratio width/height of source image and target 'rectangle
        Dim sourceRatio As Double = CDbl(sourceRect.Height) / CDbl(sourceRect.Width)
        Dim targetRatio As Double = CDbl(drawAreaRect.Height) / CDbl(drawAreaRect.Width)
        Dim drawRatio As Double
        If sourceRatio > targetRatio Then
            drawRatio = CDbl(drawAreaRect.Height) / CDbl(sourceRect.Height)
        Else
            drawRatio = CDbl(drawAreaRect.Width) / CDbl(sourceRect.Width)
        End If
        
        ' calculate target rectangle and center '
        targetRect = New Rectangle(CInt(((drawAreaRect.Width - drawRatio * sourceRect.Width) / 2)), CInt(((drawAreaRect.Height - drawRatio * sourceRect.Height) / 2)), CInt((drawRatio * sourceRect.Width)), CInt((drawRatio * sourceRect.Height)))
        
        ' draw the image '
        graph.DrawImage(bmp, targetRect)
    End Sub
    
    Private Sub pictureBox1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs)
        eraseImage(e.Graphics)
        drawScaledImage(e.Graphics)
    End Sub
    
End Class
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:

Select allOpen in new window

 

by: abelPosted on 2009-07-04 at 13:55:04ID: 24777991

In the screenshot you can see one of Window's Vista's sample pictures with a green border. It is a test with the VB code because I wasn't sure if would compile. Don't forget to add the click and paint events! (I did). You can use a ColorDialog for picking the color, which goes into line 17 above.

Happy coding with it! ;-)

  • ScreenShot419.png
    • 231 KB

    forest with green bars top/bottom, automatic resize without ratio change

    forest with green bars top/bottom, automatic resize without ratio change
 

by: Idle_MindPosted on 2009-07-04 at 15:14:12ID: 24778184

I see from one your PAQs that you have VB2008.  You could "cheat" and just use a PictureBox with the SizeMode set to Zoom.

Simple example having a PictureBox and two Buttons.  Double click the PictureBox to change the color.  Click Button1 to open an image.  Click Button2 to save the Image.

Public Class Form1
 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        PictureBox1.Size = New Size(200, 150)
        PictureBox1.BackColor = Color.DarkGreen
        PictureBox1.SizeMode = PictureBoxSizeMode.Zoom
    End Sub
 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Using ofd As New OpenFileDialog
            If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then
                ofd.Title = "Open Image"
                ofd.Filter = "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.* "
                Try
                    Using fs As New System.IO.FileStream(ofd.FileName, IO.FileMode.Open)
                        PictureBox1.Image = Image.FromStream(fs)
                    End Using
                Catch ex As Exception
                    MessageBox.Show("File: " & ofd.FileName & vbCrLf & vbCrLf & ex.Message, "Error Opening Image", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End Try
            End If
        End Using
    End Sub
 
    Private Sub PictureBox1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles PictureBox1.DoubleClick
        Using cd As New ColorDialog
            If cd.ShowDialog = Windows.Forms.DialogResult.OK Then
                PictureBox1.BackColor = cd.Color
            End If
        End Using
    End Sub
 
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        If Not IsNothing(PictureBox1.Image) Then
            Using sfd As New SaveFileDialog
                sfd.Title = "Save Image"
                sfd.Filter = "JPEG (*.JPG)|*.JPG|Bitmap (*.BMP)|*.BMP|GIF (*.GIF)|*.GIF"
                If sfd.ShowDialog = Windows.Forms.DialogResult.OK Then
                    Dim bmp As New Bitmap(PictureBox1.ClientSize.Width, PictureBox1.ClientSize.Height)
                    PictureBox1.DrawToBitmap(bmp, PictureBox1.ClientRectangle)
                    Try
                        Select Case System.IO.Path.GetExtension(sfd.FileName).ToUpper
                            Case ".BMP"
                                bmp.Save(sfd.FileName, Drawing.Imaging.ImageFormat.Bmp)
 
                            Case ".JPG"
                                bmp.Save(sfd.FileName, Drawing.Imaging.ImageFormat.Jpeg)
 
                            Case ".GIF"
                                bmp.Save(sfd.FileName, Drawing.Imaging.ImageFormat.Gif)
 
                        End Select
                    Catch ex As Exception
                        MessageBox.Show("File: " & sfd.FileName & vbCrLf & vbCrLf & ex.Message, "Error Saving Image", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    End Try
                End If
            End Using
        End If
    End Sub
 
End Class
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:

Select allOpen in new window

 

by: jorgemgonzalezPosted on 2009-07-04 at 18:46:13ID: 24778554

Thank you experts for your fast reply.

I created a separate project for each solution and copied the code exactly as posted. For some reason Abel's one did not work at all after clicking button1. Is there something missing?

Idle Mind's (And I.ve always said that mind is whatever but idle) worked like a charm, I love the idea.

Now, what I missed in my question (my apologies) is that the code I have (And need) is for  resizing ingmultiple images, (For ---> Next) actually all the images in a folder via folder browser dialog, I have no picture boxes in my form!

Attached is part of the code so you can have a better idea.

Is there a way of getting the same result without the PicBox?

Otherwise please advise on how to load - unload the images on the PicBox for each file in directory.

Dim bp As New Bitmap(newSize.Width, newSize.Height)
                Dim g As Graphics = Graphics.FromImage(bp)
 
                ' Controls the quality of the image
                g.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
                g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
                g.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality
 
                Dim rect As New Rectangle(0, 0, newSize.Width, newSize.Height)
                g.DrawImage(currentImage, rect, 0, 0, currentImage.Width, currentImage.Height, GraphicsUnit.Pixel)
 
                ' Copy Meta from old image to new image
                For Each pItem As System.Drawing.Imaging.PropertyItem In currentImage.PropertyItems
                    bp.SetPropertyItem(pItem)
                Next
                newFileName = "Thumb_" & file.ToString
                ' Saves as jpeg
                bp.Save(NewDir & "\Thumbnails\" & newFileName, Imaging.ImageFormat.Jpeg)

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:

Select allOpen in new window

 

by: Idle_MindPosted on 2009-07-04 at 19:39:54ID: 24778692

You can actually use my concept with a dynamic PictureBox that is never even visible to the user...

    Dim pb As New PictureBox
    pb.Size = New Size(200, 150)    
    pb.BackColor = Color.DarkGreen
    pb.SizeMode = PictureBoxSizeMode.Zoom

Then iterate thru your files and use "pb" in code just like in my example above.

 

by: jorgemgonzalezPosted on 2009-07-04 at 22:13:45ID: 24778882

Thanks a million Idle_Mind!

 

by: jorgemgonzalezPosted on 2009-07-04 at 22:16:19ID: 31599804

Thanks again!

 

by: abelPosted on 2009-07-05 at 02:13:18ID: 24779277

>  For some reason Abel's one did not work at all after clicking button1. Is there something missing?

You just needed to add the click event and the paint event in the properties of the button and the picture box.

> Is there a way of getting the same result without the PicBox?

you can draw on almost anything using my method, but I see you already chosen Idle's, which good, because it is simpler. I just didn't even thought of it while working the solution out. Was a nice exercise regardless ;-)

-- Abel --

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...