ImageResizer  3.4.0
 All Classes Namespaces Functions Variables Enumerations Enumerator Properties Events
Public Member Functions | Properties | List of all members
ImageResizer.ImageUploadHelper Class Reference

Public Member Functions

 ImageUploadHelper (Config c)
 
string GetExtension (string path)
 Parses the file extension from the path and returns it. If it contains a multi-segment extension like .txt.zip, only "zip" will be returned. More...
 
string NormalizeExtension (string extension)
 Lowercases and normalizes some common extension aliases (jpeg->jpg, tiff-tif). Does not filter out non-image extensions! More...
 
bool IsExtensionWhitelisted (string ext, string[] whitelistedFormats=null)
 Returns true if the given extension is whitelisted. More...
 
string GetWhitelistedExtension (Stream image=null, string originalPath=null, string[] whitelistedFormats=null)
 Uses stream signatures first, then the original path, to detect the appropriate normalized image extension. Returns null if extension (or no whitelisted extension) is found. More...
 
bool IsUploadedFileAnImage (object uploadFile, string[] whitelistedFormats=null)
 Returns true if the uploaded file is identified as an image (looks for the image signature, falling back to the user-provided filename). More...
 
int[] GetImageSize (object s)
 Returns the [width,height] of the first frame/page of the image. May return null or throw exceptions. More...
 
string SaveUploadedFileSafely (string baseDir, object uploadFile, string unrecognizedImageExtension=".unknown", string[] whitelistedFormats=null)
 Returns the name used for the file, without any path information. Name will be in "guid.ext" form. Will create any intermediate directories required. More...
 
string GenerateSafeImageName (Stream image=null, string originalPath=null, string unrecognizedImageExtension=".unknown", string[] whitelistedFormats=null)
 Generates a safe name for your image in the form "guid.ext". Uses stream signatures first, then the path to determine the appropriate image extension. You can provide your own whitelist of extensions if desired; this defaults to the extensions supported by the currently installed set of plugins. More...
 
FileSignature GuessFileTypeBySignature (Stream s)
 Tries to guess the file type of the given stream by the byte signature. Typically more reliable than file extensions - users constantly rename file extensions expecting it to change the actual encoding. Throws Argument exception if stream isn't seekable and readable. Returns null if there were no matches. Make sure the current position of the stream is at the beginning of the file, or you will get no results. Returns the stream to its original position More...
 

Properties

static ImageUploadHelper Current [get]
 

Detailed Description

Definition at line 13 of file ImageUploadHelper.cs.

Member Function Documentation

string ImageResizer.ImageUploadHelper.GenerateSafeImageName ( Stream  image = null,
string  originalPath = null,
string  unrecognizedImageExtension = ".unknown",
string[]  whitelistedFormats = null 
)
inline

Generates a safe name for your image in the form "guid.ext". Uses stream signatures first, then the path to determine the appropriate image extension. You can provide your own whitelist of extensions if desired; this defaults to the extensions supported by the currently installed set of plugins.

Parameters
unrecognizedImageExtensionPass null to have an ArgumentException thrown if the image type is not recognized as a whitelisted format
Returns

Definition at line 188 of file ImageUploadHelper.cs.

Referenced by ImageResizer.ImageUploadHelper.SaveUploadedFileSafely().

189  {
190  var ext = GetWhitelistedExtension(image,originalPath,whitelistedFormats) ?? unrecognizedImageExtension;
191  if (ext == null) throw new ArgumentException("The provided image type is not recognized as a whitelisted format");
192  return Guid.NewGuid().ToString("N", NumberFormatInfo.InvariantInfo) + ext;
193  }
string GetWhitelistedExtension(Stream image=null, string originalPath=null, string[] whitelistedFormats=null)
Uses stream signatures first, then the original path, to detect the appropriate normalized image exte...
string ImageResizer.ImageUploadHelper.GetExtension ( string  path)
inline

Parses the file extension from the path and returns it. If it contains a multi-segment extension like .txt.zip, only "zip" will be returned.

Parameters
path
Returns

Definition at line 30 of file ImageUploadHelper.cs.

Referenced by ImageResizer.ImageUploadHelper.GetWhitelistedExtension().

31  {
32  int lastDot = path.LastIndexOfAny(new char[] { '.', '/', ' ', '\\', '?', '&', ':' });
33  if (lastDot > -1 && path[lastDot] == '.') return path.Substring(lastDot + 1);
34  else return null;
35  }
int [] ImageResizer.ImageUploadHelper.GetImageSize ( object  s)
inline

Returns the [width,height] of the first frame/page of the image. May return null or throw exceptions.

Parameters
sMay be an UploadFile, a seekable Stream, a physical path, or a virtual path to the image.
Returns

Definition at line 139 of file ImageUploadHelper.cs.

139  {
140  var j = new ImageJob(s,null);
141  j.ResetSourceStream = true;
142  j.DisposeSourceObject = false;
143  c.CurrentImageBuilder.Build(j);
144  return new int[]{j.SourceWidth.Value,j.SourceHeight.Value};
145  }
string ImageResizer.ImageUploadHelper.GetWhitelistedExtension ( Stream  image = null,
string  originalPath = null,
string[]  whitelistedFormats = null 
)
inline

Uses stream signatures first, then the original path, to detect the appropriate normalized image extension. Returns null if extension (or no whitelisted extension) is found.

Parameters
image
originalPath
whitelistedFormatsYou can provide your own whitelist of extensions if desired (new string[]{"jpg","png"}). This defaults to the extensions supported by the currently installed set of plugins.
Returns

Definition at line 90 of file ImageUploadHelper.cs.

Referenced by ImageResizer.ImageUploadHelper.GenerateSafeImageName(), and ImageResizer.ImageUploadHelper.IsUploadedFileAnImage().

91  {
92  FileSignature sig = null;
93  if (image != null && image.CanSeek && image.CanRead)
94  sig = GuessFileTypeBySignature(image);
95 
96  var sigExt = sig != null ? NormalizeExtension(sig.PrimaryFileExtension) : null;
97 
98  if (sigExt != null && IsExtensionWhitelisted(sigExt,whitelistedFormats)) return sigExt;
99 
100  //Falback to untrusted ppath
101  if (originalPath != null){
102  string ext = NormalizeExtension(GetExtension(originalPath));
103 
104  if (ext != null & IsExtensionWhitelisted(ext,whitelistedFormats)) return ext;
105  }
106  return null;
107 
108  }
FileSignature GuessFileTypeBySignature(Stream s)
Tries to guess the file type of the given stream by the byte signature. Typically more reliable than ...
string GetExtension(string path)
Parses the file extension from the path and returns it. If it contains a multi-segment extension like...
string NormalizeExtension(string extension)
Lowercases and normalizes some common extension aliases (jpeg->jpg, tiff-tif). Does not filter out no...
bool IsExtensionWhitelisted(string ext, string[] whitelistedFormats=null)
Returns true if the given extension is whitelisted.
FileSignature ImageResizer.ImageUploadHelper.GuessFileTypeBySignature ( Stream  s)
inline

Tries to guess the file type of the given stream by the byte signature. Typically more reliable than file extensions - users constantly rename file extensions expecting it to change the actual encoding. Throws Argument exception if stream isn't seekable and readable. Returns null if there were no matches. Make sure the current position of the stream is at the beginning of the file, or you will get no results. Returns the stream to its original position

Parameters
s
Returns

Definition at line 203 of file ImageUploadHelper.cs.

Referenced by ImageResizer.ImageUploadHelper.GetWhitelistedExtension().

204  {
205  if (!(s.CanRead && s.CanSeek)) throw new ArgumentException("Stream must be seekable in order to guess the file type");
206 
207  List<FileSignature> signatures = new List<FileSignature>();
208  foreach (var p in c.Plugins.GetAll<IFileSignatureProvider>())
209  signatures.AddRange(p.GetSignatures());
210 
211  if (signatures.Count == 0) return null; //No signatures to compare!!
212 
213  //Sort by length, longest first
214  signatures.Sort(delegate(FileSignature a, FileSignature b){
215  return b.Signature.Length.CompareTo(a.Signature.Length);
216  });
217  //Copy the longest signature we may need to compare
218  byte[] buffer = new byte[signatures[0].Signature.Length];
219  int bytesRead = s.Read(buffer,0,buffer.Length);
220  s.Seek(bytesRead, SeekOrigin.Current);
221 
222  foreach (var sig in signatures)
223  {
224  if (bytesRead < sig.Signature.Length) continue; //Signature longer than file
225  if (sig.Signature.Length < 1) continue; //Empty signature
226  bool matches = true;
227  for (int i = 0; i < sig.Signature.Length; i++){
228  if (sig.Signature[i] != buffer[i])
229  {
230  matches = false;
231  break;
232  }
233  }
234  if (matches)
235  {
236  return sig;
237  }
238  }
239  return null;
240  }
PluginConfig Plugins
Access and modify plugins
Definition: Config.cs:85
bool ImageResizer.ImageUploadHelper.IsExtensionWhitelisted ( string  ext,
string[]  whitelistedFormats = null 
)
inline

Returns true if the given extension is whitelisted.

Parameters
ext
whitelistedFormatsYou can provide your own whitelist of extensions if desired (new string[]{"jpg","png"}). This defaults to the extensions supported by the currently installed set of plugins.
Returns

Definition at line 68 of file ImageUploadHelper.cs.

