rootpanthera
rootpanthera

Reputation: 2771

Crop images at runtime ASP.NET

I'm showing images on my webpage. Since images are various sizes, I would like to crop them (possibly from the center). I want to crop them at runtime.

I'm using datalist and img tag to show images from certain folder. Is there any way to do this ?

EDIT:

If this is the original image

enter image description here

I want to crop it for certain amount of pixles, like in this case: 220x160

enter image description here

Upvotes: 0

Views: 1199

Answers (2)

Justinas Kanguras
Justinas Kanguras

Reputation: 128

public Bitmap CropCenter(Bitmap src, int targetWidth, int targetHeight) 
{
    int x = src.Width / 2 - targetWidth / 2;
        int y = src.Height / 2 - targetHeight / 2;

        Rectangle area = new Rectangle(x, y, targetWidth, targetHeight);

        return src.Clone(area, src.PixelFormat);
}

Pass source bitmap and enter desired width, height to crop out of the center of img also some checks of targetWidth, targetHeight should happen to be sure that they are smaller than img itself.

EDIT: As SynerCoder mentioned you also need to add reference System.Windows.Drawing to your project.

Upvotes: 1

lightbricko
lightbricko

Reputation: 2709

Use ImageResizer for this, it seems like a better approach than (re-)writing the code yourself.

Nuget package: http://www.nuget.org/packages/ImageResizer/

Simple features like cropping are free (but some other features are not free).

Upvotes: 0

Related Questions