I found a nice code to down size image on server, to avoid bad image rendering by different browser. This code is for MVC application.
I have no experience in C# would like to know what do I need to change to make this code work in webforms.
<img src="#Url.Action("ResizeImage", "Controller", new { urlImage = "<url_image>", width = 35 })" />
public ActionResult ResizeImage(string imageUrl, int width)
{
WebImage wImage = new WebImage(imageUrl);
wImage = WebImageExtension.Resize(wImage, width);
return File(wImage.GetBytes(), "image/png");
}
public static class WebImageExtension
{
private static readonly IDictionary<string, ImageFormat> TransparencyFormats =
new Dictionary<string, ImageFormat>(StringComparer.OrdinalIgnoreCase) { { "png", ImageFormat.Png }, { "gif", ImageFormat.Gif } };
public static WebImage Resize(this WebImage image, int width)
{
double aspectRatio = (double)image.Width / image.Height;
var height = Convert.ToInt32(width / aspectRatio);
ImageFormat format;
if (!TransparencyFormats.TryGetValue(image.ImageFormat.ToLower(), out format))
{
return image.Resize(width, height);
}
using (Image resizedImage = new Bitmap(width, height))
{
using (var source = new Bitmap(new MemoryStream(image.GetBytes())))
{
using (Graphics g = Graphics.FromImage(resizedImage))
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(source, 0, 0, width, height);
}
}
using (var ms = new MemoryStream())
{
resizedImage.Save(ms, format);
return new WebImage(ms.ToArray());
}
}
}
}
UPDATE:
I use this code to resize images
public static void ResizeImageFreeSize(string OriginalFile, string NewFile, int MinWidth, int MinHeight, string FileExtension)
{
var NewHeight = MinHeight;
var NewWidth = MinWidth;
// var OriginalImage = System.Drawing.Image.FromFile(OriginalFile); // THis statlement alon with generate error as file is locked so -->GDI+ keeps a lock on files from which an image was contructed. To avoid the lock, construct the image from a MemorySteam:
MemoryStream ms = new MemoryStream(File.ReadAllBytes(OriginalFile));
var OriginalImage = System.Drawing.Image.FromStream(ms);
if (OriginalImage.Width < MinWidth || OriginalImage.Height < MinHeight)
throw new Exception(String.Format("Invalid Image Dimensions, please upload an image with minmum dimensions of {0}x{1}px", MinWidth.ToString(), MinHeight.ToString()));
// If the image dimensions are the same then make the new dimensions the largest of the two mins.
if (OriginalImage.Height == OriginalImage.Width)
NewWidth = NewHeight = (MinWidth > MinHeight) ? MinWidth : MinHeight;
else
{
if (MinWidth > MinHeight)
NewHeight = (int)(OriginalImage.Height * ((float)MinWidth / (float)OriginalImage.Width));
else
NewWidth = (int)(OriginalImage.Width * ((float)MinHeight / (float)OriginalImage.Height));
}
// Just resample the Original Image into a new Bitmap
var ResizedBitmap = new System.Drawing.Bitmap(OriginalImage, NewWidth, NewHeight);
// Saves the new bitmap in the same format as it's source image
FileExtension = FileExtension.ToLower().Replace(".", "");
ImageFormat Format = null;
switch (FileExtension)
{
case "jpg":
Format = ImageFormat.Jpeg;
Encoder quality = Encoder.Quality;
var ratio = new EncoderParameter(quality, 100L);
var codecParams = new EncoderParameters(1);
codecParams.Param[0] = ratio;
// NewImage.Save(NewFile, GetEncoder(ImageFormat.Jpeg), codecParams);
ResizedBitmap.Save(NewFile, GetEncoder(ImageFormat.Jpeg), codecParams);
break;
case "gif":
Format = ImageFormat.Gif;
ResizedBitmap.Save(NewFile, Format);
break;
case "png":
Format = ImageFormat.Png;
ResizedBitmap.Save(NewFile, Format);
break;
default:
Format = ImageFormat.Png;
ResizedBitmap.Save(NewFile, Format);
break;
}
// ResizedBitmap.Save(NewFile, Format);
// Clear handle to original file so that we can overwrite it if necessary
OriginalImage.Dispose();
ResizedBitmap.Dispose();
}
You can have a HttpHandler for this in C#,
namespace CMSN.Software.Tutorials.HowToDynamicallyResizeImages
{
public class DynamicImage : IHttpHandler
{
/// <summary>
/// Default cache duration
/// </summary>
private static readonly TimeSpan CacheDuration = TimeSpan.FromDays(30);
/// <summary>
/// Gets a value indicating whether another request can use the
/// <see cref="T:System.Web.IHttpHandler"/> instance.
/// </summary>
/// <returns>
/// true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.
/// </returns>
public bool IsReusable
{
get
{
return false;
}
}
/// <summary>
/// Enables processing of HTTP Web requests by a custom HttpHandler that implements the
/// <see cref="T:System.Web.IHttpHandler"/> interface.
/// </summary>
/// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the
/// intrinsic server objects (for example, Request, Response, Session, and Server)
/// used to service HTTP requests.
/// </param>
public void ProcessRequest(HttpContext context)
{
string cacheKeyName = context.Request.Url.PathAndQuery;
string imagePath = context.Server.MapPath(context.Request.Url.LocalPath);
string imageExtention = Path.GetExtension(imagePath);
string contentType = string.Empty;
byte[] imageFileContent;
ImageFormat imageFormat = null;
switch (imageExtention)
{
case ".png":
imageFormat = ImageFormat.Png;
contentType = "image/png";
break;
case ".jpg":
case ".jpeg":
case ".jpe":
imageFormat = ImageFormat.Jpeg;
contentType = "image/jpeg";
break;
case ".bmp":
imageFormat = ImageFormat.Bmp;
contentType = "image/bmp";
break;
case ".gif":
imageFormat = ImageFormat.Gif;
contentType = "image/gif";
break;
default:
break;
}
context.Response.ContentType = contentType;
if (context.Cache[CacheKey(cacheKeyName)] != null)
{
imageFileContent = context.Cache[CacheKey(cacheKeyName)] as byte[];
}
else
{
int imageWidth = 0;
int imageHeight = 0;
if (!string.IsNullOrEmpty(context.Request["w"]))
{
if (!int.TryParse(context.Request["w"], out imageWidth))
{
imageWidth = 0;
}
}
if (!string.IsNullOrEmpty(context.Request["h"]))
{
if (!int.TryParse(context.Request["h"], out imageHeight))
{
imageHeight = 0;
}
}
Image originalImage;
if (File.Exists(imagePath))
{
originalImage = Image.FromFile(imagePath);
}
else
{
originalImage = new Bitmap(100, 100);
}
if (imageWidth > 0 || imageHeight > 0)
{
if (imageHeight == 0 && imageWidth > 0)
{
imageHeight = originalImage.Height * imageWidth / originalImage.Width;
}
if (imageWidth == 0 && imageHeight > 0)
{
imageWidth = originalImage.Width * imageHeight / originalImage.Height;
}
}
else
{
imageHeight = originalImage.Height;
imageWidth = originalImage.Width;
}
using (Bitmap newImage = new Bitmap(originalImage, imageWidth, imageHeight))
{
Graphics generatedImage = Graphics.FromImage(newImage);
generatedImage.InterpolationMode = InterpolationMode.HighQualityBicubic;
generatedImage.SmoothingMode = SmoothingMode.AntiAlias;
generatedImage.CompositingQuality = CompositingQuality.HighQuality;
generatedImage.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);
// make a memory stream to work with the image bytes
using (MemoryStream imageStream = new MemoryStream())
{
// put the image into the memory stream
newImage.Save(imageStream, imageFormat);
// make byte array the same size as the image
byte[] imageContent = new byte[imageStream.Length];
// rewind the memory stream
imageStream.Position = 0;
// load the byte array with the image
imageStream.Read(imageContent, 0, (int)imageStream.Length);
// return byte array to caller with image type
imageFileContent = imageContent;
using (CacheDependency dependency = new CacheDependency(imagePath))
{
context.Cache.Insert(
CacheKey(cacheKeyName),
imageContent,
dependency,
System.Web.Caching.Cache.NoAbsoluteExpiration,
CacheDuration);
}
}
}
originalImage.Dispose();
}
SetResponseCache(context.Response, new string[1] { imagePath });
context.Response.BinaryWrite(imageFileContent);
}
/// <summary>
/// Generate unique Cache key.
/// </summary>
/// <param name="key">The cache key.</param>
/// <returns>Generated unique Cache key</returns>
protected static string CacheKey(string key)
{
return "DynamicImage." + key;
}
/// <summary>
/// Sets the response cache.
/// </summary>
/// <param name="response">The response.</param>
/// <param name="files">The files.</param>
protected static void SetResponseCache(HttpResponse response, string[] files)
{
response.AddFileDependencies(files);
HttpCachePolicy browserCache = response.Cache;
DateTime modifiedTime = DateTime.Now;
browserCache.SetCacheability(HttpCacheability.ServerAndPrivate);
browserCache.VaryByParams["w"] = true;
browserCache.VaryByParams["h"] = true;
browserCache.VaryByParams["v"] = true;
browserCache.SetOmitVaryStar(true);
browserCache.SetExpires(modifiedTime.AddDays(7));
browserCache.SetValidUntilExpires(true);
browserCache.SetLastModified(modifiedTime);
browserCache.SetETagFromFileDependencies();
browserCache.SetLastModifiedFromFileDependencies();
}
}
}
Web.config
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpHandlers>
<add verb="*" path="*.png,*.jpg,*.jpeg,*.gif,*.bmp" type="CMSN.Software.Tutorials.HowToDynamicallyResizeImages.DynamicImage,HowToDynamicallyResizeImages"/>
</httpHandlers>
</system.web>
<system.webServer>
<handlers>
<add verb="*" path="*.png,*.jpg,*.jpeg,*.gif,*.bmp" name="DynamicImage" type="CMSN.Software.Tutorials.HowToDynamicallyResizeImages.DynamicImage,HowToDynamicallyResizeImages"/>
</handlers>
<validation validateIntegratedModeConfiguration="false"/>
</system.webServer>
</configuration>
Usage,
http://localhost/Images/xxxxxxxx.png?w=300&h=149
If you want to see the complete guide for this, please follow the following URL.
http://tutorials.cmsnsoftware.com/2011/09/how-to-dynamically-resize-images.html
Related
I am working on a web based OHIF Dicom viewer. I am using clear canvas as my PACs server. So I developed one broker application in .net core which works like WADO-RS and supply information to OHIF viewer from clear canvas. In my broker application I am passing metadata to OHIF viewer in json format by using FO-dicom json converter which converts dcm file into Json string.
My code for sending metadata:
var files = Directory.GetFiles(directory);
List<JObject> lstjo = new List<JObject>();
JObject jo;
foreach (var file in files)
{
var dicomDirectory = DicomFile.Open(file, FileReadOption.ReadAll);
if (dicomDirectory.Dataset.InternalTransferSyntax.UID.UID != DicomTransferSyntax.ImplicitVRLittleEndian.UID.UID)
{
var transcoder = new DicomTranscoder(dicomDirectory.Dataset.InternalTransferSyntax, DicomTransferSyntax.ImplicitVRLittleEndian);
dicomDirectory = transcoder.Transcode(dicomDirectory);
}
JsonDicomConverter dicomConverter = new JsonDicomConverter();
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
JsonWriter writer = new JsonTextWriter(sw);
Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
dicomConverter.WriteJson(writer, dicomDirectory.Dataset, serializer);
jo = JObject.Parse(sb.ToString());
// jo.Property("7FE00010").Remove();
retJsonstring += jo.ToString() + ",";
}
if (retJsonstring.Length > 6)
{
retJsonstring = retJsonstring.Substring(0, retJsonstring.Length - 1) + "]";
}
else
{
retJsonstring += "]";
}
retJsonstring = retJsonstring.Replace("\r", "").Replace("\n", "");
}
return retJsonstring;
During passing metadata there is no issue in Ohif viewer. After then OHIF viewer sending WADORS request for frames to display. My broker application also send responding for that request in multipart.
My code for sending Multipart response :
{
var dicomFile = DicomFile.Open(path, FileReadOption.ReadAll);
string transfersyntax = dicomFile.Dataset.InternalTransferSyntax.UID.UID;
MemoryStream streamContent = new MemoryStream();
if (transfersyntax != DicomTransferSyntax.ImplicitVRLittleEndian.UID.UID)
{
var transcoder = new DicomTranscoder(dicomFile.Dataset.InternalTransferSyntax, DicomTransferSyntax.ImplicitVRLittleEndian);
dicomFile = transcoder.Transcode(dicomFile);
}
dicomFile.Save(streamContent);
DicomImage img = new DicomImage(dicomFile.Dataset, 0);
streamContent.Seek(0, SeekOrigin.Begin);
string boundary = Guid.NewGuid().ToString();
MultipartContent multipartContent = new MultipartContent();
//newFile.Save(multipartContent.Stream);
multipartContent.Stream = streamContent;// File.OpenRead(path);
multipartContent.ContentType = "application/octet-stream";
multipartContent.transfersyntax = dicomFile.Dataset.InternalTransferSyntax.UID.UID;
multipartContent.FileName = "";
multiContentResult = new MultipartResult("related", boundary) { multipartContent };
return multiContentResult;
}
Mulitpart class and MulticontentResult Class:
public class MultipartContent
{
public string ContentType { get; set; }
public string FileName { get; set; }
public Stream Stream { get; set; }
public string transfersyntax { get; set; }
}
public class MultipartResult : Collection<MultipartContent>, IActionResult
{
private readonly System.Net.Http.MultipartContent content;
public MultipartResult(string subtype = "byteranges", string boundary = null)
{
if (boundary == null)
{
this.content = new System.Net.Http.MultipartContent(subtype);
}
else
{
this.content = new System.Net.Http.MultipartContent(subtype, boundary);
}
}
public async Task ExecuteResultAsync(ActionContext context)
{
foreach (var item in this)
{
if (item.Stream != null)
{
var content = new StreamContent(item.Stream);
if (item.ContentType != null)
{
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(item.ContentType);
content.Headers.ContentType.Parameters.Add(new System.Net.Http.Headers.NameValueHeaderValue("transfer-syntax", item.transfersyntax));
}
this.content.Add(content);
}
}
context.HttpContext.Response.ContentLength = content.Headers.ContentLength;
context.HttpContext.Response.ContentType = content.Headers.ContentType.ToString();
await content.CopyToAsync(context.HttpContext.Response.Body);
}
}
After sending WAROrs response , I getting error in OHIF viewer in RangeError: offset is out of bounds in stackviewport.js during set pixeldata flat32array to scaledata flat32array like below Image
So I inspect in browser after then I come know that Pixel data size and scaledata size is different like below image..
To verify my dcm file I checked with ohif viewer by directly opened those file in https://v3-demo.ohif.org/local. It is opening properly.
So what are possible reason for this issue ? how to rectify?
I just want to re-size image without losing quality
can I use this ?
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
WebImage img = new WebImage(file.InputStream);
if (img.Width > 1000)
img.Resize(1000, 1000);
img.Save("path");
return View();
}
or WebImage resize but loss image quality ?
thanks
Here is a code I use. Call ResizeImage method in your action.
public class Size
{
public Size(int width, int height)
{
Width = width;
Height = height;
}
public int Width { get; set; }
public int Height { get; set; }
}
public static bool ResizeImage(string orgFile, string resizedFile, ImageFormat format, int width, int height)
{
try
{
using (Image img = Image.FromFile(orgFile))
{
Image thumbNail = new Bitmap(width, height, img.PixelFormat);
Graphics g = Graphics.FromImage(thumbNail);
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle rect = new Rectangle(0, 0, width, height);
g.DrawImage(img, rect);
thumbNail.Save(resizedFile, format);
}
return true;
}
catch (Exception)
{
return false;
}
}
Taken from http://www.codeproject.com/Tips/481015/Rename-Resize-Upload-Image-ASP-NET-MVC.
It is say to firstly create a class for image to save (I have just copy and paste)
public class ImageResult
{
public bool Success { get; set; }
public string ImageName { get; set; }
public string ErrorMessage { get; set; }
}
then you need another class with method to save (i have just copy and paste)
public class ImageUpload
{
// set default size here
public int Width { get; set; }
public int Height { get; set; }
// folder for the upload, you can put this in the web.config
private readonly string UploadPath = "~/Images/Items/";
public ImageResult RenameUploadFile(HttpPostedFileBase file, Int32 counter = 0)
{
var fileName = Path.GetFileName(file.FileName);
string prepend = "item_";
string finalFileName = prepend + ((counter).ToString()) + "_" + fileName;
if (System.IO.File.Exists
(HttpContext.Current.Request.MapPath(UploadPath + finalFileName)))
{
//file exists => add country try again
return RenameUploadFile(file, ++counter);
}
//file doesn't exist, upload item but validate first
return UploadFile(file, finalFileName);
}
private ImageResult UploadFile(HttpPostedFileBase file, string fileName)
{
ImageResult imageResult = new ImageResult { Success = true, ErrorMessage = null };
var path =
Path.Combine(HttpContext.Current.Request.MapPath(UploadPath), fileName);
string extension = Path.GetExtension(file.FileName);
//make sure the file is valid
if (!ValidateExtension(extension))
{
imageResult.Success = false;
imageResult.ErrorMessage = "Invalid Extension";
return imageResult;
}
try
{
file.SaveAs(path);
Image imgOriginal = Image.FromFile(path);
//pass in whatever value you want
Image imgActual = Scale(imgOriginal);
imgOriginal.Dispose();
imgActual.Save(path);
imgActual.Dispose();
imageResult.ImageName = fileName;
return imageResult;
}
catch (Exception ex)
{
// you might NOT want to show the exception error for the user
// this is generally logging or testing
imageResult.Success = false;
imageResult.ErrorMessage = ex.Message;
return imageResult;
}
}
// you can also create an Mvc dataannotation to validate the extension of image in both server side and client side
// don't forget to add (.JPG, .JPEG or .PNG on these extension, because you can facing this type of problem
private bool ValidateExtension(string extension)
{
extension = extension.ToLower();
switch (extension)
{
case ".jpg":
return true;
case ".png":
return true;
case ".gif":
return true;
case ".jpeg":
return true;
default:
return false;
}
}
private Image Scale(Image imgPhoto)
{
float sourceWidth = imgPhoto.Width;
float sourceHeight = imgPhoto.Height;
float destHeight = 0;
float destWidth = 0;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
// force resize, might distort image
if (Width != 0 && Height != 0)
{
destWidth = Width;
destHeight = Height;
}
// change size proportially depending on width or height
else if (Height != 0)
{
destWidth = (float)(Height * sourceWidth) / sourceHeight;
destHeight = Height;
}
else
{
destWidth = Width;
destHeight = (float)(sourceHeight * Width / sourceWidth);
}
Bitmap bmPhoto = new Bitmap((int)destWidth, (int)destHeight,
PixelFormat.Format32bppPArgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
//you can also add these properties to improve the quality of saved image
grPhoto.SmoothingMode = SmoothingMode.HighQuality;
grPhoto.CompositingQuality = CompositingQuality.HighQuality;
grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX, destY, (int)destWidth, (int)destHeight),
new Rectangle(sourceX, sourceY, (int)sourceWidth, (int)sourceHeight),
GraphicsUnit.Pixel);
grPhoto.Dispose();
return bmPhoto;
}
//you can also create another method to verify if a saved image with similar name exist and use it in som method of controller like (Modify your account
public ImageResult VerifyUploadFile(HttpPostedFileBase file)
{
var fileName = Path.GetFileName(file.FileName);
string finalFileName = UploadPath + fileName;
// si une telle image existe déjà, renvoyer le nom du fichier et dire que le succes est faux
if (System.IO.File.Exists
(HttpContext.Current.Request.MapPath(UploadPath + finalFileName)))
{
//file exists => sucess is false
return new ImageResult { Success = false, ErrorMessage = null, ImageName =finalFileName };
}
//file doesn't exist, upload item but validate first
return RenameUploadFile(file);
}
}
You can use it after in the controller depending of your need
[HttpPost]
public ActionResult Index(FormCollection formCollection)
{
foreach (string item in Request.Files)
{
HttpPostedFileBase file = Request.Files[item] as HttpPostedFileBase;
if (file.ContentLength == 0)
continue;
if (file.ContentLength > 0)
{
// width + height will force size, care for distortion
//Exmaple: ImageUpload imageUpload = new ImageUpload { Width = 800, Height = 700 };
// height will increase the width proportionally
//Example: ImageUpload imageUpload = new ImageUpload { Height= 600 };
// width will increase the height proportionally
ImageUpload imageUpload = new ImageUpload { Width= 600 };
// rename, resize, and upload
//return object that contains {bool Success,string ErrorMessage,string ImageName}
ImageResult imageResult = imageUpload.RenameUploadFile(file);
if (imageResult.Success)
{
//TODO: write the filename to the db
Console.WriteLine(imageResult.ImageName);
}
else
{
// use imageResult.ErrorMessage to show the error
ViewBag.Error = imageResult.ErrorMessage;
}
}
}
return View();
}
You can use verifyupload at your need.
var imagePhysicalPath = #"c://image.jpg";
var newImagePhysicalPath = #"c://new-image.jpg";
var image = new System.Web.Helpers.WebImage(imagePhysicalPath)
.Resize(width + 1, height + 1, false, true)//+1 because webimage use 1px for border
.Crop(1, 1) //remove border
.Save(newImagePhysicalPath);
Someone helped me get this code for taking a picture using xamarin forms labs camera:
picker = DependencyService.Get<IMediaPicker> ();
task = picker.TakePhotoAsync (new CameraMediaStorageOptions {
DefaultCamera = CameraDevice.Rear,
MaxPixelDimension = 800,
});
img.BackgroundColor = Color.Gray;
Device.StartTimer (TimeSpan.FromMilliseconds (250), () => {
if (task != null) {
if (task.Status == TaskStatus.RanToCompletion) {
Device.BeginInvokeOnMainThread (async () => {
//img.Source = ImageSource.FromStream (() => task.Result.Source);
var fileAccess = Resolver.Resolve<IFileAccess> ();
string imageName = "img_user_" + User.CurrentUser().id + "_" + DateTime.Now.ToString ("yy_MM_dd_HH_mm_ss") + ".jpg";
fileName = imageName;
fileAccess.WriteStream (imageName, task.Result.Source);
fileLocation = fileAccess.FullPath(imageName);
FileStream fileStream = new FileStream(fileAccess.FullPath(imageName), FileMode.Open, System.IO.FileAccess.Read);
imageUrl = (string)test[0]["url"];
img.Source = imageUrl;
});
}
return task.Status != TaskStatus.Canceled
&& task.Status != TaskStatus.Faulted
&& task.Status != TaskStatus.RanToCompletion;
}
return true;
});
It saves the image, but the actual size of the phone picture taken is huge, is there a way to resize it.
UPDATE: The original answer is not useful, see below for updated answer. The issue was the PCL library was very slow and consumed too much memory.
ORIGINAL ANSWER (do not use):
I found an image I/O library, ImageTools-PCL, which I forked on github and trimmed down what wouldn't compile in Xamarin, keeping the modifications to minimum and the result seems to work.
To use it download the linked repository, compile it with Xamarin and add the DLLs from Build folder to your Forms project.
To resize an image you can do this (should fit the context of your question)
var decoder = new ImageTools.IO.Jpeg.JpegDecoder ();
ImageTools.ExtendedImage inImage = new ImageTools.ExtendedImage ();
decoder.Decode (inImage, task.Result.Source);
var outImage = ImageTools.ExtendedImage.Resize (inImage, 1024, new ImageTools.Filtering.BilinearResizer ());
var encoder = new ImageTools.IO.Jpeg.JpegEncoder ();
encoder.Encode (outImage, fileAccess.CreateStream (imageName));
ImageSource imgSource = ImageSource.FromFile (fileAccess.FullPath (imageName));
UPDATED ANSWER:
Get Xamarin.XLabs from nuget, learn about using Resolver, create an IImageService interface with Resize method.
Implementation for iOS:
public class ImageServiceIOS: IImageService{
public void ResizeImage(string sourceFile, string targetFile, float maxWidth, float maxHeight)
{
if (File.Exists(sourceFile) && !File.Exists(targetFile))
{
using (UIImage sourceImage = UIImage.FromFile(sourceFile))
{
var sourceSize = sourceImage.Size;
var maxResizeFactor = Math.Min(maxWidth / sourceSize.Width, maxHeight / sourceSize.Height);
if (!Directory.Exists(Path.GetDirectoryName(targetFile)))
Directory.CreateDirectory(Path.GetDirectoryName(targetFile));
if (maxResizeFactor > 0.9)
{
File.Copy(sourceFile, targetFile);
}
else
{
var width = maxResizeFactor * sourceSize.Width;
var height = maxResizeFactor * sourceSize.Height;
UIGraphics.BeginImageContextWithOptions(new CGSize((float)width, (float)height), true, 1.0f);
// UIGraphics.GetCurrentContext().RotateCTM(90 / Math.PI);
sourceImage.Draw(new CGRect(0, 0, (float)width, (float)height));
var resultImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
if (targetFile.ToLower().EndsWith("png"))
resultImage.AsPNG().Save(targetFile, true);
else
resultImage.AsJPEG().Save(targetFile, true);
}
}
}
}
}
Implementation of the service for Android:
public class ImageServiceDroid: IImageService{
public void ResizeImage(string sourceFile, string targetFile, float maxWidth, float maxHeight)
{
if (!File.Exists(targetFile) && File.Exists(sourceFile))
{
// First decode with inJustDecodeBounds=true to check dimensions
var options = new BitmapFactory.Options()
{
InJustDecodeBounds = false,
InPurgeable = true,
};
using (var image = BitmapFactory.DecodeFile(sourceFile, options))
{
if (image != null)
{
var sourceSize = new Size((int)image.GetBitmapInfo().Height, (int)image.GetBitmapInfo().Width);
var maxResizeFactor = Math.Min(maxWidth / sourceSize.Width, maxHeight / sourceSize.Height);
string targetDir = System.IO.Path.GetDirectoryName(targetFile);
if (!Directory.Exists(targetDir))
Directory.CreateDirectory(targetDir);
if (maxResizeFactor > 0.9)
{
File.Copy(sourceFile, targetFile);
}
else
{
var width = (int)(maxResizeFactor * sourceSize.Width);
var height = (int)(maxResizeFactor * sourceSize.Height);
using (var bitmapScaled = Bitmap.CreateScaledBitmap(image, height, width, true))
{
using (Stream outStream = File.Create(targetFile))
{
if (targetFile.ToLower().EndsWith("png"))
bitmapScaled.Compress(Bitmap.CompressFormat.Png, 100, outStream);
else
bitmapScaled.Compress(Bitmap.CompressFormat.Jpeg, 95, outStream);
}
bitmapScaled.Recycle();
}
}
image.Recycle();
}
else
Log.E("Image scaling failed: " + sourceFile);
}
}
}
}
#Sten's answer might encounter out-of-memory problem on some android devices. Here's my solution to implement the ResizeImage function
, which is according to google's "Loading Large Bitmaps Efficiently" document:
public void ResizeImage (string sourceFile, string targetFile, int reqWidth, int reqHeight)
{
if (!File.Exists (targetFile) && File.Exists (sourceFile)) {
var downImg = decodeSampledBitmapFromFile (sourceFile, reqWidth, reqHeight);
using (var outStream = File.Create (targetFile)) {
if (targetFile.ToLower ().EndsWith ("png"))
downImg.Compress (Bitmap.CompressFormat.Png, 100, outStream);
else
downImg.Compress (Bitmap.CompressFormat.Jpeg, 95, outStream);
}
downImg.Recycle();
}
}
public static Bitmap decodeSampledBitmapFromFile (string path, int reqWidth, int reqHeight)
{
// First decode with inJustDecodeBounds=true to check dimensions
var options = new BitmapFactory.Options ();
options.InJustDecodeBounds = true;
BitmapFactory.DecodeFile (path, options);
// Calculate inSampleSize
options.InSampleSize = calculateInSampleSize (options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.InJustDecodeBounds = false;
return BitmapFactory.DecodeFile (path, options);
}
public static int calculateInSampleSize (BitmapFactory.Options options, int reqWidth, int reqHeight)
{
// Raw height and width of image
int height = options.OutHeight;
int width = options.OutWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
int halfHeight = height / 2;
int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
You can do this natively for each platform and use an interface. Heres an example for IOS
In your PCL project you need to add an interface
public interface IImageResizer
{
byte[] ResizeImage (byte[] imageData, double width, double height);
}
Then to resize an image in your code, you can load the IOS implementation of that interface using the DependencyService and run the ResizeImage method
var resizer = DependencyService.Get<IImageResizer>();
var resizedBytes = resizer.ResizeImage (originalImageByteArray, 400, 400);
Stream stream = new MemoryStream(resizedBytes);
image.Source = ImageSource.FromStream(stream);
IOS Implementation, add this class to your IOS project.
[assembly: Xamarin.Forms.Dependency (typeof (ImageResizer_iOS))]
namespace YourNamespace
{
public class ImageResizer_iOS : IImageResizer
{
public byte[] ResizeImage (byte[] imageData, double maxWidth, double maxHeight)
{
UIImage originalImage = ImageFromByteArray (imageData);
double width = 300, height = 300;
double maxAspect = (double)maxWidth / (double)maxHeight;
double aspect = (double)originalImage.Size.Width/(double)originalImage.Size.Height;
if (maxAspect > aspect && originalImage.Size.Width > maxWidth) {
//Width is the bigger dimension relative to max bounds
width = maxWidth;
height = maxWidth / aspect;
}else if (maxAspect <= aspect && originalImage.Size.Height > maxHeight){
//Height is the bigger dimension
height = maxHeight;
width = maxHeight * aspect;
}
return originalImage.Scale(new SizeF((float)width,(float)height)).AsJPEG ().ToArray ();
}
public static MonoTouch.UIKit.UIImage ImageFromByteArray(byte[] data)
{
if (data == null) {
return null;
}
MonoTouch.UIKit.UIImage image;
try {
image = new MonoTouch.UIKit.UIImage(MonoTouch.Foundation.NSData.FromArray(data));
} catch (Exception e) {
Console.WriteLine ("Image load failed: " + e.Message);
return null;
}
return image;
}
}
}
An update from the Xamarin Media Plugin allows you to resize the image
https://github.com/jamesmontemagno/MediaPlugin
... barring that, and you need a more generic resize option (say the image comes from a web call, and not the device, then have a look at:
https://github.com/InquisitorJax/Wibci.Xamarin.Images
I am working on a project where i want to generate Bar-code based on an user-ID. I need a code which can generate bar-code and also is encrypted. I have found a few codes but they do not seem very helpful. Thank you in advance for help. i have tried this code but it does not provide me the barcode image.
`private void Page_Load(object sender, System.EventArgs e)
{
// Get the Requested code to be created.
string Code = Request["code"].ToString();
// Multiply the lenght of the code by 40 (just to have enough width)
int w = Code.Length * 40;
// Create a bitmap object of the width that we calculated and height of 100
Bitmap oBitmap = new Bitmap(w,100);
// then create a Graphic object for the bitmap we just created.
Graphics oGraphics = Graphics.FromImage(oBitmap);
// Now create a Font object for the Barcode Font
// (in this case the IDAutomationHC39M) of 18 point size
Font oFont = new Font("IDAutomationHC39M", 18);
// Let's create the Point and Brushes for the barcode
PointF oPoint = new PointF(2f, 2f);
SolidBrush oBrushWrite = new SolidBrush(Color.Black);
SolidBrush oBrush = new SolidBrush(Color.White);
// Now lets create the actual barcode image
// with a rectangle filled with white color
oGraphics.FillRectangle(oBrush, 0, 0, w, 100);
// We have to put prefix and sufix of an asterisk (*),
// in order to be a valid barcode
oGraphics.DrawString("*" + Code + "*", oFont, oBrushWrite, oPoint);
// Then we send the Graphics with the actual barcode
Response.ContentType = "image/jpeg" ;
oBitmap.Save (Response.OutputStream, ImageFormat.Jpeg);
}`
Check out this link it is a simple code 39 barcode display which supports a header and footer, printing, saving, and is pretty well customizable. For the encryption part you will have to encrypt your message before converting it to a barcode.
From the link.
Using the code The code is very simple to use, just plop the control
onto a form and you are ready to start customizing it via the
Properties window or through your code. In addition to the
properties, there are also two public functions of interest: public
void Print() This function will display a print dialog and then print
the contents of the control to the selected printer. public void
SaveImage(string filename) This function will save the contents of the
control to a bitmap image specified by filename.
http://www.codeproject.com/Articles/10344/Barcode-NET-Control
Please try Following Code you have to add "FREE3OF9.TTF" font file in your code
Default.aspx.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
////GenerateBarCode.GenerateBarCodes("dfdfdf", Label1);
GenerateBarCode();
}
}
private void GenerateBarCode()
{
WSBarcodeGenerator.BarCodeGenerator barCodeGen = new WSBarcodeGenerator.BarCodeGenerator();
int barSize = 30;
System.Byte[] imgBarcode =Code39("123456", barSize, true, "Centralbiz...");
MemoryStream memStream = new MemoryStream(imgBarcode);
Bitmap bitmap = new Bitmap(memStream);
bitmap.Save(memStream, ImageFormat.Png);
var base64Data = Convert.ToBase64String(memStream.ToArray());
imgBar.Attributes.Add("src", "data:image/png;base64," + base64Data);
//Response.Write(bitmap);
//var base64Data = Convert.ToBase64String(memStream.ToArray());
//imgBar.Attributes.Add("src", "png");
}
public byte[] Code39(string code, int barSize, bool showCodeString, string title)
{
Code39 c39 = new Code39();
// Create stream....
MemoryStream ms = new MemoryStream();
c39.FontFamilyName = "Free 3 of 9";
c39.FontFileName = Server.MapPath("FREE3OF9.TTF");
c39.FontSize = barSize;
c39.ShowCodeString = showCodeString;
if (title + "" != "")
c39.Title = title;
Bitmap objBitmap = c39.GenerateBarcode(code);
objBitmap.Save(ms, ImageFormat.Png);
//return bytes....
return ms.GetBuffer();
}
}
public class Code39
{
private const int _itemSepHeight = 3;
SizeF _titleSize = SizeF.Empty;
SizeF _barCodeSize = SizeF.Empty;
SizeF _codeStringSize = SizeF.Empty;
#region Barcode Title
private string _titleString = null;
private Font _titleFont = null;
public string Title
{
get { return _titleString; }
set { _titleString = value; }
}
public Font TitleFont
{
get { return _titleFont; }
set { _titleFont = value; }
}
#endregion
#region Barcode code string
private bool _showCodeString = false;
private Font _codeStringFont = null;
public bool ShowCodeString
{
get { return _showCodeString; }
set { _showCodeString = value; }
}
public Font CodeStringFont
{
get { return _codeStringFont; }
set { _codeStringFont = value; }
}
#endregion
#region Barcode Font
private Font _c39Font = null;
private float _c39FontSize = 12;
private string _c39FontFileName = null;
private string _c39FontFamilyName = null;
public string FontFileName
{
get { return _c39FontFileName; }
set { _c39FontFileName = value; }
}
public string FontFamilyName
{
get { return _c39FontFamilyName; }
set { _c39FontFamilyName = value; }
}
public float FontSize
{
get { return _c39FontSize; }
set { _c39FontSize = value; }
}
private Font Code39Font
{
get
{
if (_c39Font == null)
{
PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddFontFile(_c39FontFileName);
FontFamily family = new FontFamily(_c39FontFamilyName, pfc);
_c39Font = new Font(family, _c39FontSize);
}
return _c39Font;
}
}
#endregion
public Code39()
{
_titleFont = new Font("Arial", 10);
_codeStringFont = new Font("Arial", 10);
}
#region Barcode Generation
public Bitmap GenerateBarcode(string barCode)
{
int bcodeWidth = 0;
int bcodeHeight = 0;
// Get the image container...
Bitmap bcodeBitmap = CreateImageContainer(barCode, ref bcodeWidth, ref bcodeHeight);
Graphics objGraphics = Graphics.FromImage(bcodeBitmap);
// Fill the background
objGraphics.FillRectangle(new SolidBrush(Color.White), new Rectangle(0, 0, bcodeWidth, bcodeHeight));
int vpos = 0;
// Draw the title string
if (_titleString != null)
{
objGraphics.DrawString(_titleString, _titleFont, new SolidBrush(Color.Black), XCentered((int)_titleSize.Width, bcodeWidth), vpos);
vpos += (((int)_titleSize.Height) + _itemSepHeight);
}
// Draw the barcode
objGraphics.DrawString(barCode, Code39Font, new SolidBrush(Color.Black), XCentered((int)_barCodeSize.Width, bcodeWidth), vpos);
// Draw the barcode string
if (_showCodeString)
{
vpos += (((int)_barCodeSize.Height));
objGraphics.DrawString(barCode, _codeStringFont, new SolidBrush(Color.Black), XCentered((int)_codeStringSize.Width, bcodeWidth), vpos);
}
// return the image...
return bcodeBitmap;
}
private Bitmap CreateImageContainer(string barCode, ref int bcodeWidth, ref int bcodeHeight)
{
Graphics objGraphics;
// Create a temporary bitmap...
Bitmap tmpBitmap = new Bitmap(1, 1, PixelFormat.Format32bppArgb);
objGraphics = Graphics.FromImage(tmpBitmap);
// calculate size of the barcode items...
if (_titleString != null)
{
_titleSize = objGraphics.MeasureString(_titleString, _titleFont);
bcodeWidth = (int)_titleSize.Width;
bcodeHeight = (int)_titleSize.Height + _itemSepHeight;
}
_barCodeSize = objGraphics.MeasureString(barCode, Code39Font);
bcodeWidth = Max(bcodeWidth, (int)_barCodeSize.Width);
bcodeHeight += (int)_barCodeSize.Height;
if (_showCodeString)
{
_codeStringSize = objGraphics.MeasureString(barCode, _codeStringFont);
bcodeWidth = Max(bcodeWidth, (int)_codeStringSize.Width);
bcodeHeight += (_itemSepHeight + (int)_codeStringSize.Height);
}
// dispose temporary objects...
objGraphics.Dispose();
tmpBitmap.Dispose();
return (new Bitmap(bcodeWidth, bcodeHeight, PixelFormat.Format32bppArgb));
}
#endregion
#region Auxiliary Methods
private int Max(int v1, int v2)
{
return (v1 > v2 ? v1 : v2);
}
private int XCentered(int localWidth, int globalWidth)
{
return ((globalWidth - localWidth) / 2);
}
#endregion
}
Default.aspx code
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
</h2>
<p>
To learn more about ASP.NET visit www.asp.net.
</p>
<p>
You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&clcid=0x409"
title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
</p>
<asp:Image ID="imgBar" runat="server" />
</asp:Content>
I'm using Filestream for read big file (> 500 MB) and I get the OutOfMemoryException.
I use Asp.net , .net 3.5, win2003, iis 6.0
I want this in my app:
Read DATA from Oracle
Uncompress file using FileStream and BZip2
Read file uncompressed and send it to asp.net page for download.
When I read file from disk, Fails !!! and get OutOfMemory...
. My Code is:
using (var fs3 = new FileStream(filePath2, FileMode.Open, FileAccess.Read))
{
byte[] b2 = ReadFully(fs3, 1024);
}
// http://www.yoda.arachsys.com/csharp/readbinary.html
public static byte[] ReadFully(Stream stream, int initialLength)
{
// If we've been passed an unhelpful initial length, just
// use 32K.
if (initialLength < 1)
{
initialLength = 32768;
}
byte[] buffer = new byte[initialLength];
int read = 0;
int chunk;
while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
{
read += chunk;
// If we've reached the end of our buffer, check to see if there's
// any more information
if (read == buffer.Length)
{
int nextByte = stream.ReadByte();
// End of stream? If so, we're done
if (nextByte == -1)
{
return buffer;
}
// Nope. Resize the buffer, put in the byte we've just
// read, and continue
byte[] newBuffer = new byte[buffer.Length * 2];
Array.Copy(buffer, newBuffer, buffer.Length);
newBuffer[read] = (byte)nextByte;
buffer = newBuffer;
read++;
}
}
// Buffer is now too big. Shrink it.
byte[] ret = new byte[read];
Array.Copy(buffer, ret, read);
return ret;
}
Now, I specify my issue better.
Uncompress file using FileStream and BZip2 is OK, all is right.
The Problem is the following:
Read fat big file in disk (> 500 MB) in byte[] and send bytes to Response (asp.net) for download it.
When use
http://www.yoda.arachsys.com/csharp/readbinary.html
public static byte[] ReadFully
I get the error: OutOfMemoryException...
If better BufferedStream than Stream (FileStream, MemoryStream, ...) ??
Using BufferedStream , Can I read big file of 700 MB ?? (any sample code source using BufferedStream for download big file)
I think, this is the question: Not "how to read a 500mb file into memory?" , But "how to send a large file to the ASPNET Response stream?"
I found this code by Cheeso:
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
Response.BufferOutput= false; // to prevent buffering
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
{
Response.OutputStream.Write(buffer, 0, bytesRead);
}
}
Is it good code ?? any improvements for high performance ??
A collegue say me, use
Response.TransmitFile(filePath);
Now, another question, better TransmitFile or code by Cheeso ??
Many years ago, in msdn magazine appears great article about it but I cannot access http://msdn.microsoft.com/msdnmag/issues/06/09/WebDownloads/,
Update: You can access using webarchive in the link: https://web.archive.org/web/20070627063111/http://msdn.microsoft.com/msdnmag/issues/06/09/WebDownloads/
Any suggestions, comments, sample code source??
I've created download page which allows user to download up to 4gb (may be more) few months ago. Here is my working snippet:
private void TransmitFile(string fullPath, string outFileName)
{
System.IO.Stream iStream = null;
// Buffer to read 10K bytes in chunk:
byte[] buffer = new Byte[10000];
// Length of the file:
int length;
// Total bytes to read:
long dataToRead;
// Identify the file to download including its path.
string filepath = fullPath;
// Identify the file name.
string filename = System.IO.Path.GetFileName(filepath);
try
{
// Open the file.
iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
System.IO.FileAccess.Read, System.IO.FileShare.Read);
// Total bytes to read:
dataToRead = iStream.Length;
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + outFileName);
Response.AddHeader("Content-Length", iStream.Length.ToString());
// Read the bytes.
while (dataToRead > 0)
{
// Verify that the client is connected.
if (Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10000);
// Write the data to the current output stream.
Response.OutputStream.Write(buffer, 0, length);
// Flush the data to the output.
Response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
Response.Close();
}
}
You do not need to hold the whole file in memory just read it and write to the response stream in a loop.
I came across this question in my search to return a FileStreamResult from a controller, as I kept running into issues while working with large streams due to .Net trying to build the entire response all at once. Pavel Morshenyuk's answer was a huge help, but I figured I'd share the BufferedFileStreamResult that I ended up with.
/// <summary>Based upon https://stackoverflow.com/a/3363015/595473 </summary>
public class BufferedFileStreamResult : System.Web.Mvc.FileStreamResult
{
public BufferedFileStreamResult(System.IO.Stream stream, string contentType, string fileDownloadName)
: base(stream, contentType)
{
FileDownloadName = fileDownloadName;
}
public int BufferSize { get; set; } = 16 * 1024 * 1024;//--16MiB
protected override void WriteFile(System.Web.HttpResponseBase response)
{
try
{
response.Clear();
response.Headers.Set("Content-Disposition", $"attachment; filename={FileDownloadName}");
response.Headers.Set("Content-Length", FileStream.Length.ToString());
byte[] buffer;
int bytesRead;
while (response.IsClientConnected)//--Prevent infinite loop if user disconnects
{
buffer = new byte[BufferSize];
//--Read the data in buffer
if ((bytesRead = FileStream.Read(buffer, 0, BufferSize)) == 0)
{
break;//--Stop writing if there's nothing left to write
}
//--Write the data to the current output stream
response.OutputStream.Write(buffer, 0, bytesRead);
//--Flush the data to the output
response.Flush();
}
}
finally
{
FileStream?.Close();
response.Close();
}
}
}
Now, in my controller, I can just
return new BufferedFileStreamResult(stream, contentType, fileDownloadName);
There are more than one solution
1- Using RecyclableMemoryStream instead of MemoryStream solution
You can read more about RecyclableMemoryStream here :
http://www.philosophicalgeek.com/2015/02/06/announcing-microsoft-io-recycablememorystream/
https://github.com/Microsoft/Microsoft.IO.RecyclableMemoryStream
2- Using MemoryTributary instead of MemoryStream
You can read more about MemoryTributary here :
https://www.codeproject.com/Articles/348590/A-replacement-for-MemoryStream?msg=5257615#xx5257615xx
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
namespace LiquidEngine.Tools
{
/// <summary>
/// MemoryTributary is a re-implementation of MemoryStream that uses a dynamic list of byte arrays as a backing store, instead of a single byte array, the allocation
/// of which will fail for relatively small streams as it requires contiguous memory.
/// </summary>
public class MemoryTributary : Stream /* http://msdn.microsoft.com/en-us/library/system.io.stream.aspx */
{
#region Constructors
public MemoryTributary()
{
Position = 0;
}
public MemoryTributary(byte[] source)
{
this.Write(source, 0, source.Length);
Position = 0;
}
/* length is ignored because capacity has no meaning unless we implement an artifical limit */
public MemoryTributary(int length)
{
SetLength(length);
Position = length;
byte[] d = block; //access block to prompt the allocation of memory
Position = 0;
}
#endregion
#region Status Properties
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return true; }
}
public override bool CanWrite
{
get { return true; }
}
#endregion
#region Public Properties
public override long Length
{
get { return length; }
}
public override long Position { get; set; }
#endregion
#region Members
protected long length = 0;
protected long blockSize = 65536;
protected List<byte[]> blocks = new List<byte[]>();
#endregion
#region Internal Properties
/* Use these properties to gain access to the appropriate block of memory for the current Position */
/// <summary>
/// The block of memory currently addressed by Position
/// </summary>
protected byte[] block
{
get
{
while (blocks.Count <= blockId)
blocks.Add(new byte[blockSize]);
return blocks[(int)blockId];
}
}
/// <summary>
/// The id of the block currently addressed by Position
/// </summary>
protected long blockId
{
get { return Position / blockSize; }
}
/// <summary>
/// The offset of the byte currently addressed by Position, into the block that contains it
/// </summary>
protected long blockOffset
{
get { return Position % blockSize; }
}
#endregion
#region Public Stream Methods
public override void Flush()
{
}
public override int Read(byte[] buffer, int offset, int count)
{
long lcount = (long)count;
if (lcount < 0)
{
throw new ArgumentOutOfRangeException("count", lcount, "Number of bytes to copy cannot be negative.");
}
long remaining = (length - Position);
if (lcount > remaining)
lcount = remaining;
if (buffer == null)
{
throw new ArgumentNullException("buffer", "Buffer cannot be null.");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset",offset,"Destination offset cannot be negative.");
}
int read = 0;
long copysize = 0;
do
{
copysize = Math.Min(lcount, (blockSize - blockOffset));
Buffer.BlockCopy(block, (int)blockOffset, buffer, offset, (int)copysize);
lcount -= copysize;
offset += (int)copysize;
read += (int)copysize;
Position += copysize;
} while (lcount > 0);
return read;
}
public override long Seek(long offset, SeekOrigin origin)
{
switch (origin)
{
case SeekOrigin.Begin:
Position = offset;
break;
case SeekOrigin.Current:
Position += offset;
break;
case SeekOrigin.End:
Position = Length - offset;
break;
}
return Position;
}
public override void SetLength(long value)
{
length = value;
}
public override void Write(byte[] buffer, int offset, int count)
{
long initialPosition = Position;
int copysize;
try
{
do
{
copysize = Math.Min(count, (int)(blockSize - blockOffset));
EnsureCapacity(Position + copysize);
Buffer.BlockCopy(buffer, (int)offset, block, (int)blockOffset, copysize);
count -= copysize;
offset += copysize;
Position += copysize;
} while (count > 0);
}
catch (Exception e)
{
Position = initialPosition;
throw e;
}
}
public override int ReadByte()
{
if (Position >= length)
return -1;
byte b = block[blockOffset];
Position++;
return b;
}
public override void WriteByte(byte value)
{
EnsureCapacity(Position + 1);
block[blockOffset] = value;
Position++;
}
protected void EnsureCapacity(long intended_length)
{
if (intended_length > length)
length = (intended_length);
}
#endregion
#region IDispose
/* http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx */
protected override void Dispose(bool disposing)
{
/* We do not currently use unmanaged resources */
base.Dispose(disposing);
}
#endregion
#region Public Additional Helper Methods
/// <summary>
/// Returns the entire content of the stream as a byte array. This is not safe because the call to new byte[] may
/// fail if the stream is large enough. Where possible use methods which operate on streams directly instead.
/// </summary>
/// <returns>A byte[] containing the current data in the stream</returns>
public byte[] ToArray()
{
long firstposition = Position;
Position = 0;
byte[] destination = new byte[Length];
Read(destination, 0, (int)Length);
Position = firstposition;
return destination;
}
/// <summary>
/// Reads length bytes from source into the this instance at the current position.
/// </summary>
/// <param name="source">The stream containing the data to copy</param>
/// <param name="length">The number of bytes to copy</param>
public void ReadFrom(Stream source, long length)
{
byte[] buffer = new byte[4096];
int read;
do
{
read = source.Read(buffer, 0, (int)Math.Min(4096, length));
length -= read;
this.Write(buffer, 0, read);
} while (length > 0);
}
/// <summary>
/// Writes the entire stream into destination, regardless of Position, which remains unchanged.
/// </summary>
/// <param name="destination">The stream to write the content of this stream to</param>
public void WriteTo(Stream destination)
{
long initialpos = Position;
Position = 0;
this.CopyTo(destination);
Position = initialpos;
}
#endregion
}
}