Referenced by ImageResizer.ImageUploadHelper.GetWhitelistedExtension().

69  {
70  if (whitelistedFormats == null)
71  return c.Pipeline.IsAcceptedImageType("." + ext);
72  else
73  {
74  foreach (var f in whitelistedFormats)
75  {
76  if (ext.Equals(f, StringComparison.OrdinalIgnoreCase)) return true;
77  }
78  return false;
79  }
80  }
bool ImageResizer.ImageUploadHelper.IsUploadedFileAnImage ( object  uploadFile,
string[]  whitelistedFormats = null 
)
inline

Returns true if the uploaded file is identified as an image (looks for the image signature, falling back to the user-provided filename).

Parameters
uploadFileMust be an HttpPostedFile or another class with both FileName and InputStream members
whitelistedFormatsYou can provide your own whitelist of extensions if desired (new string[]{"jpg","png"}). This defaults to the extensions supported by the currently installed set of plugins.
Returns

Definition at line 116 of file ImageUploadHelper.cs.

117  {
118  if (uploadFile == null) return false;
119 
120  PropertyInfo pname = uploadFile.GetType().GetProperty("FileName", typeof(string));
121  PropertyInfo pstream = uploadFile.GetType().GetProperty("InputStream");
122 
123  if (pname != null && pstream != null)
124  {
125  var path = pname.GetValue(uploadFile, null) as string;
126  var s = pstream.GetValue(uploadFile, null) as Stream;
127  if (s == null && path == null) throw new ArgumentException("The given upload file has a null .InputStream and .FileName");
128 
129  return GetWhitelistedExtension(s, path, whitelistedFormats) != null;
130  }
131  return false;
132  }
string GetWhitelistedExtension(Stream image=null, string originalPath=null, string[] whitelistedFormats=null)
Uses stream signatures first, then the original path, to detect the appropriate normalized image exte...
string ImageResizer.ImageUploadHelper.NormalizeExtension ( string  extension)
inline

Lowercases and normalizes some common extension aliases (jpeg->jpg, tiff-tif). Does not filter out non-image extensions!

Parameters
path
Returns

Definition at line 42 of file ImageUploadHelper.cs.

Referenced by ImageResizer.ImageUploadHelper.GetWhitelistedExtension().

43  {
44  if (extension == null) return null;
45  extension = extension.ToLowerInvariant();
46 
47  var mapping = new Dictionary<string,string>{
48  {"jpeg","jpg"},
49  {"jpe","jpg"},
50  {"jif","jpg"},
51  {"jfif","jpg"},
52  {"jfi","jpg"},
53  {"exif","jpg"},
54  {"tiff","tif"},
55  {"tff","tif"},
56  };
57 
58  return mapping.ContainsKey(extension) ? mapping[extension] : extension;
59  }
string ImageResizer.ImageUploadHelper.SaveUploadedFileSafely ( string  baseDir,
object  uploadFile,
string  unrecognizedImageExtension = ".unknown",
string[]  whitelistedFormats = null 
)
inline

Returns the name used for the file, without any path information. Name will be in "guid.ext" form. Will create any intermediate directories required.

Parameters
baseDir
uploadFile
unrecognizedImageExtension
whitelistedFormats
Returns

Definition at line 155 of file ImageUploadHelper.cs.

156  {
157  PropertyInfo pname = uploadFile.GetType().GetProperty("FileName", typeof(string));
158  PropertyInfo pstream = uploadFile.GetType().GetProperty("InputStream");
159 
160  if (pname == null || pstream == null) throw new ArgumentException("uploadFile.InputStream and uploadFile.fileName are required. Ensure you are passing in an HttpPostedFile instance or similar");
161 
162  var uploadPath = pname.GetValue(uploadFile, null) as string;
163  var uploadStream = pstream.GetValue(uploadFile, null) as Stream;
164 
165  var name = GenerateSafeImageName(uploadStream, uploadPath, unrecognizedImageExtension, whitelistedFormats);
166 
167  var dir = PathUtils.MapPathIfAppRelative(baseDir);
168 
169  var finalpath = Path.Combine(dir, name);
170 
171  string dirName = Path.GetDirectoryName(finalpath);
172  if (!Directory.Exists(dirName)) Directory.CreateDirectory(dirName);
173 
174  using (var fileStream = new FileStream(finalpath, FileMode.Create))
175  {
176  ImageResizer.ExtensionMethods.StreamExtensions.CopyToStream(uploadStream, fileStream);
177  fileStream.Flush();
178  }
179  return name;
180  }
string GenerateSafeImageName(Stream image=null, string originalPath=null, string unrecognizedImageExtension=".unknown", string[] whitelistedFormats=null)
Generates a safe name for your image in the form &quot;guid.ext&quot;. Uses stream signatures first...

The documentation for this class was generated from the following file: