本文整理汇总了C#中ImageFactory.Load方法的典型用法代码示例。如果您正苦于以下问题:C# ImageFactory.Load方法的具体用法?C# ImageFactory.Load怎么用?C# ImageFactory.Load使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ImageFactory
的用法示例。
在下文中一共展示了ImageFactory.Load方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ThenResultingImageSizeShouldBeLikeCropLayer
public void ThenResultingImageSizeShouldBeLikeCropLayer(float left, float top, float right, float bottom, CropMode mode)
{
// When crop mode is percentage. The right and bottom values should represent
// the percentage amount to remove from those sides.
const int SizeX = 200;
const int SizeY = 200;
int expectedWidth = 160;
int expectedHeight = 144;
CropLayer cl = new CropLayer(left, top, right, bottom, mode);
// Arrange
using (Bitmap bitmap = new Bitmap(SizeX, SizeY))
using (MemoryStream memoryStream = new MemoryStream())
{
bitmap.Save(memoryStream, ImageFormat.Bmp);
memoryStream.Position = 0;
using (ImageFactory imageFactory = new ImageFactory())
using (ImageFactory resultImage = imageFactory.Load(memoryStream).Crop(cl))
{
// Act // Assert
Assert.AreEqual(expectedWidth, resultImage.Image.Width);
Assert.AreEqual(expectedHeight, resultImage.Image.Height);
}
}
}
示例2: BackgroundColorIsChanged
public void BackgroundColorIsChanged()
{
ImageFactory imageFactory = new ImageFactory();
imageFactory.Load(@"Images\text.png");
Image original = (Image)imageFactory.Image.Clone();
imageFactory.BackgroundColor(Color.Yellow);
AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the background color operation should have been applied on {0}", imageFactory.ImagePath);
}
示例3: TestLoadImageFromFile
public void TestLoadImageFromFile(string fileName, string expectedMime)
{
var testPhoto = Path.Combine(this.localPath, string.Format("Images/{0}", fileName));
using (ImageFactory imageFactory = new ImageFactory())
{
imageFactory.Load(testPhoto);
Assert.AreEqual(testPhoto, imageFactory.ImagePath);
Assert.AreEqual(expectedMime, imageFactory.MimeType);
Assert.IsNotNull(imageFactory.Image);
}
}
示例4: ImageIsLoadedFromFile
public void ImageIsLoadedFromFile()
{
foreach (FileInfo file in this.ListInputFiles())
{
using (ImageFactory imageFactory = new ImageFactory())
{
imageFactory.Load(file.FullName);
imageFactory.ImagePath.Should().Be(file.FullName, "because the path should have been memorized");
imageFactory.Image.Should().NotBeNull("because the image should have been loaded");
}
}
}
示例5: BackgroundColorIsChanged
public void BackgroundColorIsChanged()
{
using (ImageFactory imageFactory = new ImageFactory())
{
imageFactory.Load(ImageSources.GetFilePathByName("text.png"));
using (Image original = imageFactory.Image.Copy())
{
imageFactory.BackgroundColor(Color.Yellow);
AssertionHelpers.AssertImagesAreDifferent(
original,
imageFactory.Image,
"because the background color operation should have been applied on {0}",
imageFactory.ImagePath);
}
}
}
示例6: ImageIsLoadedFromMemoryStream
public void ImageIsLoadedFromMemoryStream()
{
foreach (FileInfo file in this.ListInputFiles())
{
byte[] photoBytes = File.ReadAllBytes(file.FullName);
using (MemoryStream inStream = new MemoryStream(photoBytes))
{
using (ImageFactory imageFactory = new ImageFactory())
{
imageFactory.Load(inStream);
imageFactory.ImagePath.Should().BeNull("because an image loaded from stream should not have a file path");
imageFactory.Image.Should().NotBeNull("because the image should have been loaded");
}
}
}
}
示例7: ImageIsSavedToDisk
public void ImageIsSavedToDisk()
{
foreach (FileInfo file in this.ListInputFiles())
{
string outputFileName = string.Format("./output/{0}", file.Name);
using (ImageFactory imageFactory = new ImageFactory())
{
imageFactory.Load(file.FullName);
imageFactory.Save(outputFileName);
File.Exists(outputFileName).Should().BeTrue("because the file should have been saved on disk");
File.Delete(outputFileName);
}
}
}
示例8: ProcessImageAsync
//.........这里部分代码省略.........
if (ex.GetHttpCode() == (int)HttpStatusCode.NotFound)
{
ImageProcessorBootstrapper.Instance.Logger.Log<ImageProcessingModule>(ex.Message);
return;
}
}
if (imageBuffer == null)
{
return;
}
using (MemoryStream inStream = new MemoryStream(imageBuffer))
{
// Process the Image
MemoryStream outStream = new MemoryStream();
if (!string.IsNullOrWhiteSpace(queryString))
{
// Animation is not a processor but can be a specific request so we should allow it.
bool processAnimation;
AnimationProcessMode mode = this.ParseAnimationMode(queryString, out processAnimation);
// Attempt to match querystring and processors.
IWebGraphicsProcessor[] processors = ImageFactoryExtensions.GetMatchingProcessors(queryString);
if (processors.Any() || processAnimation)
{
// Process the image.
bool exif = preserveExifMetaData != null && preserveExifMetaData.Value;
bool gamma = fixGamma != null && fixGamma.Value;
using (ImageFactory imageFactory = new ImageFactory(exif, gamma) { AnimationProcessMode = mode })
{
imageFactory.Load(inStream).AutoProcess(processors).Save(outStream);
mimeType = imageFactory.CurrentImageFormat.MimeType;
}
}
else if (this.ParseCacheBuster(queryString))
{
// We're cachebustng. Allow the value to be cached
await inStream.CopyToAsync(outStream);
mimeType = FormatUtilities.GetFormat(outStream).MimeType;
}
else
{
// No match? Someone is either attacking the server or hasn't read the instructions.
// Either way throw an exception to prevent caching.
string message = string.Format(
"The request {0} could not be understood by the server due to malformed syntax.",
request.Unvalidated.RawUrl);
ImageProcessorBootstrapper.Instance.Logger.Log<ImageProcessingModule>(message);
throw new HttpException((int)HttpStatusCode.BadRequest, message);
}
}
else
{
// We're capturing all requests.
await inStream.CopyToAsync(outStream);
mimeType = FormatUtilities.GetFormat(outStream).MimeType;
}
// Fire the post processing event.
EventHandler<PostProcessingEventArgs> handler = OnPostProcessing;
if (handler != null)
{
string extension = Path.GetExtension(cachedPath);
示例9: ParseImage
/// <summary>
/// Returns an image from the given input path.
/// </summary>
/// <param name="input">
/// The input containing the value to parse.
/// </param>
/// <returns>
/// The <see cref="Image"/> representing the given image path.
/// </returns>
public Image ParseImage(string input)
{
Image image = null;
// Correctly parse the path.
string path;
this.Processor.Settings.TryGetValue("VirtualPath", out path);
if (!string.IsNullOrWhiteSpace(path) && path.StartsWith("~/"))
{
string imagePath = HostingEnvironment.MapPath(path);
if (imagePath != null)
{
imagePath = Path.Combine(imagePath, input);
try
{
using (ImageFactory factory = new ImageFactory())
{
factory.Load(imagePath);
image = new Bitmap(factory.Image);
}
}
catch
{
throw new HttpException((int)HttpStatusCode.NotFound, "No image exists at " + imagePath);
}
}
}
return image;
}
示例10: ProcessImageAsync
/// <summary>
/// Processes the image.
/// </summary>
/// <param name="context">
/// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that provides
/// references to the intrinsic server objects
/// </param>
/// <returns>
/// The <see cref="T:System.Threading.Tasks.Task"/>.
/// </returns>
private async Task ProcessImageAsync(HttpContext context)
{
HttpRequest request = context.Request;
bool isRemote = request.Path.Equals(RemotePrefix, StringComparison.OrdinalIgnoreCase);
string requestPath = string.Empty;
string queryString = string.Empty;
if (isRemote)
{
// We need to split the querystring to get the actual values we want.
string urlDecode = HttpUtility.UrlDecode(request.QueryString.ToString());
if (urlDecode != null)
{
string[] paths = urlDecode.Split('?');
requestPath = paths[0];
if (paths.Length > 1)
{
queryString = paths[1];
}
}
}
else
{
requestPath = HostingEnvironment.MapPath(request.Path);
queryString = HttpUtility.UrlDecode(request.QueryString.ToString());
}
// Only process requests that pass our sanitizing filter.
if (ImageUtils.IsValidImageExtension(requestPath) && !string.IsNullOrWhiteSpace(queryString))
{
string fullPath = string.Format("{0}?{1}", requestPath, queryString);
string imageName = Path.GetFileName(requestPath);
// Create a new cache to help process and cache the request.
DiskCache cache = new DiskCache(request, requestPath, fullPath, imageName, isRemote);
// Is the file new or updated?
bool isNewOrUpdated = await cache.IsNewOrUpdatedFileAsync();
// Only process if the file has been updated.
if (isNewOrUpdated)
{
// Process the image.
using (ImageFactory imageFactory = new ImageFactory())
{
if (isRemote)
{
Uri uri = new Uri(requestPath);
RemoteFile remoteFile = new RemoteFile(uri, false);
// Prevent response blocking.
WebResponse webResponse = await remoteFile.GetWebResponseAsync().ConfigureAwait(false);
using (MemoryStream memoryStream = new MemoryStream())
{
using (WebResponse response = webResponse)
{
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
// Trim the cache.
await cache.TrimCachedFoldersAsync();
responseStream.CopyTo(memoryStream);
imageFactory.Load(memoryStream)
.AddQueryString(queryString)
.Format(ImageUtils.GetImageFormat(imageName))
.AutoProcess().Save(cache.CachedPath);
// Ensure that the LastWriteTime property of the source and cached file match.
DateTime dateTime = await cache.SetCachedLastWriteTimeAsync();
// Add to the cache.
await cache.AddImageToCacheAsync(dateTime);
}
}
}
}
}
else
{
// Trim the cache.
await cache.TrimCachedFoldersAsync();
//.........这里部分代码省略.........
示例11: ProcessImageAsync
//.........这里部分代码省略.........
// Process the image.
bool exif = preserveExifMetaData != null && preserveExifMetaData.Value;
bool gamma = fixGamma != null && fixGamma.Value;
using (ImageFactory imageFactory = new ImageFactory(exif, gamma))
{
byte[] imageBuffer = null;
string mimeType;
try
{
imageBuffer = await currentService.GetImage(resourcePath);
}
catch (HttpException ex)
{
// We want 404's to be handled by IIS so that other handlers/modules can still run.
if (ex.GetHttpCode() == (int)HttpStatusCode.NotFound)
{
return;
}
}
if (imageBuffer == null)
{
return;
}
using (MemoryStream inStream = new MemoryStream(imageBuffer))
{
// Process the Image
MemoryStream outStream = new MemoryStream();
if (!string.IsNullOrWhiteSpace(queryString))
{
imageFactory.Load(inStream).AutoProcess(queryString).Save(outStream);
mimeType = imageFactory.CurrentImageFormat.MimeType;
}
else
{
await inStream.CopyToAsync(outStream);
mimeType = FormatUtilities.GetFormat(outStream).MimeType;
}
// Fire the post processing event.
EventHandler<PostProcessingEventArgs> handler = OnPostProcessing;
if (handler != null)
{
string extension = Path.GetExtension(cachedPath);
PostProcessingEventArgs args = new PostProcessingEventArgs
{
Context = context,
ImageStream = outStream,
ImageExtension = extension
};
handler(this, args);
outStream = args.ImageStream;
}
// Add to the cache.
await this.imageCache.AddImageToCacheAsync(outStream, mimeType);
// Cleanup
outStream.Dispose();
}
// Store the response type and cache dependency in the context for later retrieval.
示例12: ProcessImageAsync
//.........这里部分代码省略.........
return;
}
if (string.IsNullOrWhiteSpace(requestPath))
{
return;
}
string parts = !string.IsNullOrWhiteSpace(urlParameters) ? "?" + urlParameters : string.Empty;
string fullPath = string.Format("{0}{1}?{2}", requestPath, parts, queryString);
object resourcePath;
// More legacy support code.
if (hasMultiParams)
{
resourcePath = string.IsNullOrWhiteSpace(urlParameters)
? new Uri(requestPath, UriKind.RelativeOrAbsolute)
: new Uri(requestPath + "?" + urlParameters, UriKind.RelativeOrAbsolute);
}
else
{
resourcePath = requestPath;
}
// Check whether the path is valid for other requests.
if (!currentService.IsValidRequest(resourcePath.ToString()))
{
return;
}
string combined = requestPath + fullPath + queryString;
using (await Locker.LockAsync(combined))
{
// Create a new cache to help process and cache the request.
this.imageCache = (IImageCache)ImageProcessorConfiguration.Instance
.ImageCache.GetInstance(requestPath, fullPath, queryString);
// Is the file new or updated?
bool isNewOrUpdated = await this.imageCache.IsNewOrUpdatedAsync();
string cachedPath = this.imageCache.CachedPath;
// Only process if the file has been updated.
if (isNewOrUpdated)
{
// Process the image.
using (ImageFactory imageFactory = new ImageFactory(preserveExifMetaData != null && preserveExifMetaData.Value))
{
byte[] imageBuffer = await currentService.GetImage(resourcePath);
using (MemoryStream inStream = new MemoryStream(imageBuffer))
{
// Process the Image
using (MemoryStream outStream = new MemoryStream())
{
imageFactory.Load(inStream).AutoProcess(queryString).Save(outStream);
// Add to the cache.
await this.imageCache.AddImageToCacheAsync(outStream, imageFactory.CurrentImageFormat.MimeType);
}
}
// Store the cached path, response type, and cache dependency in the context for later retrieval.
context.Items[CachedPathKey] = cachedPath;
context.Items[CachedResponseTypeKey] = imageFactory.CurrentImageFormat.MimeType;
bool isFileCached = new Uri(cachedPath).IsFile;
if (isFileLocal)
{
if (isFileCached)
{
// Some services might only provide filename so we can't monitor for the browser.
context.Items[CachedResponseFileDependency] = Path.GetFileName(requestPath) == requestPath
? new List<string> { cachedPath }
: new List<string> { requestPath, cachedPath };
}
else
{
context.Items[CachedResponseFileDependency] = Path.GetFileName(requestPath) == requestPath
? null
: new List<string> { requestPath };
}
}
else if (isFileCached)
{
context.Items[CachedResponseFileDependency] = new List<string> { cachedPath };
}
}
}
// The cached file is valid so just rewrite the path.
this.imageCache.RewritePath(context);
// Redirect if not a locally store file.
if (!new Uri(cachedPath).IsFile)
{
context.ApplicationInstance.CompleteRequest();
}
}
}
}
示例13: ParseImage
/// <summary>
/// Returns an image from the given input path.
/// </summary>
/// <param name="input">
/// The input containing the value to parse.
/// </param>
/// <returns>
/// The <see cref="Image"/> representing the given image path.
/// </returns>
public Image ParseImage(string input)
{
Image image = null;
// Correctly parse the path.
string path;
this.Processor.Settings.TryGetValue("VirtualPath", out path);
if (!string.IsNullOrWhiteSpace(path) && path.StartsWith("~/"))
{
string imagePath = HostingEnvironment.MapPath(path);
if (imagePath != null)
{
imagePath = Path.Combine(imagePath, input);
using (ImageFactory factory = new ImageFactory())
{
factory.Load(imagePath);
image = new Bitmap(factory.Image);
}
}
}
return image;
}
示例14: ProcessImageAsync
//.........这里部分代码省略.........
// Only process if the file has been updated.
if (isNewOrUpdated)
{
string cachedPath = cache.CachedPath;
// Process the image.
using (ImageFactory imageFactory = new ImageFactory(preserveExifMetaData != null && preserveExifMetaData.Value))
{
if (isRemote)
{
Uri uri = new Uri(requestPath + "?" + urlParameters);
RemoteFile remoteFile = new RemoteFile(uri, false);
// Prevent response blocking.
WebResponse webResponse = await remoteFile.GetWebResponseAsync().ConfigureAwait(false);
SemaphoreSlim semaphore = GetSemaphoreSlim(cachedPath);
try
{
semaphore.Wait();
using (MemoryStream memoryStream = new MemoryStream())
{
using (WebResponse response = webResponse)
{
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
responseStream.CopyTo(memoryStream);
// Process the Image
imageFactory.Load(memoryStream)
.AddQueryString(queryString)
.AutoProcess()
.Save(cachedPath);
// Store the response type in the context for later retrieval.
context.Items[CachedResponseTypeKey] = imageFactory.MimeType;
// Add to the cache.
cache.AddImageToCache();
// Trim the cache.
await cache.TrimCachedFolderAsync(cachedPath);
}
}
}
}
}
finally
{
semaphore.Release();
}
}
else
{
// Check to see if the file exists.
// ReSharper disable once AssignNullToNotNullAttribute
FileInfo fileInfo = new FileInfo(requestPath);
if (!fileInfo.Exists)
{
throw new HttpException(404, "No image exists at " + fullPath);
}
示例15: ImageIsLoadedFromByteArray
public void ImageIsLoadedFromByteArray()
{
foreach (FileInfo file in ImageSources.GetInputImageFiles())
{
byte[] photoBytes = File.ReadAllBytes(file.FullName);
using (ImageFactory imageFactory = new ImageFactory())
{
imageFactory.Load(photoBytes);
imageFactory.ImagePath.Should().BeNull("because an image loaded from byte array should not have a file path");
imageFactory.Image.Should().NotBeNull("because the image should have been loaded");
}
}
}