We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

Create a bitmap from another bitmap

riceman0
riceman0 asked
on
Medium Priority
239 Views
Last Modified: 2010-04-23

What's the easiest way to create a bitmap object that contains an offset rectangle within an existing bitmap?  I thought I had a (long) method using BitBlt, but turns out if didn't work...

Thanks!
Comment
Watch Question

High School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
CERTIFIED EXPERT
Top Expert 2009
Commented:
Like this?...

        Dim sourceBmp As Bitmap = Image.FromFile("c:\someImage.bmp")
        Dim sourceRect As New Rectangle(100, 50, 75, 25)

        Dim destBmp As New Bitmap(sourceRect.Width, sourceRect.Height)
        Dim g As Graphics = Graphics.FromImage(destBmp)
        g.DrawImage(sourceBmp, New Rectangle(0, 0, destBmp.Width, destBmp.Height), sourceRect, GraphicsUnit.Pixel)
        g.Dispose()

        ' do something with destBmp...
        destBmp.Save("c:\someOtherImage.bmp")
        PictureBox1.Image = destBmp

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

Commented:

You rock.
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
CERTIFIED EXPERT
Top Expert 2009

Commented:
Just FYI, when you load an image using Image.FromFile(), the actual image file remains LOCKED until you dispose of the Bitmap class (or Image class) that opened it.

So "c:\someImage.bmp" will be locked until "sourceBmp" is explicitly disposed of or goes out of scope.

You can load an image without locking the file by first using Image.FromFile(), and then creating another Bitmap instance from the first Bitmap instance and then Disposing of the first Bitmap:

    Dim bmpA As Bitmap = Image.FromFile("c:\someImage.bmp") ' file is locked
    Dim bmpB As Bitmap = New Bitmap(bmpA) ' create a copy in memory
    bmpA.Dispose() ' file is unlocked now

Now you can work with bmpB and "c:\someImage.bmp" will NOT be locked because we disposed of bmpA.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.