PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 27, 2022

[FIXED] How to crop a cross rectangle from an image using c#?

 July 27, 2022     c#, crop, image-processing, image-rotation     No comments   

Issue

I want to get some specific parts of an image so I'm cropping the images. However, when I want to get a part that is not parallel to the image, I rotate the image and crop afterwards.

I don't want to rotate the image and crop a parallel rectangle. What I want is, without rotating the image, to crop a rectangle with an angle from the image.

Is there any way to do that?

I think I couldnt express myself well enough. This is what I want to do: example picture.

Assume the red thing is a rectangle :) I want to crop that thing out of image. After cropping it doesn't need to be angeled. So mj can lie down.


Solution

This method should perform what you asked for.

public static Bitmap CropRotatedRect(Bitmap source, Rectangle rect, float angle, bool HighQuality)
{
    Bitmap result = new Bitmap(rect.Width, rect.Height);
    using (Graphics g = Graphics.FromImage(result))
    {
        g.InterpolationMode = HighQuality ? InterpolationMode.HighQualityBicubic : InterpolationMode.Default;
        using (Matrix mat = new Matrix())
        {
            mat.Translate(-rect.Location.X, -rect.Location.Y);
            mat.RotateAt(angle, rect.Location);
            g.Transform = mat;
            g.DrawImage(source, new Point(0, 0));
        }
    }
    return result;
}

usage (using your MJ example):

Bitmap src = new Bitmap("C:\\mjexample.jpg");
Rectangle rect = new Rectangle(272, 5, 100, 350);
Bitmap cropped = CropRotatedRect(src, rect, -42.5f, true);


Answered By - Rotem
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing