Thursday, July 30, 2009

Resizing images without loss of quality in sharepoint

Let’s see the code that makes clean resizing. This code doesn’t use GetThumbnailImage method and operates therefore on full size image. Also you can see that this code tries to save as much quality as possible.


--------------------------------------------------------------------------------

public string ResizeImage(Stream fromStream,string fileName,int newWidth, int newHeight )
{

System.Drawing.Image image = System.Drawing.Image.FromStream(fromStream);

Bitmap thumbnailBitmap = new Bitmap(newWidth, newHeight);


Graphics thumbnailGraph = Graphics.FromImage(thumbnailBitmap);

thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;

thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;

thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;



Rectangle imageRectangle = new Rectangle(0, 0, newWidth, newHeight);

thumbnailGraph.DrawImage(image, imageRectangle);



thumbnailBitmap.Save(Server.MapPath(@"/_layouts/images/" + fileName), ImageFormat.Jpeg);



thumbnailGraph.Dispose();

thumbnailBitmap.Dispose();

image.Dispose();

return "../../_layouts/images/" + fileName;

}
You have call your newly created method as follows
SPList lstEvents = web.Lists["Events"];
int id=10;
SPListItem item = lstEvents.GetItemById(id);

string path=ResizeImage(item.File.OpenBinaryStream(), "40_40_resized_image.jpg", 40, 40)