Search code examples
c#bitmapcut

c# cut image in specific size in memory without save file


i have colde like this :

 Bitmap bmp = new Bitmap(width, height);

I just take a capture of window. Now i want just resize this captured bitmap (bmp). How can i cut my bmp for example

  RECT rt = new RECT();
        GetWindowRect(hwnd1, out rt);
        Int32 width = rt.Right - rt.Left;
        Int32 height = rt.Bottom - rt.Top;
        int leftttt = rt.Left + (width - 202);
        int width2 = rt.Right - leftttt;

//              // I want cut like this :
//
      //  in x=lefttt  y = rt.Top    Size ( width2,height)

And later i can easy save file to check my results by: (but won't do that only for check)

    bmp.Save(@"D:\test.jpg", ImageFormat.Jpeg);

EDIT: I Want just cut not resize . When i do code :

var graph = Graphics.FromImage(scren_kurwa.Image);

graph.DrawImage(bmp.Image, 10, 10, 200, 200);

And i save it its just override my bmp screen and just take a capture just in smaller version.

I just want to cut for examaple i want show only 1/4 of width this screen and save it to file. ( just save 1/4 width not more).

EDIT 2 :

graph.CopyFromScreen(leftttt, rt.Top, 0, 0, new Size(width2, height), CopyPixelOperation.SourceCopy);

This code above just doing what i want but i don't want again copy from screen i want copy this from bmp captured before.

Please be patient for newbies . I searched forums and just can't find solution. Thank you.

EDIT 3 I just did how you wrote :

        Rectangle cropRect = new Rectangle(100,100,100,100);
        Bitmap bmp1 = new Bitmap(bmp1.Image);
        bmp1.Clone(cropRect, bmp.PixelFormat);


        bmp1.Save(@"D:\xdddde.jpg", ImageFormat.Jpeg);

But it don't cut an image just display the same as i had bmp.


Solution

  • This should work for you:

    Bitmap cuttedImage;
    
    using(Bitmap originalImage = new Bitmap("filePathName"))
    {
       Rectangle cropRect = new Rectangle(...);
    
       cuttedImage = originalImage .Clone(cropRect, originalBmp.PixelFormat);
    }
    
    cuttedImage.Save("filePathName", ImageFormat.Jpeg);
    cuttedImage.Dispose();
    

    Note that this will create a shallow copy of your Bitmap. In your case that does not seem to be a problem, but keep that in mind.

    Also make sure to check the MSDN documentation for exception handling. Either check that the rectangle is bigger than 0 and not bigger than the original image beforehand or catch the exceptions.