Resize or rotate image in SharePoint library
16/01/2018 10:36
using System.Drawing;
...
public static string ResizeImageItem(SPListItem item)
{
var message = Constants.Error;
var isImage = true;
if (isImage)
{
var file = item.File;
var parentFolder = item.Web.GetFolder(item[FieldNames.FileDirRef].ToString());
var size = 800; //px
using (Stream fileStream = file.OpenBinaryStream())
{
var image = Image.FromStream(file.OpenBinaryStream());
var format = image.RawFormat;
var originalSize = image.Size;
int originalWidth = image.Width;
int originalHeight = image.Height;
float percentWidth = (float)size / (float)originalWidth;
float percentHeight = (float)size / (float)originalHeight;
float percent = percentHeight < percentWidth ? percentHeight : percentWidth;
var newWidth = (int)(originalWidth * percent);
var newHeight = (int)(originalHeight * percent);
if (originalWidth <= newWidth || originalHeight <= newHeight) //resize is not needed
{
message = "Picture resize not needed";
}
else
{
Bitmap resizedImage = new Bitmap(newWidth, newHeight);
var graphics = Graphics.FromImage((Image)resizedImage);
graphics.InterpolationMode = InterpolationMode.High;
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
fileStream.Close();
SaveImageToFolder(file.Name, parentFolder, resizedImage, format);
message = Constants.Ok;
}
}
}
else
message = "Selected item is not image.";
return message;
}
public static string RotateImageItem(SPListItem item)
{
var message = Constants.Error;
var isImage = true;
if (isImage)
{
var file = item.File;
var parentFolder = item.Web.GetFolder(item[FieldNames.FileDirRef].ToString());
using (Stream fileStream = file.OpenBinaryStream())
{
var image = Image.FromStream(file.OpenBinaryStream());
var format = image.RawFormat;
var orientation = RotateFlipType.Rotate90FlipNone;//rotate right
image.RotateFlip(orientation);
fileStream.Close();
SaveImageToFolder(file.Name, parentFolder, image, format);
message = Constants.Ok;
}
}
else
message = "Selected item is not image.";
return message;
}
private static void SaveImageToFolder(string filename, SPFolder folder, Image image, ImageFormat format)
{
using (var ms = new MemoryStream())
{
image.Save(ms, format);
byte[] bytes = ms.ToArray();
folder.Files.Add(filename, bytes, true);
folder.Update();
}
}