Create a bitmap from another bitmap


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!
riceman0Asked:
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.

Mike TomlinsonMiddle School Assistant TeacherCommented:
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

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
riceman0Author Commented:

You rock.
0
Mike TomlinsonMiddle School Assistant TeacherCommented:
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.
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
Visual Basic.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.