In this example we're going to create a visual webpart that allows a user to upload an image to SharePoint. During the upload process, the image dimensions are checked, and if the image's width or height exceeds 300px, we'll resize the image so that the maximum width/height is 300px. The resizing process will keep the images width/height ratio the same as the original image selected. After uploading the image to SharePoint, we'll display the image on the page in an asp:image control. Example:
1. Open Visual Studio (this example has been created in Visual Studio 2012) 2. Create a new farm scoped Empty SharePoint project 3. Add a new visual webpart to the project 4. Add the following additional references to the project
System.Core System.Drawing
5. Add the following using statements
using
System;
System.ComponentModel;
System.Drawing;
System.Drawing.Drawing2D;
System.Drawing.Imaging;
System.IO;
System.Web.UI.WebControls.WebParts;
Microsoft.SharePoint;
Microsoft.SharePoint.Utilities;
<
SharePoint:CssLink
runat
=
"server"
ID
"mycorestyles"
DefaultUrl
"/_layouts/incestyles/core.css"
></
>
div
class
"container"
"row"
"span8 rowpad"
span
>Click browse to locate a file to upload, then click Upload to save it to SharePoint.</
</
asp:Label
"userMessage"
Text
""
asp:FileUpload
"fileBrowser"
/>
asp:Button
"uploadFile"
"Upload"
OnClick
"UploadFileClick"
asp:Image
"previewImage"
Visible
"false"
The webpart will look like this when it loads;
...and like this after you upload an image (hopefully with a different picture!) 7. In the visual webparts code file, add the following code (the OnClick event and two helper methods for resizing the image). In the uploadFile button's OnClick event, we check a file has been selected, is in the right format, and is within size restrictions, before finally uploading it to a memory stream. Once we have the image as a memory steam, we can resize the image to our required width/height maximums (if the selected image has exceeded our maximums width/height).
Note that elevating permissions, error handling and validation have been omitted to keep the example short.
protected
void
UploadFileClick(
object
sender, EventArgs e)
{
try
userMessage.Text = String.Empty;
SPWeb web = SPContext.Current.Site.RootWeb;
previewImage.ImageUrl =
null
;
previewImage.Visible =
false
if
(!fileBrowser.HasFile)
userMessage.Text =
"Please select a file before clicking upload."
return
}
//Check the file is less than 4MB
int
fileSize = fileBrowser.PostedFile.ContentLength;
(fileSize > 4000000)
userMessage.Text += String.Format(
"File Size Exceeds 4MB. Choose a smaller file."
);
String imageFileExtension = Path.GetExtension(fileBrowser.FileName);
//Check the user has selected a jpg image
(imageFileExtension ==
|| imageFileExtension.ToLower() !=
".jpg"
)
userMessage.Text +=
"The file you have selected is not in the right format. Please use a jpg image."
var imageFileData = fileBrowser.FileBytes;
(var imageFileStream =
new
MemoryStream())
imageFileStream.Write(imageFileData, 0, imageFileData.Length);
//Before uploading the image to SharePoint, lets make sure resize the image if the width or height are greater than 300px.
var imagePreview = ResizeImage(imageFileStream, 300, 300);
SPList listExists = web.Lists.TryGetList(
"picturelibrary"
SPUtility.ValidateFormDigest();
(listExists ==
//...
var fileName = fileBrowser.FileName.Replace(
" "
,
"-"
var urlpreview = String.Format(
"{0}/picturelibrary/{1}"
, web.Url, fileName);
web.AllowUnsafeUpdates =
true
web.Files.Add(urlpreview, imagePreview,
previewImage.ImageUrl = urlpreview;
catch
(Exception exception)
//..Do something
public
byte
[] ResizeImage(Stream fileData,
maxwidth,
maxheight)
(var image =
Bitmap(fileData))
adjustedWidth = image.Width;
adjustedHieght = image.Height;
//Check the image is less than the maxwidth. If not, resize the image dimensions.
(adjustedWidth > maxwidth)
decimal
ratio = Decimal.Divide(maxwidth, adjustedWidth);
adjustedWidth = maxwidth;
adjustedHieght = Convert.ToInt32(Decimal.Multiply(adjustedHieght, ratio));
//Now that we've adjusted the width, check the hieght is below the maximum hieght value
(adjustedHieght > maxheight)
ratio = Decimal.Divide(maxheight, adjustedHieght);
adjustedHieght = maxheight;
adjustedWidth = Convert.ToInt32(Decimal.Multiply(adjustedWidth, ratio));
var resizedImage =
Bitmap(adjustedWidth, adjustedHieght);
var g = Graphics.FromImage(resizedImage);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.SmoothingMode = SmoothingMode.HighQuality;
g.CompositingQuality = CompositingQuality.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.FillRectangle(Brushes.White, 0, 0, adjustedWidth, adjustedHieght);
g.DrawImage(image, 0, 0, adjustedWidth, adjustedHieght);
var ms =
MemoryStream();
const
quality = 90;
var encoderParameters =
EncoderParameters(1);
encoderParameters.Param[0] =
EncoderParameter(Encoder.Quality, (
long
)quality);
resizedImage.Save(ms, GetImageCodeInfo(
"image/jpeg"
), encoderParameters);
ms.Position = 0;
var data =
[ms.Length];
ms.Read(data, 0, (
)ms.Length);
data;
static
ImageCodecInfo GetImageCodeInfo(
string
mimeType)
ImageCodecInfo[] imageEncoders = ImageCodecInfo.GetImageEncoders();
foreach
(ImageCodecInfo imageCodeInfo
in
imageEncoders)
(imageCodeInfo.MimeType.Equals(mimeType, StringComparison.OrdinalIgnoreCase))
imageCodeInfo;
Gokan Ozcifci edited Revision 11. Comment: title and content and content added
Matthew Yarlett edited Revision 12. Comment: The title has been changed to SharePoint 2013 - this article was originally written for SharePoint 2010 (and was tagged with SharePoint 2010 and SharePoint 2013). Tags have been removed that shouldn't have been removed (as per Wiki guidelines social.technet.microsoft.com/.../145.wiki-how-to-contribute-content-to-technet-wiki.aspx).
Matthew Yarlett edited Revision 10. Comment: Minor change to code example (in UploadClick)
Matthew Yarlett edited Revision 9. Comment: This article was originally written for SharePoint 2010. I've removed 2013 from the title and added the SharePoint 2013 tag.
kuthodsapon edited Revision 8. Comment: ขอบคุณที่ให้คำแนะนำ เสียใจทีตอบช้า
Gokan Ozcifci edited Revision 6. Comment: title
Matthew Yarlett edited Revision 2. Comment: Cut/Pasted the code blocks back into the "Format Code Block" editor so that it applies the code styles correctly.
Matthew Yarlett edited Revision 1. Comment: Minor changes to formatting and grammar.
Matthew Yarlett edited Original. Comment: Added an extra image, checked code formatting
Congratulations on winning the gold! blogs.technet.com/.../technet-guru-awards-june-2013.aspx
Matthew, I featured your article on MSDN Blogs: blogs.msdn.com/.../sharepoint-guru-uploading-and-resizing-images-to-a-sharepoint-picture-library-via-a-webpart.aspx
Congratulations on being featured on the home page of TechNet Wiki: social.technet.microsoft.com/.../default.aspx
Congrats, Nice article...
Thanks Ed! Thanks Glenn!
I also featured your article on the Wiki Ninjas blog: blogs.technet.com/.../june-sharepoint-guru-matthew-yarlett-brings-us-quot-uploading-and-resizing-images-to-a-sharepoint-picture-library-via-a-webpart-quot.aspx