0

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

rootpanthera
  • 2,731
  • 10
  • 33
  • 65
  • how do you want to crop them? to a certain format (4:3, 16:9, 16:10 etc) or do you wish to crop them to a certain amount of pixels (400px*400px in the center etc)? – SynerCoder Dec 14 '13 at 12:15
  • Could you just go for the cheap solution; use your images as background-images in a 220x160 div? That would make them appear cropped while still having the cached client-side in full size for the details page. – sisve Dec 14 '13 at 12:46

2 Answers2

1
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.

  • 1
    Good answer, but maybe a good idea to tell @rootpanthera what references he needs to add. He is using asp.net webforms, so System.Windows.Drawing isn't a standard references (I believe it is drawing, correct me if im wrong) – SynerCoder Dec 14 '13 at 12:24
  • also.. How to pass bitmap to this method? I've datalist and image tag inside.. And what are "cropArea" and "sourceImage" variables? – rootpanthera Dec 14 '13 at 12:27
  • I suggest you to resize them during upload as this will decrease need of CPU a lot, instead of resizing them on each request. Or you could do that on client side using CSS here is an example http://stackoverflow.com/questions/11552380/how-to-automatically-crop-and-center-an-image – Justinas Kanguras Dec 14 '13 at 12:47
0

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).

lightbricko
  • 2,649
  • 15
  • 21