There are some times when we might want to check /restrict the height and width of Image before uploading to SharePoint Images Library
to address this situation , I have tried creating a event receiver which checks the width and height of image which we are uploading from file system , and If found big then resize to 200x200
public override void ItemAdded(SPItemEventProperties properties)
{
int _imageWidth = 0;
int _imageHeight = 0;
if (properties.ListTitle.ToLower().Equals("images"))
{
try
{
string _width = properties.ListItem.File.Properties["vti_lastwidth"].ToString();
string _height = properties.ListItem.File.Properties["vti_lastheight"].ToString();
if (Int32.TryParse(_width, out _imageWidth) && Int32.TryParse(_height, out _imageHeight))
{
if (_imageWidth > 200 && _imageHeight > 200)
{
SPFile _imageFile = properties.ListItem.File;
MemoryStream _inputStream = new MemoryStream(_imageFile.OpenBinary(), true);
MemoryStream _outputStream = new MemoryStream();
Image _resizedImage = Image.FromStream(_inputStream).GetThumbnailImage(200, 200, null, IntPtr.Zero);
_resizedImage.Save(_outputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
_imageFile.SaveBinary(_outputStream, false);
_imageFile.CheckOut();
_imageFile.Update();
_imageFile.CheckIn("Image Resized");
if (properties.ListItem.ParentList.EnableMinorVersions)
{
properties.ListItem.File.Publish("ImagePublished");
}
if (properties.ListItem.ParentList.EnableModeration)
{
properties.ListItem.File.Approve("ImageApproved");
}
}
}
}
catch (Exception ex)
{
throw new SPException("Error: " + ex.StackTrace);
}
}
}